Completed
Push — 3.x ( b0e4d8...846f8c )
by Grégoire
03:01
created

StringExtension   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 36
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getFilters() 0 12 2
A legacyTruncteWithUnicodeString() 0 4 1
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