Skip to content

Commit 34b9b3f

Browse files
committed
fix(Helpers): prevent TypeError in excerpt() when phrase is not found or radius is odd
1 parent 49e5001 commit 34b9b3f

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎system/Helpers/text_helper.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -717,8 +717,12 @@ function excerpt(string $text, ?string $phrase = null, int $radius = 100, string
717717
if (isset($phrase)) {
718718
$phrasePosition = mb_stripos($text, $phrase);
719719
$phraseLength = mb_strlen($phrase);
720+
721+
if ($phrasePosition === false) {
722+
return excerpt($text, null, $radius, $ellipsis);
723+
}
720724
} else {
721-
$phrasePosition = $radius / 2;
725+
$phrasePosition = (int) ($radius / 2);
722726
$phraseLength = 1;
723727
}
724728

‎tests/system/Helpers/TextHelperTest.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,24 @@ public function testExcerptRadius(): void
450450
$this->assertSame($multibyteResult, excerpt($this->mbLongString, 'печально', 10));
451451
}
452452

453+
public function testExcerptPhraseNotFound(): void
454+
{
455+
$result = ' Once upon a time, a framework had no tests. It sad So some nice people began to write tests. The more time that went on, the happier it became. ...';
456+
$this->assertSame($result, excerpt($this->longString, 'nonexistent'));
457+
458+
$multibyteResult = ' Давным-давно во фреймворке не было тестов. Это печ льно. И вот несколько хороших людей начали писать тесты. Чем больше времени проходило, тем ...';
459+
$this->assertSame($multibyteResult, excerpt($this->mbLongString, 'несуществующее'));
460+
}
461+
462+
public function testExcerptOddRadius(): void
463+
{
464+
$result = ' Once upon a time, a framework had no tests. It sad So some nice people began to write tests. The more time that went on, the happier it became. ...';
465+
$this->assertSame($result, excerpt($this->longString, null, 101));
466+
467+
$multibyteResult = ' Давным-давно во фреймворке не было тестов. Это печ льно. И вот несколько хороших людей начали писать тесты. Чем больше времени проходило, тем ...';
468+
$this->assertSame($multibyteResult, excerpt($this->mbLongString, null, 101));
469+
}
470+
453471
public function testAlternator(): void
454472
{
455473
$phrase = ' scream! ';

0 commit comments

Comments
 (0)