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
|
|
|
const DEFAULT_TEMPLATE = '@LAGAdmin/Scripts/scripts.html.twig'; |
15
|
|
|
|
16
|
|
|
protected $scripts = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var string |
20
|
|
|
*/ |
21
|
|
|
protected $template; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var Environment |
25
|
|
|
*/ |
26
|
|
|
protected $environment; |
27
|
|
|
|
28
|
|
|
public function __construct(Environment $environment, string $template = self::DEFAULT_TEMPLATE) |
29
|
|
|
{ |
30
|
|
|
$this->template = $template; |
31
|
|
|
$this->environment = $environment; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function register(string $location, string $script, string $template = null, array $context = []): void |
35
|
|
|
{ |
36
|
|
|
$asset = [ |
37
|
|
|
'location' => $location, |
38
|
|
|
'template' => $template, |
39
|
|
|
'context' => $context, |
40
|
|
|
]; |
41
|
|
|
|
42
|
|
|
if (null === $template) { |
43
|
|
|
// if no template is provided, we use the default script template |
44
|
|
|
$asset['template'] = $this->template; |
45
|
|
|
$asset['context']['script'] = $script; |
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
|
|
|
unset($this->scripts[$location][$script]); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function dump(string $location): string |
59
|
|
|
{ |
60
|
|
|
$content = ''; |
61
|
|
|
|
62
|
|
|
foreach ($this->scripts as $location => $scripts) { |
63
|
|
|
foreach ($scripts as $script) { |
64
|
|
|
$content .= $this->environment->render($script['template'], $script['context']); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $content; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function hasLocation(string $location): bool |
72
|
|
|
{ |
73
|
|
|
return key_exists($location, $this->scripts); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
public function hasScript(string $location, string $script): bool |
77
|
|
|
{ |
78
|
|
|
return $this->hasLocation($location) && key_exists($script, $this->scripts[$location]); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|