Completed
Push — master ( 4e1c5d...6050c4 )
by Grégoire
22:25 queued 19:06
created

TemplateRegistryExtension::getAdmin()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
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 Sonata\AdminBundle\Templating\TemplateRegistryInterface;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
19
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
20
use Twig\Extension\AbstractExtension;
21
use Twig\TwigFunction;
22
23
final class TemplateRegistryExtension extends AbstractExtension
24
{
25
    /**
26
     * @var TemplateRegistryInterface
27
     */
28
    private $globalTemplateRegistry;
29
30
    /**
31
     * @var ContainerInterface
32
     */
33
    private $container;
34
35
    public function __construct(TemplateRegistryInterface $globalTemplateRegistry, ContainerInterface $container)
36
    {
37
        $this->globalTemplateRegistry = $globalTemplateRegistry;
38
        $this->container = $container;
39
    }
40
41
    public function getFunctions(): array
42
    {
43
        return [
44
            new TwigFunction('get_admin_template', [$this, 'getAdminTemplate']),
45
            new TwigFunction('get_global_template', [$this, 'getGlobalTemplate']),
46
        ];
47
    }
48
49
    /**
50
     * @param string $name
51
     * @param string $adminCode
52
     *
53
     * @throws ServiceNotFoundException
54
     * @throws ServiceCircularReferenceException
55
     */
56
    public function getAdminTemplate($name, $adminCode): ?string
57
    {
58
        return $this->getTemplateRegistry($adminCode)->getTemplate($name);
59
    }
60
61
    /**
62
     * @param string $name
63
     */
64
    public function getGlobalTemplate($name): ?string
65
    {
66
        return $this->globalTemplateRegistry->getTemplate($name);
67
    }
68
69
    /**
70
     * @throws ServiceNotFoundException
71
     * @throws ServiceCircularReferenceException
72
     */
73
    private function getTemplateRegistry(string $adminCode): TemplateRegistryInterface
74
    {
75
        $serviceId = $adminCode.'.template_registry';
76
        $templateRegistry = $this->container->get($serviceId);
77
        if ($templateRegistry instanceof TemplateRegistryInterface) {
78
            return $templateRegistry;
79
        }
80
81
        throw new ServiceNotFoundException($serviceId);
82
    }
83
}
84