1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Enjoys\AssetsCollector\Extensions\Twig; |
6
|
|
|
|
7
|
|
|
use Enjoys\AssetsCollector\Assets; |
8
|
|
|
use Twig\Extension\AbstractExtension; |
9
|
|
|
use Twig\TwigFunction; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class AssetsExtension |
13
|
|
|
* Set assets from Twig. In the css example, but for js the same |
14
|
|
|
* {{ asset('css', [{0: '//cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.css', 'minify': false}]) }} |
15
|
|
|
* {{ asset('css', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.css') }} |
16
|
|
|
* {{ asset('css', ['path/style1.css', 'style2.css']) }} |
17
|
|
|
* |
18
|
|
|
* Output |
19
|
|
|
* {{ eCSS() }} |
20
|
|
|
* {{ eJS() }} |
21
|
|
|
* |
22
|
|
|
* @package Enjoys\AssetsCollector\Extensions\Twig |
23
|
|
|
*/ |
24
|
|
|
class AssetsExtension extends AbstractExtension |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @var Assets |
28
|
|
|
*/ |
29
|
|
|
private Assets $assetsCollector; |
30
|
|
|
|
31
|
4 |
|
public function __construct(Assets $assetsCollector) |
32
|
|
|
{ |
33
|
4 |
|
$this->assetsCollector = $assetsCollector; |
34
|
4 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* {@inheritdoc} |
38
|
|
|
*/ |
39
|
1 |
|
public function getFunctions(): array |
40
|
|
|
{ |
41
|
|
|
return [ |
42
|
1 |
|
new TwigFunction('asset', [$this, 'asset']), |
43
|
1 |
|
new TwigFunction('eCSS', [$this, 'getExternCss'], ['is_safe' => ['html']]), |
44
|
1 |
|
new TwigFunction('eJS', [$this, 'getExternJs'], ['is_safe' => ['html']]), |
45
|
|
|
]; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param string $type |
50
|
|
|
* @param array<string> $paths |
51
|
|
|
* @param string $namespace |
52
|
|
|
*/ |
53
|
4 |
|
public function asset(string $type, array $paths = [], string $namespace = Assets::NAMESPACE_COMMON): void |
54
|
|
|
{ |
55
|
4 |
|
$this->assetsCollector->add($type, $paths, $namespace); |
56
|
4 |
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param string $namespace |
60
|
|
|
* @return string |
61
|
|
|
* @throws \Exception |
62
|
|
|
*/ |
63
|
1 |
|
public function getExternCss(string $namespace = Assets::NAMESPACE_COMMON): string |
64
|
|
|
{ |
65
|
1 |
|
return $this->assetsCollector->get('css', $namespace); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param string $namespace |
70
|
|
|
* @return string |
71
|
|
|
* @throws \Exception |
72
|
|
|
*/ |
73
|
1 |
|
public function getExternJs(string $namespace = Assets::NAMESPACE_COMMON): string |
74
|
|
|
{ |
75
|
1 |
|
return $this->assetsCollector->get('js', $namespace); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return Assets |
80
|
|
|
*/ |
81
|
|
|
public function getAssetsCollector(): Assets |
82
|
|
|
{ |
83
|
|
|
return $this->assetsCollector; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|