Passed
Push — master ( b38da1...a59646 )
by Dāvis
04:33
created

PaginationExtension::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Pagination\Twig;
4
5
use Sludio\HelperBundle\Pagination\Twig\Behaviour\BehaviourInterface;
6
use Sludio\HelperBundle\Pagination\Twig\Behaviour\FixedLength;
7
8
class PaginationExtension extends \Twig_Extension
9
{
10
    /**
11
     * @var BehaviourInterface[]
12
     */
13
    private $functions;
14
15
    public function __construct($container, $shortFunctions)
16
    {
17
        $this->functions = [];
18
        if ($container->hasParameter('sludio_helper.pagination.behaviour') && !empty($container->getParameter('sludio_helper.pagination.behaviour', []))) {
19
            $functions = $container->getParameter('sludio_helper.pagination.behaviour');
20
            /** @var $functions array */
21
            foreach ($functions as $function) {
22
                if ($shortFunctions) {
23
                    $this->functions[] = $this->withFunction(array_keys($function)[0], array_values($function)[0]);
24
                }
25
                $this->functions[] = $this->withFunction('sludio_'.array_keys($function)[0], array_values($function)[0]);
26
            }
27
        }
28
    }
29
30
    public function withFunction($functionName, $behaviour)
31
    {
32
        $functionName = $this->suffixFunctionName($functionName);
33
        $behaviour = new FixedLength($behaviour);
34
35
        $clone = clone $this;
36
37
        $clone->functions[$functionName] = new \Twig_SimpleFunction($functionName, [
38
            $behaviour,
39
            'getPaginationData',
40
        ]);
41
42
        return $clone->functions[$functionName];
43
    }
44
45
    /**
46
     * @param string $functionName
47
     *
48
     * @return string
49
     */
50
    private function suffixFunctionName($functionName)
51
    {
52
        // Make sure the function name is not suffixed twice.
53
        $functionName = (string)preg_replace('/(_pagination)$/', '', (string)$functionName);
54
55
        return $functionName.'_pagination';
56
    }
57
58
    public function withoutFunction($functionName)
59
    {
60
        $functionName = $this->suffixFunctionName($functionName);
61
62
        $clone = clone $this;
63
        unset($clone->functions[$functionName]);
64
65
        return $clone;
66
    }
67
68
    /**
69
     * @return \Twig_SimpleFunction[]
70
     */
71
    public function getFunctions()
72
    {
73
        return array_values($this->functions);
74
    }
75
}
76