Skip to content

Commit f174d04

Browse files
committed
fix(Helpers): clamp position and handle float 1.0 in ellipsize()
1 parent ff76fcf commit f174d04

2 files changed

Lines changed: 21 additions & 8 deletions

File tree

‎system/Helpers/text_helper.php‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -437,14 +437,10 @@ function ellipsize(string $str, int $maxLength, $position = 1, string $ellipsis
437437
return $str;
438438
}
439439

440-
$beg = mb_substr($str, 0, (int) floor($maxLength * $position));
441-
$position = ($position > 1) ? 1 : $position;
442-
443-
if ($position === 1) {
444-
$end = mb_substr($str, 0, -($maxLength - mb_strlen($beg)));
445-
} else {
446-
$end = mb_substr($str, -($maxLength - mb_strlen($beg)));
447-
}
440+
$position = max(0.0, min(1.0, (float) $position));
441+
$beg = mb_substr($str, 0, (int) floor($maxLength * $position));
442+
$remaining = $maxLength - mb_strlen($beg);
443+
$end = $remaining > 0 ? mb_substr($str, -$remaining) : '';
448444

449445
return $beg . $ellipsis . $end;
450446
}

‎tests/system/Helpers/TextHelperTest.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,23 @@ public function testEllipsize(): void
358358
}
359359
}
360360

361+
#[DataProvider('provideEllipsizePositionEdgeCases')]
362+
public function testEllipsizePositionEdgeCases(float|int $position, string $expected): void
363+
{
364+
$this->assertSame($expected, ellipsize('this is my string', 10, $position));
365+
}
366+
367+
/**
368+
* @return iterable<string, array{float|int, string}>
369+
*/
370+
public static function provideEllipsizePositionEdgeCases(): iterable
371+
{
372+
yield 'float one' => [1.0, 'this is my&hellip;'];
373+
yield 'greater than one (int)' => [2, 'this is my&hellip;'];
374+
yield 'greater than one (float)' => [1.5, 'this is my&hellip;'];
375+
yield 'negative float' => [-0.5, '&hellip; my string'];
376+
}
377+
361378
/**
362379
* A character limit below 2 used to make word_wrap() loop forever.
363380
*/

0 commit comments

Comments
 (0)