Skip to content

Commit 4e6d0f5

Browse files
[String] fix slicing in UnicodeString
1 parent b3a1bc0 commit 4e6d0f5

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

Tests/AbstractAsciiTestCase.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,37 @@ public static function provideSlice()
597597
['awesome', 'Symfony is awesome', 11, 7],
598598
['awesome', 'Symfony is awesome', -7, null],
599599
['awe', 'Symfony is awesome', -7, -4],
600+
['S', 'Symfony is awesome', -42, 1],
601+
['', 'Symfony is awesome', 42, 1],
602+
['', 'Symfony is awesome', 0, -42],
603+
];
604+
}
605+
606+
/**
607+
* @dataProvider provideSplice
608+
*/
609+
public function testSplice(string $expected, int $start, int $length = null)
610+
{
611+
$this->assertEquals(
612+
static::createFromString($expected),
613+
static::createFromString('Symfony is awesome')->splice('X', $start, $length)
614+
);
615+
}
616+
617+
public static function provideSplice()
618+
{
619+
return [
620+
['X is awesome', 0, 7],
621+
['SymfonyXis awesome', 7, 1],
622+
['Symfony X awesome', 8, 2],
623+
['Symfony X', 8, null],
624+
['Symfony isXawesome', 10, 1],
625+
['Symfony is X', 11, 7],
626+
['Symfony is X', -7, null],
627+
['Symfony is Xsome', -7, -4],
628+
['Xymfony is awesome', -42, 1],
629+
['Symfony is awesomeX', 42, 1],
630+
['XSymfony is awesome', 0, -42],
600631
];
601632
}
602633

UnicodeString.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -267,18 +267,22 @@ public function replaceMatches(string $fromRegexp, $to): AbstractString
267267
public function slice(int $start = 0, int $length = null): AbstractString
268268
{
269269
$str = clone $this;
270-
try {
271-
$str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
272-
} catch (\ValueError $e) {
273-
$str->string = '';
270+
271+
if (\PHP_VERSION_ID < 80000 && 0 > $start && grapheme_strlen($this->string) < -$start) {
272+
$start = 0;
274273
}
274+
$str->string = (string) grapheme_substr($this->string, $start, $length ?? 2147483647);
275275

276276
return $str;
277277
}
278278

279279
public function splice(string $replacement, int $start = 0, int $length = null): AbstractString
280280
{
281281
$str = clone $this;
282+
283+
if (\PHP_VERSION_ID < 80000 && 0 > $start && grapheme_strlen($this->string) < -$start) {
284+
$start = 0;
285+
}
282286
$start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
283287
$length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? 2147483647)) : $length;
284288
$str->string = substr_replace($this->string, $replacement, $start, $length ?? 2147483647);

0 commit comments

Comments
 (0)