1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Sonata Project package. |
7
|
|
|
* |
8
|
|
|
* (c) Thomas Rabaix <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Sonata\AdminBundle\Twig\Extension; |
15
|
|
|
|
16
|
|
|
use Symfony\Component\String\UnicodeString as DecoratedUnicodeString; |
17
|
|
|
use Twig\Extension\AbstractExtension; |
18
|
|
|
use Twig\Extensions\TextExtension; |
19
|
|
|
use Twig\TwigFilter; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Decorates `Twig\Extra\String\StringExtension` in order to provide the `$cut` |
23
|
|
|
* argument for `Symfony\Component\String\UnicodeString::truncate()`. |
24
|
|
|
* This class must be removed when the component ships this feature. |
25
|
|
|
* |
26
|
|
|
* @internal |
27
|
|
|
* |
28
|
|
|
* @see https://github.com/symfony/symfony/pull/35649 |
29
|
|
|
* |
30
|
|
|
* @author Javier Spagnoletti <[email protected]> |
31
|
|
|
*/ |
32
|
|
|
final class StringExtension extends AbstractExtension |
33
|
|
|
{ |
34
|
|
|
/** |
35
|
|
|
* @var TextExtension |
36
|
|
|
*/ |
37
|
|
|
private $legacyExtension; |
38
|
|
|
|
39
|
|
|
public function __construct(TextExtension $legacyExtension = null) |
40
|
|
|
{ |
41
|
|
|
$this->legacyExtension = $legacyExtension; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @return TwigFilter[] |
46
|
|
|
*/ |
47
|
|
|
public function getFilters(): array |
48
|
|
|
{ |
49
|
|
|
if (null !== $this->legacyExtension) { |
50
|
|
|
return [ |
51
|
|
|
new TwigFilter('sonata_truncate', 'twig_truncate_filter', ['needs_environment' => true]), |
52
|
|
|
]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return [ |
56
|
|
|
new TwigFilter('sonata_truncate', [$this, 'legacyTruncteWithUnicodeString']), |
57
|
|
|
]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* NEXT_MAJOR: Fix the arguments in order to respect the signature at `UnicodeString::truncate()`. |
62
|
|
|
*/ |
63
|
|
|
public function legacyTruncteWithUnicodeString(?string $text, int $length = 30, bool $preserve = false, string $ellipsis = '...'): DecoratedUnicodeString |
64
|
|
|
{ |
65
|
|
|
return (new UnicodeString($text ?? ''))->truncate($length, $ellipsis, $preserve); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|