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

UnicodeString::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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\Exception\ExceptionInterface;
17
use Symfony\Component\String\UnicodeString as DecoratedUnicodeString;
18
19
/**
20
 * Decorates `Symfony\Component\String\UnicodeString` in order to provide the `$cut`
21
 * argument for `truncate()`. This class must be removed when the component ships
22
 * this feature.
23
 *
24
 * @see https://github.com/symfony/symfony/pull/35649
25
 *
26
 * @throws ExceptionInterface
27
 *
28
 * @author Javier Spagnoletti <[email protected]>
29
 */
30
final class UnicodeString
31
{
32
    /**
33
     * @var DecoratedUnicodeString
34
     */
35
    private $unicodeString;
36
37
    public function __construct(string $string = '')
38
    {
39
        $this->unicodeString = new DecoratedUnicodeString($string);
40
    }
41
42
    public function __call($name, $arguments)
43
    {
44
        return $this->unicodeString->$name(...$arguments);
45
    }
46
47
    public function __toString(): string
48
    {
49
        return (string) $this->unicodeString;
50
    }
51
52
    public function truncate(int $length, string $ellipsis = '', bool $preserve = false): DecoratedUnicodeString
53
    {
54
        $stringLength = $this->unicodeString->length();
55
56
        if ($stringLength <= $length) {
57
            return clone $this->unicodeString;
58
        }
59
60
        $ellipsisLength = '' !== $ellipsis ? (new DecoratedUnicodeString($ellipsis))->length() : 0;
61
62
        if ($length < $ellipsisLength) {
63
            $ellipsisLength = 0;
64
        }
65
66
        if ($preserve) {
67
            $length = $ellipsisLength + ($this->unicodeString->indexOf([' ', "\r", "\n", "\t"], ($length ?: 1) - 1) ?? $stringLength);
68
        }
69
70
        $str = $this->unicodeString->slice(0, $length - $ellipsisLength);
71
72
        return $ellipsisLength ? $str->trimEnd()->append($ellipsis) : $str;
73
    }
74
}
75