AssetsTwigExtension   A
last analyzed

Complexity

Total Complexity 28

Size/Duplication

Total Lines 280
Duplicated Lines 0 %

Importance

Changes 10
Bugs 0 Features 5
Metric Value
wmc 28
eloc 86
dl 0
loc 280
rs 10
c 10
b 0
f 5

15 Methods

Rating   Name   Duplication   Size   Complexity  
A coreImageFunction() 0 14 1
A assetExists() 0 7 2
B renderIcon() 0 31 10
A getPublicDirectory() 0 2 1
A coreStyleFilter() 0 9 1
A coreRenderIconFunction() 0 2 1
A coreResourceStyleFunction() 0 10 1
A setPublicDirectory() 0 3 1
A coreGtag() 0 9 3
A coreResourcePath() 0 10 2
A cssRgba() 0 2 1
A coreScriptFilter() 0 9 1
A getFilters() 0 8 1
A getFunctions() 0 11 1
A coreResourceScriptFunction() 0 8 1
1
<?php
2
3
/*
4
 * This file is part of the core-bundle package.
5
 *
6
 * (c) 2022 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Bundle\CoreBundle\Twig\Extension;
13
14
use Twig\Environment;
15
use Twig\TwigFilter;
16
use Twig\TwigFunction;
17
use WBW\Bundle\CoreBundle\Routing\RouterTrait;
18
use WBW\Bundle\CoreBundle\Twig\Extension\Assets\FontAwesomeTwigExtension;
19
use WBW\Bundle\CoreBundle\Twig\Extension\Assets\MaterialDesignIconicFontTwigExtension;
20
use WBW\Bundle\CoreBundle\Twig\Extension\Assets\MeteoconsTwigExtension;
21
use WBW\Library\Symfony\Helper\ColorHelper;
22
use WBW\Library\Symfony\Provider\JavascriptProviderInterface;
23
use WBW\Library\Symfony\Provider\StylesheetProviderInterface;
24
use WBW\Library\Types\Helper\ArrayHelper;
25
use WBW\Library\Types\Helper\StringHelper;
26
27
/**
28
 * Assets Twig extension.
29
 *
30
 * @author webeweb <https://github.com/webeweb>
31
 * @package WBW\Bundle\CoreBundle\Twig\Extension
32
 */
33
class AssetsTwigExtension extends AbstractTwigExtension {
34
35
    use RouterTrait {
36
        setRouter as public;
37
    }
38
39
    /**
40
     * Service name.
41
     *
42
     * @var string
43
     */
44
    const SERVICE_NAME = "wbw.core.twig.extension.assets";
45
46
    /**
47
     * Public directory.
48
     *
49
     * @var string|null
50
     */
51
    protected $publicDirectory;
52
53
    /**
54
     * Determine if an asset exists.
55
     *
56
     * @param string|null $filename The filename.
57
     * @return bool|null Returns true in case of success, false otherwise.
58
     */
59
    public function assetExists(?string $filename): ?bool {
60
61
        if (null === $filename) {
62
            return null;
63
        }
64
65
        return file_exists($this->getPublicDirectory() . $filename);
66
    }
67
68
    /**
69
     * Display a Google tag manager.
70
     *
71
     * @param string|null $id The id.
72
     * @return string|null Returns the Google tag manager.
73
     */
74
    public function coreGtag(?string $id): ?string {
75
76
        if (null === $id || "" === $id) {
77
            return null;
78
        }
79
80
        $template = file_get_contents(__DIR__ . "/AssetsTwigExtension.coreGtag.html");
81
82
        return str_replace("{{ id }}", $id, $template);
83
    }
84
85
    /**
86
     * Display an image.
87
     *
88
     * @param array $args The arguments.
89
     * @return string Returns the image.
90
     */
91
    public function coreImageFunction(array $args = []): string {
92
93
        $template = "<img {{ attributes }}/>";
94
95
        $attributes = [
96
            "src"    => ArrayHelper::get($args, "src"),
97
            "alt"    => ArrayHelper::get($args, "alt"),
98
            "width"  => ArrayHelper::get($args, "width"),
99
            "height" => ArrayHelper::get($args, "height"),
100
            "class"  => ArrayHelper::get($args, "class"),
101
            "usemap" => ArrayHelper::get($args, "usemap"),
102
        ];
103
104
        return str_replace("{{ attributes }}", StringHelper::parseArray($attributes), $template);
105
    }
106
107
    /**
108
     * Display an icon.
109
     *
110
     * @param string|null $name The name.
111
     * @param string|null $style The style.
112
     * @return string|null Returns the icon.
113
     */
114
    public function coreRenderIconFunction(?string $name, string $style = null): ?string {
115
        return static::renderIcon($this->getTwigEnvironment(), $name, $style);
0 ignored issues
show
Bug introduced by
It seems like $this->getTwigEnvironment() can also be of type null; however, parameter $twigEnvironment of WBW\Bundle\CoreBundle\Tw...Extension::renderIcon() does only seem to accept Twig\Environment, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

115
        return static::renderIcon(/** @scrutinizer ignore-type */ $this->getTwigEnvironment(), $name, $style);
Loading history...
116
    }
117
118
    /**
119
     * Resource path.
120
     *
121
     * @param string $type The type.
122
     * @param string $name The name.
123
     * @param array $query The query.
124
     * @return string|null Returns the resource path.
125
     */
126
    public function coreResourcePath(string $type, string $name, array $query = []): ?string {
127
128
        if (null === $this->getRouter()) {
129
            return null;
130
        }
131
132
        return $this->getRouter()->generate("wbw_core_twig_resource", array_merge([
133
            "type" => $type,
134
            "name" => $name,
135
        ], $query));
136
    }
137
138
    /**
139
     * Resource "script".
140
     *
141
     * @param string $name The name.
142
     * @param array $query The query.
143
     * @return string Returns the resource "script".
144
     */
145
    public function coreResourceScriptFunction(string $name, array $query = []): string {
146
147
        $attributes = [
148
            "type" => "text/javascript",
149
            "src"  => $this->coreResourcePath(JavascriptProviderInterface::JAVASCRIPT_PROVIDER_EXTENSION, $name, $query),
150
        ];
151
152
        return static::coreHtmlElement("script", null, $attributes);
153
    }
154
155
    /**
156
     * Resource "style".
157
     *
158
     * @param string $name The name.
159
     * @param array $query The query.
160
     * @return string Returns the resource "style".
161
     */
162
    public function coreResourceStyleFunction(string $name, array $query = []): string {
163
164
        $template   = "<link {{ attributes }}>";
165
        $attributes = [
166
            "type" => "text/css",
167
            "rel"  => "stylesheet",
168
            "href" => $this->coreResourcePath(StylesheetProviderInterface::STYLESHEET_PROVIDER_EXTENSION, $name, $query),
169
        ];
170
171
        return str_replace("{{ attributes }}", StringHelper::parseArray($attributes), $template);
172
    }
173
174
    /**
175
     * Display a script.
176
     *
177
     * @param string $content The content.
178
     * @return string Returns a script.
179
     */
180
    public function coreScriptFilter(string $content): string {
181
182
        $attributes = [
183
            "type" => "text/javascript",
184
        ];
185
186
        $innerHTML = implode("", ["\n", $content, "\n"]);
187
188
        return static::coreHtmlElement("script", $innerHTML, $attributes);
189
    }
190
191
    /**
192
     * Display a style.
193
     *
194
     * @param string $content The content.
195
     * @return string Returns a style.
196
     */
197
    public function coreStyleFilter(string $content): string {
198
199
        $attributes = [
200
            "type" => "text/css",
201
        ];
202
203
        $innerHTML = implode("", ["\n", $content, "\n"]);
204
205
        return static::coreHtmlElement("style", $innerHTML, $attributes);
206
    }
207
208
    /**
209
     * Display a rgba().
210
     *
211
     * @param string|null $color The hexadecimal color.
212
     * @param float $alpha The alpha channel.
213
     * @return string|null Returns the rgba().
214
     */
215
    public function cssRgba(?string $color, float $alpha = 1.00): ?string {
216
        return ColorHelper::hexToRgba($color, $alpha);
217
    }
218
219
    /**
220
     * Get the Twig filters.
221
     *
222
     * @return TwigFilter[] Returns the Twig filters.
223
     */
224
    public function getFilters(): array {
225
226
        return [
227
            new TwigFilter("assetExists", [$this, "assetExists"], ["is_safe" => ["html"]]),
228
            new TwigFilter("coreGtag", [$this, "coreGtag"], ["is_safe" => ["html"]]),
229
            new TwigFilter("coreScript", [$this, "coreScriptFilter"], ["is_safe" => ["html"]]),
230
            new TwigFilter("coreStyle", [$this, "coreStyleFilter"], ["is_safe" => ["html"]]),
231
            new TwigFilter("cssRgba", [$this, "cssRgba"], ["is_safe" => ["html"]]),
232
        ];
233
    }
234
235
    /**
236
     * Get the Twig functions.
237
     *
238
     * @return TwigFunction[] Returns the Twig functions.
239
     */
240
    public function getFunctions(): array {
241
242
        return [
243
            new TwigFunction("assetExists", [$this, "assetExists"], ["is_safe" => ["html"]]),
244
            new TwigFunction("coreGtag", [$this, "coreGtag"], ["is_safe" => ["html"]]),
245
            new TwigFunction("coreImage", [$this, "coreImageFunction"], ["is_safe" => ["html"]]),
246
            new TwigFunction("coreRenderIcon", [$this, "coreRenderIconFunction"], ["is_safe" => ["html"]]),
247
            new TwigFunction("coreResourcePath", [$this, "coreResourcePathFunction"], ["is_safe" => ["html"]]),
248
            new TwigFunction("coreResourceScript", [$this, "coreResourceScriptFunction"], ["is_safe" => ["html"]]),
249
            new TwigFunction("coreResourceStyle", [$this, "coreResourceStyleFunction"], ["is_safe" => ["html"]]),
250
            new TwigFunction("cssRgba", [$this, "cssRgba"], ["is_safe" => ["html"]]),
251
        ];
252
    }
253
254
    /**
255
     * Get the public directory.
256
     *
257
     * @return string|null Returns the public directory.
258
     */
259
    public function getPublicDirectory(): ?string {
260
        return $this->publicDirectory;
261
    }
262
263
    /**
264
     * Render an icon.
265
     *
266
     * @param Environment $twigEnvironment The Twig environment.
267
     * @param string|null $name The name.
268
     * @param string|null $style The style.
269
     * @return string|null Returns the rendered icon.
270
     */
271
    public static function renderIcon(Environment $twigEnvironment, ?string $name, string $style = null): ?string {
272
273
        $handler = explode(":", $name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

273
        $handler = explode(":", /** @scrutinizer ignore-type */ $name);
Loading history...
274
        if (2 !== count($handler)) {
275
            return null;
276
        }
277
278
        $output = null;
279
280
        switch ($handler[0]) {
281
282
            case "fa": // Font Awesome
283
            case "fas":
284
            case "far":
285
            case "fal":
286
            case "fab":
287
            case "fad":
288
                $output = (new FontAwesomeTwigExtension($twigEnvironment))->renderIcon($handler[1], $style);
289
                $output = str_replace('class="fa', 'class="' . $handler[0], $output);
290
                break;
291
292
            case "mc": // Meteocons
293
                $output = (new MeteoconsTwigExtension($twigEnvironment))->renderIcon($handler[1], $style);
294
                break;
295
296
            case "zmdi": // Material Design Iconic Font
297
                $output = (new MaterialDesignIconicFontTwigExtension($twigEnvironment))->renderIcon($handler[1], $style);
298
                break;
299
        }
300
301
        return $output;
302
    }
303
304
    /**
305
     * Set the public directory.
306
     *
307
     * @param string|null $publicDirectory The public directory.
308
     * @return AssetsTwigExtension Returns this assets Twig extension.
309
     */
310
    public function setPublicDirectory(?string $publicDirectory): AssetsTwigExtension {
311
        $this->publicDirectory = $publicDirectory;
312
        return $this;
313
    }
314
}
315