Completed
Push — symfony5 ( 074008...b11eb2 )
by
unknown
267:19 queued 255:17
created

QueryRenderingExtension::getFunctions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 28
rs 9.472
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace eZ\Publish\Core\MVC\Symfony\Templating\Twig\Extension;
10
11
use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException;
12
use Symfony\Component\HttpKernel\Controller\ControllerReference;
13
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
14
use Twig\Extension\AbstractExtension;
15
use Twig\TwigFunction;
16
17
class QueryRenderingExtension extends AbstractExtension
18
{
19
    private const VALID_TYPES = ['content', 'location'];
20
21
    /** @var \Symfony\Component\HttpKernel\Fragment\FragmentHandler */
22
    private $fragmentHandler;
23
24
    public function __construct(FragmentHandler $fragmentHandler)
25
    {
26
        $this->fragmentHandler = $fragmentHandler;
27
    }
28
29
    public function getFunctions(): array
30
    {
31
        return [
32
            new TwigFunction(
33
                'ez_render_*_query',
34
                function (string $type, array $options): ?string {
35
                    $this->assertTypeIsValid($type);
36
37
                    return $this->fragmentHandler->render(
38
                        $this->createControllerReference($options)
39
                    );
40
                },
41
                ['is_safe' => ['html']]
42
            ),
43
            new TwigFunction(
44
                'ez_render_*_query_*',
45
                function (string $type, string $renderer, array $options): ?string {
46
                    $this->assertTypeIsValid($type);
47
48
                    return $this->fragmentHandler->render(
49
                        $this->createControllerReference($options),
50
                        $renderer
51
                    );
52
                },
53
                ['is_safe' => ['html']]
54
            ),
55
        ];
56
    }
57
58
    private function createControllerReference(array $options): ControllerReference
59
    {
60
        return new ControllerReference('ez_query_render::renderQuery', [
61
            'options' => $options,
62
        ]);
63
    }
64
65
    /**
66
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
67
     */
68
    private function assertTypeIsValid(string $type): void
69
    {
70
        if (!in_array($type, self::VALID_TYPES)) {
71
            throw new InvalidArgumentException(
72
                '$type',
73
                'Expected value to be of ' . implode(', ', self::VALID_TYPES)
74
            );
75
        }
76
    }
77
}
78