Skip to content

Commit

Permalink
bug #394 [Php80] Fix str_ends_with() when needle is longer than hayst…
Browse files Browse the repository at this point in the history
…ack (SpacePossum)

This PR was squashed before being merged into the 1.23-dev branch.

Discussion
----------

[Php80] Fix str_ends_with() when needle is longer than haystack

Little bug, found in PHP-CS-Fixer/PHP-CS-Fixer#6323

https://3v4l.org/oHUKH

```php
<?php
error_reporting(E_ALL);
$needle = '[]';
echo \substr_compare('', $needle, -\strlen($needle));
```

show issues for

```
Output for 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.17, 7.3.0 - 7.3.4
Warning: substr_compare(): The start position cannot exceed initial string length in /in/oHUKH on line 4
```

Looking at the test matrix I assume the tests will run latest 7.2 which is not effected,
~so I naively changed it here in this draft to see if my test indeeds fails on the CI (I don't have an easy 7.2.17 or 7.1.0 env. at hand at the moment)~ @ see shivammathur/setup-php#570

Commits
-------

09a94a5 [Php80] Fix str_ends_with() when needle is longer than haystack
  • Loading branch information
nicolas-grekas committed Mar 4, 2022
2 parents 329cde9 + 09a94a5 commit 31c7c7f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# 1.25.0

* Add `PhpToken` to the PHP 8.0 polyfill when the tokenizer extension is enabled
* Fix `str_ends_with()` when needle is longer than haystack

# 1.24.0

Expand Down
12 changes: 11 additions & 1 deletion src/Php80/Php80.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@ public static function str_starts_with(string $haystack, string $needle): bool

public static function str_ends_with(string $haystack, string $needle): bool
{
return '' === $needle || ('' !== $haystack && 0 === substr_compare($haystack, $needle, -\strlen($needle)));
if ('' === $needle || $needle === $haystack) {
return true;
}

if ('' === $haystack) {
return false;
}

$needleLength = \strlen($needle);

return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength);
}
}
2 changes: 2 additions & 0 deletions tests/Php80/Php80Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ public function testStrEndsWith()
$testEmoji = '🙌🎉✨🚀'; // 0xf0 0x9f 0x99 0x8c 0xf0 0x9f 0x8e 0x89 0xe2 0x9c 0xa8 0xf0 0x9f 0x9a 0x80
$this->assertTrue(str_ends_with($testEmoji, '🚀')); // 0xf0 0x9f 0x9a 0x80
$this->assertFalse(str_ends_with($testEmoji, '✨')); // 0xe2 0x9c 0xa8

$this->assertFalse(str_ends_with('', '[]'));
}

/**
Expand Down

0 comments on commit 31c7c7f

Please sign in to comment.