Completed
Push — master ( 74371a...6da8c0 )
by Vladimir
02:21
created

TruncateFilter::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Templating\Twig\Extension;
9
10
/**
11
 * This filter is adapted from the Twig Text extension.
12
 *
13
 * @copyright 2009 Fabien Potencier
14
 * @author Henrik Bjornskov <[email protected]>
15
 * @see https://github.com/twigphp/Twig-extensions
16
 */
17
class TruncateFilter extends AbstractTwigExtension implements TwigFilterInterface
18
{
19
    public function __invoke(\Twig_Environment $env, $value, $length = 30, $preserve = false, $separator = '...')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
20
    {
21
        if (mb_strlen($value, $env->getCharset()) > $length)
22
        {
23
            if ($preserve)
24
            {
25
                // If breakpoint is on the last word, return the value without separator.
26
                if (false === ($breakpoint = mb_strpos($value, ' ', $length, $env->getCharset())))
27
                {
28
                    return $value;
29
                }
30
31
                $length = $breakpoint;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $length. This often makes code more readable.
Loading history...
32
            }
33
34
            return rtrim(mb_substr($value, 0, $length, $env->getCharset())) . $separator;
35
        }
36
37
        return $value;
38
    }
39
40
    /**
41
     * @return \Twig_SimpleFilter
42
     */
43
    public static function get()
44
    {
45
        return new \Twig_SimpleFilter('truncate', new self(), [
46
            'needs_environment' => true,
47
        ]);
48
    }
49
}
50