-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTruncate.php
More file actions
42 lines (36 loc) · 1.04 KB
/
Truncate.php
File metadata and controls
42 lines (36 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
declare(strict_types=1);
namespace Kiboko\Component\StringExpressionLanguage;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
final class Truncate extends ExpressionFunction
{
public function __construct($name)
{
parent::__construct(
$name,
\Closure::fromCallable($this->compile(...))->bindTo($this),
\Closure::fromCallable($this->evaluate(...))->bindTo($this)
);
}
private function compile(string $input, string $limit): string
{
return <<<PHP
(
mb_strlen({$input}) > {$limit} ?
(
rtrim(mb_substr({$input}, 0, {$limit} - 1)) . '…'
) : {$input}
)
PHP;
}
/**
* @param array<string, mixed> $context
*/
private function evaluate(array $context, string $input, int $limit): string
{
return mb_strlen($input) > $limit ?
(
rtrim(mb_substr($input, 0, $limit - 1)).'…'
) : $input;
}
}