Skip to content

Commit

Permalink
Improve str::limit function
Browse files Browse the repository at this point in the history
  • Loading branch information
martialblog committed Aug 12, 2024
1 parent c4066bd commit c664fc4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions library/Toplevelview/Util/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ class Str
*/
public static function limit($str, $len = 25, $end = '...'): string
{
if (empty($str)) {
return '';
}

// If the string is smaller or equal to the limit we simply return it
if (mb_strwidth($str, 'UTF-8') <= $len) {
return $str;
Expand Down
13 changes: 13 additions & 0 deletions test/php/library/Toplevelview/Util/StrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ final class StrTest extends TestCase
{
public function testLimitWithSmallerString()
{
$this->assertSame('', Str::limit(null));
$this->assertSame('', Str::limit(''));
$this->assertSame('noop', Str::limit('noop'));
}
Expand All @@ -19,6 +20,10 @@ public function testLimitWithLongerStringAndSpecificLimit()
'Lorem ipsu...',
Str::limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 10)
);
$this->assertSame(
'🍔🍔🍔🍔🍔...',
Str::limit('🍔🍔🍔🍔🍔🍔🍔🍔', 10)
);
}

public function testLimitWithLongerStringAndSpecificEnd()
Expand All @@ -27,5 +32,13 @@ public function testLimitWithLongerStringAndSpecificEnd()
'L (...)',
Str::limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 1, ' (...)')
);
$this->assertSame(
'К (...)',
Str::limit('Кто это читает, тот дурак', 1, ' (...)')
);
$this->assertSame(
'К (🦔🦔🦔)',
Str::limit('Кто это читает, тот дурак', 1, ' (🦔🦔🦔)')
);
}
}

0 comments on commit c664fc4

Please sign in to comment.