Skip to content

Commit

Permalink
[String] fix slicing in UnicodeString
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Oct 21, 2020
1 parent b3a1bc0 commit 4e6d0f5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
31 changes: 31 additions & 0 deletions Tests/AbstractAsciiTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,37 @@ public static function provideSlice()
['awesome', 'Symfony is awesome', 11, 7],
['awesome', 'Symfony is awesome', -7, null],
['awe', 'Symfony is awesome', -7, -4],
['S', 'Symfony is awesome', -42, 1],
['', 'Symfony is awesome', 42, 1],
['', 'Symfony is awesome', 0, -42],
];
}

/**
* @dataProvider provideSplice
*/
public function testSplice(string $expected, int $start, int $length = null)
{
$this->assertEquals(
static::createFromString($expected),
static::createFromString('Symfony is awesome')->splice('X', $start, $length)
);
}

public static function provideSplice()
{
return [
['X is awesome', 0, 7],
['SymfonyXis awesome', 7, 1],
['Symfony X awesome', 8, 2],
['Symfony X', 8, null],
['Symfony isXawesome', 10, 1],
['Symfony is X', 11, 7],
['Symfony is X', -7, null],
['Symfony is Xsome', -7, -4],
['Xymfony is awesome', -42, 1],
['Symfony is awesomeX', 42, 1],
['XSymfony is awesome', 0, -42],
];
}

Expand Down
12 changes: 8 additions & 4 deletions UnicodeString.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,18 +267,22 @@ public function replaceMatches(string $fromRegexp, $to): AbstractString
public function slice(int $start = 0, int $length = null): AbstractString
{
$str = clone $this;
try {
$str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
} catch (\ValueError $e) {
$str->string = '';

if (\PHP_VERSION_ID < 80000 && 0 > $start && grapheme_strlen($this->string) < -$start) {
$start = 0;
}
$str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);

return $str;
}

public function splice(string $replacement, int $start = 0, int $length = null): AbstractString
{
$str = clone $this;

if (\PHP_VERSION_ID < 80000 && 0 > $start && grapheme_strlen($this->string) < -$start) {
$start = 0;
}
$start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
$length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? 2147483647)) : $length;
$str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647);
Expand Down

0 comments on commit 4e6d0f5

Please sign in to comment.