Skip to content

[Php80] Skip possibly empty needle in StrEndsWithRector - #9034

Closed
TomasVotruba wants to merge 1 commit into
mainfrom
str-ends-with-empty-needle
Closed

TomasVotruba wants to merge 1 commit into
mainfrom
str-ends-with-empty-needle

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

StrEndsWithRector changes behavior when the needle can be empty, or when a loose comparison meets a numeric string.

Empty needle - substr('abc', -strlen('')) is substr('abc', -0), which is 'abc', not ''. substr_compare('abc', '', 0) returns 1. Both originals are false, but str_ends_with('abc', '') is true.

// before - false for $needle = ''
substr($haystack, -strlen($needle)) === $needle;
substr_compare($haystack, $needle, -strlen($needle)) === 0;

// after - true for $needle = ''
str_ends_with($haystack, $needle);

Loose numeric - with haystack 'x010' and needle '1e1', '010' == '1e1' is true (both compare as 10), but str_ends_with('x010', '1e1') is false.

Fix

  • Rewrite only when the needle is known to be non-empty: a non-empty literal, or a non-empty-string type. The type comes from the PHPStan scope, because getType() turns non-empty-string into plain string.
  • For ==/!= on the substr() form, also require that the needle is not a numeric string. A non-numeric literal like 'foo' still converts.

Fixtures

  • Added skip_empty_needle and skip_loose_numeric.
  • Fixtures that used an untyped $needle now declare @param non-empty-string $needle, so they still convert.
  • The loose substr() fixtures with an untyped needle (fixture_equal, substr_not_equal_prefix) are now skips (skip_fixture_equal, skip_substr_not_equal_prefix).

So the rule now skips the common -strlen($needle) pattern whenever $needle is a plain string. That is intended: the old rewrite was only safe when the needle could not be empty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant