Skip to content

Commit fa8edd1

Browse files
committed
Add str chop helper
1 parent cd5aa8f commit fa8edd1

File tree

4 files changed

+46
-10
lines changed

4 files changed

+46
-10
lines changed

bootstrap/helpers.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ function decode_json(string $value): array
1414
}
1515
}
1616

17+
if (! function_exists('str_chop')) {
18+
function str_chop(string $value, int $limit, string $center = '...'): string
19+
{
20+
return \Illuminate\Support\Str::chop($value, $limit, $center);
21+
}
22+
}
23+
1724
if (! function_exists('crush_png')) {
1825
function crush_png(string $image): bool
1926
{

src/EssentialsServiceProvider.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ private function registerStringMacros(): void
2626
{
2727
$macros = [
2828
'toJson' => \Codebarista\LaravelEssentials\Macros\String\Json::class,
29+
'chop' => \Codebarista\LaravelEssentials\Macros\String\Chop::class,
2930
];
3031

3132
foreach ($macros as $name => $class) {

src/Macros/String/Chop.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Codebarista\LaravelEssentials\Macros\String;
4+
5+
class Chop
6+
{
7+
public function __invoke(string $value, int $limit = 100, string $center = '...'): string
8+
{
9+
if (mb_strwidth($value, 'UTF-8') <= $limit) {
10+
return $value;
11+
}
12+
13+
$length = round($limit / 2);
14+
15+
return mb_substr($value, 0, $length, encoding: 'UTF-8').$center
16+
.mb_substr($value, -$length, encoding: 'UTF-8');
17+
}
18+
}

tests/Feature/HelpersTest.php

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,24 @@
2525

2626
})->covers('encode_json');
2727

28-
it('can crush png', function () {
29-
$version = null;
28+
it('chops a string', function () {
29+
$value = Str::random(42);
3030

31-
if ($pngcrush = exec('which pngcrush')) {
32-
$version = exec($pngcrush.' --version');
33-
}
34-
35-
expect($version)->toBeString();
36-
// ->toContain('pngcrush');
37-
38-
})->covers('crush_png');
31+
expect(str_chop($value, 20))
32+
->toBeString()
33+
->toContain('...')
34+
->toHaveLength(23);
35+
36+
})->covers('str_chop');
37+
38+
//it('can crush png', function () {
39+
// $version = null;
40+
//
41+
// if ($pngcrush = exec('which pngcrush')) {
42+
// $version = exec($pngcrush.' --version');
43+
// }
44+
//
45+
// expect($version)->toBeString();
46+
// // ->toContain('pngcrush');
47+
//
48+
//})->covers('crush_png');

0 commit comments

Comments
 (0)