Completed
Push — ezp_31440 ( 87ccef )
by
unknown
18:57 queued 03:24
created

QueryRenderingExtension::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace eZ\Publish\Core\MVC\Symfony\Templating\Twig\Extension;
6
7
use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException;
8
use Symfony\Component\HttpKernel\Controller\ControllerReference;
9
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
10
use Twig\Extension\AbstractExtension;
11
use Twig\TwigFunction;
12
13
class QueryRenderingExtension extends AbstractExtension
14
{
15
    /** @var \Symfony\Component\HttpKernel\Fragment\FragmentHandler */
16
    private $fragmentHandler;
17
18
    /** @var string[] */
19
    private $controllerMap;
20
21
    public function __construct(FragmentHandler $fragmentHandler, array $controllerMap)
22
    {
23
        $this->fragmentHandler = $fragmentHandler;
24
        $this->controllerMap = $controllerMap;
25
    }
26
27
    public function getFunctions(): array
28
    {
29
        return [
30
            new TwigFunction(
31
                'ez_render_*_query',
32
                function (string $type, array $options) {
33
                    return $this->fragmentHandler->render(
34
                        $this->createControllerReference($type, $options),
35
                        'inline'
36
                    );
37
                },
38
                ['is_safe' => ['html']]
39
            ),
40
            new TwigFunction(
41
                'ez_render_*_query_*',
42
                function (string $type, string $renderer, array $options) {
43
                    return $this->fragmentHandler->render(
44
                        $this->createControllerReference($type, $options),
45
                        $renderer
46
                    );
47
                },
48
                ['is_safe' => ['html']]
49
            ),
50
        ];
51
    }
52
53
    private function createControllerReference(string $type, array $options): ControllerReference
54
    {
55
        $controller = $this->controllerMap[$type] ?? null;
56
57
        if ($controller === null) {
58
            throw new InvalidArgumentException(
59
                '$type',
60
                'Expected value to be of ' . implode(',', array_keys($this->controllerMap))
61
            );
62
        }
63
64
        return new ControllerReference($controller, [
65
            'options' => $options,
66
        ]);
67
    }
68
}
69