Passed
Pull Request — master (#150)
by Arnaud
07:48
created

ScriptRegistry::dump()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 11
rs 10
1
<?php
2
3
namespace LAG\AdminBundle\Assets\Registry;
4
5
use LAG\AdminBundle\Exception\Exception;
6
use Twig\Environment;
7
8
/**
9
 * Manage script to avoid adding javascript into the body, and allow dumping them into the head and footer section of
10
 * the html page.
11
 */
12
class ScriptRegistry implements ScriptRegistryInterface
13
{
14
    protected $scripts = [];
15
16
    /**
17
     * @var string
18
     */
19
    protected $template;
20
21
    /**
22
     * @var Environment
23
     */
24
    protected $environment;
25
26
    public function __construct(Environment $environment, string $template = '@LAGAdmin/Scripts/scripts.html.twig')
27
    {
28
        $this->template = $template;
29
        $this->environment = $environment;
30
    }
31
32
    public function register(string $location, string $script, string $template = null, array $context = []): void
33
    {
34
        $asset = [
35
            'location' => $location,
36
            'template' => $template,
37
            'context' => $context,
38
        ];
39
40
        if (null === $template) {
41
            // if no template is provided, we use the default script template
42
            $asset['template'] = $this->template;
43
            $asset['context'] = [
44
                'script' => $script,
45
            ];
46
        }
47
        $this->scripts[$location][$script] = $asset;
48
    }
49
50
    public function unregister(string $location, string $script): void
51
    {
52
        if (!$this->hasScript($location, $script)) {
53
            throw new Exception('The script "'.$script.'" is not registered at the location "'.$location.'". It can be unregistered');
54
        }
55
    }
56
57
    public function dump(string $location): string
58
    {
59
        $content = '';
60
61
        foreach ($this->scripts as $location => $scripts) {
62
            foreach ($scripts as $script) {
63
                $content .= $this->environment->render($script['template'], $script['context']);
64
            }
65
        }
66
67
        return $content;
68
    }
69
70
    public function hasLocation(string $location): bool
71
    {
72
        return key_exists($location, $this->scripts);
73
    }
74
75
    public function hasScript(string $location, string $script): bool
76
    {
77
        return $this->hasLocation($location) && key_exists($script, $this->scripts[$location]);
78
    }
79
}
80