Passed
Pull Request — develop (#10)
by
unknown
10:37
created

ViteService::publicAsset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * Vite plugin for Craft CMS 3.x
4
 *
5
 * Allows the use of the Vite.js next generation frontend tooling with Craft CMS
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2021 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\pluginvite\services;
12
13
use Craft;
14
use craft\base\Component;
15
use craft\helpers\Html as HtmlHelper;
16
use craft\helpers\Json as JsonHelper;
17
use craft\web\View;
18
use nystudio107\pluginvite\helpers\FileHelper;
19
use nystudio107\pluginvite\helpers\ManifestHelper;
20
use Throwable;
21
use yii\base\InvalidConfigException;
22
use yii\caching\TagDependency;
23
24
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
25
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
26
 * @package   Vite
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
27
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
28
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
29
class ViteService extends Component
30
{
31
    // Constants
32
    // =========================================================================
33
34
    const VITE_CLIENT = '@vite/client';
35
    const VITE_DEVSERVER_PING = '__vite_ping';
36
    const LEGACY_POLYFILLS = 'vite/legacy-polyfills';
37
38
    // Public Properties
39
    // =========================================================================
40
41
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
42
     * @var bool Should the dev server be used for?
43
     */
44
    public $useDevServer;
45
46
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
47
     * @var string File system path (or URL) to the Vite-built manifest.json
48
     */
49
    public $manifestPath;
50
51
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
52
     * @var string The public URL to the dev server (what appears in `<script src="">` tags
53
     */
54
    public $devServerPublic;
55
56
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
57
     * @var string The public URL to use when not using the dev server
58
     */
59
    public $serverPublic;
60
61
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
62
     * @var string The JavaScript entry from the manifest.json to inject on Twig error pages
63
     *              This can be a string or an array of strings
64
     */
65
    public $errorEntry = '';
66
67
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
68
     * @var string String to be appended to the cache key
69
     */
70
    public $cacheKeySuffix = '';
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @var string The internal URL to the dev server, when accessed from the environment in which PHP is executing
74
     *              This can be the same as `$devServerPublic`, but may be different in containerized or VM setups.
75
     *              ONLY used if $checkDevServer = true
76
     */
77
    public $devServerInternal;
78
79
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
80
     * @var bool Should we check for the presence of the dev server by pinging $devServerInternal to make sure it's running?
81
     */
82
    public $checkDevServer = false;
83
84
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
85
     * @var bool Whether the react-refresh-shim should be included
86
     */
87
    public $includeReactRefreshShim = false;
88
89
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
90
     * @var bool Whether the modulepreload-polyfill shim should be included
91
     */
92
    public $includeModulePreloadShim = true;
93
94
    // Protected Properties
95
    // =========================================================================
96
97
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
98
     * @var bool Whether the manifest shims has been included yet or not
99
     */
100
    protected $manifestShimsIncluded = false;
101
102
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
103
     * @var bool Whether the dev server shims has been included yet or not
104
     */
105
    protected $devServerShimsIncluded = false;
106
107
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
108
     * @var null|bool Cached status of whether the devServer is running or not
109
     */
110
    protected $devServerRunningCached = null;
111
112
    // Public Methods
113
    // =========================================================================
114
115
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
116
     * @inheritDoc
117
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
118
    public function init()
119
    {
120
        parent::init();
121
        // Do nothing for console requests
122
        $request = Craft::$app->getRequest();
123
        if ($request->getIsConsoleRequest()) {
124
            return;
125
        }
126
        // Our component is lazily loaded, so the View will be instantiated by now
127
        if (Craft::$app->getConfig()->getGeneral()->devMode) {
128
            Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']);
129
        }
130
    }
131
132
    /**
133
     * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or
134
     * extracting it from the manifest.json file
135
     *
136
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
137
     * @param bool $asyncCss
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
138
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
139
     * @param array $cssTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
140
     *
141
     * @return void
142
     * @throws InvalidConfigException
143
     */
144
    public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
145
    {
146
        if ($this->devServerRunning()) {
147
            $this->devServerRegister($path, $scriptTagAttrs);
148
149
            return;
150
        }
151
152
        $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
153
    }
154
155
    /**
156
     * Determine whether the Vite dev server is running
157
     *
158
     * @return bool
159
     */
160
    public function devServerRunning(): bool
161
    {
162
        if ($this->devServerRunningCached !== null) {
163
            return $this->devServerRunningCached;
164
        }
165
        // If the dev server is turned off via config, say it's not running
166
        if (!$this->useDevServer) {
167
            return false;
168
        }
169
        // If we're not supposed to check that the dev server is actually running, just assume it is
170
        if (!$this->checkDevServer) {
171
            return true;
172
        }
173
        // Check to see if the dev server is actually running by pinging it
174
        $url = FileHelper::createUrl($this->devServerInternal, self::VITE_DEVSERVER_PING);
175
        $this->devServerRunningCached = !($this->fetch($url) === null);
176
177
        return $this->devServerRunningCached;
178
    }
179
180
    /**
181
     * Return the contents of a local file (via path) or remote file (via URL),
182
     * or null if the file doesn't exist or couldn't be fetched
183
     * Yii2 aliases and/or environment variables may be used
184
     *
185
     * @param string $pathOrUrl
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
186
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
187
     *
188
     * @return string|array|null
189
     */
190
    public function fetch(string $pathOrUrl, callable $callback = null)
191
    {
192
        return FileHelper::fetch($pathOrUrl, $callback, $this->cacheKeySuffix);
193
    }
194
195
    /**
196
     * Register the script tag to the Craft View to load the script from the Vite dev server
197
     *
198
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
199
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
200
     *
201
     * @return void
202
     * @throws InvalidConfigException
203
     */
204
    public function devServerRegister(string $path, array $scriptTagAttrs = [])
205
    {
206
        $view = Craft::$app->getView();
207
        // Include any dev server shims
208
        if (!$this->devServerShimsIncluded) {
209
            // Include the react-refresh-shim
210
            if ($this->includeReactRefreshShim) {
211
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
212
                // Replace the hard-coded dev server URL with whatever they have theirs set to
213
                $script = str_replace(
214
                    'http://localhost:3000/',
215
                    rtrim($this->devServerPublic, '/') . '/',
216
                    $script
217
                );
218
                $view->registerScript(
219
                    $script,
220
                    $view::POS_HEAD,
221
                    [
222
                        'type' => 'module',
223
                    ],
224
                    'REACT_REFRESH_SHIM'
225
                );
226
            }
227
            $this->devServerShimsIncluded = true;
228
        }
229
        // Include the entry script
230
        $url = FileHelper::createUrl($this->devServerPublic, $path);
231
        $view->registerJsFile(
232
            $url,
233
            array_merge(['type' => 'module'], $scriptTagAttrs),
234
            md5($url . JsonHelper::encode($scriptTagAttrs))
235
        );
236
    }
237
238
    /**
239
     * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file
240
     *
241
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
242
     * @param bool $asyncCss
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
243
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
244
     * @param array $cssTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
245
     *
246
     * @return void
247
     * @throws InvalidConfigException
248
     */
249
    public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
250
    {
251
        $view = Craft::$app->getView();
252
        ManifestHelper::fetchManifest($this->manifestPath);
253
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
254
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
255
        // Include any manifest shims
256
        if (!$this->manifestShimsIncluded) {
257
            // Handle the modulepreload-polyfill shim
258
            if ($this->includeModulePreloadShim) {
259
                $view->registerScript(
260
                    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
261
                    $view::POS_HEAD,
262
                    ['type' => 'module'],
263
                    'MODULEPRELOAD_POLYFILL'
264
                );
265
            }
266
            // Handle any legacy polyfills
267
            if (!empty($legacyTags)) {
268
                $view->registerScript(
269
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
270
                    $view::POS_HEAD,
271
                    [],
272
                    'SAFARI_NOMODULE_FIX'
273
                );
274
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
275
                $tags = array_merge($legacyPolyfillTags, $tags);
276
            }
277
            $this->manifestShimsIncluded = true;
278
        }
279
        $this->manifestRegisterTags($tags, $legacyTags);
280
    }
281
282
    /**
283
     * Return the URL for the given entry
284
     *
285
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
286
     *
287
     * @return string
288
     */
289
    public function entry(string $path): string
290
    {
291
        ManifestHelper::fetchManifest($this->manifestPath);
292
        $entry = ManifestHelper::extractEntry($path);
293
294
        return FileHelper::createUrl($this->serverPublic, $entry);
295
    }
296
297
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $public should have a doc-comment as per coding-style.
Loading history...
298
     * Return the URL for the given asset
299
     *
300
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
301
     *
302
     * @return string
303
     */
304
    public function asset(string $path, bool $public=false): string
305
    {
306
        if ($this->devServerRunning()) {
307
            return $this->devServerAsset($path);
308
        }
309
        
310
        if ($public) {
311
            return $this->publicAsset($path);
312
        }
313
314
        return $this->manifestAsset($path);
315
    }
316
317
    /**
318
     * Return the URL for the asset from the Vite dev server
319
     *
320
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
321
     *
322
     * @return string
323
     */
324
    public function devServerAsset(string $path): string
325
    {
326
        // Return a URL to the given asset
327
        return FileHelper::createUrl($this->devServerPublic, $path);
328
    }
329
    
330
    /**
331
     * Return the URL for the asset from the public Vite folder
332
     *
333
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
334
     *
335
     * @return string
336
     */
337
    public function publicAsset(string $path): string
338
    {
339
        // Return a URL to the given asset
340
        return FileHelper::createUrl($this->serverPublic, $path);
341
    }
342
343
    /**
344
     * Return the URL for the asset from the manifest.json file
345
     *
346
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
347
     *
348
     * @return string
349
     */
350
    public function manifestAsset(string $path): string
351
    {
352
        ManifestHelper::fetchManifest($this->manifestPath);
353
        $assets = ManifestHelper::extractAssetFiles();
354
        // Get just the file name
355
        $assetKeyParts = explode('/', $path);
356
        $assetKey = end($assetKeyParts);
357
        foreach ($assets as $key => $value) {
358
            if ($key === $assetKey) {
359
                return FileHelper::createUrl($this->serverPublic, $value);
360
            }
361
        }
362
363
        return '';
364
    }
365
366
    /**
367
     * Invalidate all of the Vite caches
368
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
369
    public function invalidateCaches()
370
    {
371
        $cache = Craft::$app->getCache();
372
        TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix);
373
        Craft::info('All Vite caches cleared', __METHOD__);
374
    }
375
376
    /**
377
     * Return the appropriate tags to load the Vite script, either via the dev server or
378
     * extracting it from the manifest.json file
379
     *
380
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
381
     * @param bool $asyncCss
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
382
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
383
     * @param array $cssTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
384
     *
385
     * @return string
386
     */
387
    public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
388
    {
389
        if ($this->devServerRunning()) {
390
            return $this->devServerScript($path, $scriptTagAttrs);
391
        }
392
393
        return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
394
    }
395
396
    /**
397
     * Return the script tag to load the script from the Vite dev server
398
     *
399
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
400
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
401
     *
402
     * @return string
403
     */
404
    public function devServerScript(string $path, array $scriptTagAttrs = []): string
405
    {
406
        $lines = [];
407
        // Include any dev server shims
408
        if (!$this->devServerShimsIncluded) {
409
            // Include the react-refresh-shim
410
            if ($this->includeReactRefreshShim) {
411
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
412
                // Replace the hard-coded dev server URL with whatever they have theirs set to
413
                $script = str_replace(
414
                    'http://localhost:3000/',
415
                    rtrim($this->devServerPublic, '/') . '/',
416
                    $script
417
                );
418
                $lines[] = HtmlHelper::script(
419
                    $script,
420
                    [
421
                        'type' => 'module',
422
                    ]
423
                );
424
            }
425
            $this->devServerShimsIncluded = true;
426
        }
427
        // Include the entry script
428
        $url = FileHelper::createUrl($this->devServerPublic, $path);
429
        $lines[] = HtmlHelper::jsFile($url, array_merge([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
430
            'type' => 'module',
431
        ], $scriptTagAttrs));
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
432
433
        return implode("\r\n", $lines);
434
    }
435
436
    /**
437
     * Return the script, module link, and CSS link tags for the script from the manifest.json file
438
     *
439
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
440
     * @param bool $asyncCss
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
441
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
442
     * @param array $cssTagAttrs
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
443
     *
444
     * @return string
445
     */
446
    public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
447
    {
448
        $lines = [];
449
        ManifestHelper::fetchManifest($this->manifestPath);
450
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
451
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
452
        // Include any manifest shims
453
        if (!$this->manifestShimsIncluded) {
454
            // Handle the modulepreload-polyfill shim
455
            if ($this->includeModulePreloadShim) {
456
                $lines[] = HtmlHelper::script(
457
                    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
458
                    ['type' => 'module']
459
                );
460
            }
461
            // Handle any legacy polyfills
462
            if (!empty($legacyTags)) {
463
                $lines[] = HtmlHelper::script(
464
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
465
                    []
466
                );
467
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
468
                $tags = array_merge($legacyPolyfillTags, $tags);
469
            }
470
            $this->manifestShimsIncluded = true;
471
        }
472
        $lines = array_merge($lines, $this->manifestScriptTags($tags, $legacyTags));
473
474
        return implode("\r\n", $lines);
475
    }
476
477
    // Protected Methods
478
    // =========================================================================
479
480
    /**
481
     * Iterate through all the tags, and register them
482
     *
483
     * @param array $tags
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
484
     * @param array $legacyTags
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
485
     * @throws InvalidConfigException
0 ignored issues
show
Coding Style introduced by
Tag @throws cannot be grouped with parameter tags in a doc comment
Loading history...
486
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
487
    protected function manifestRegisterTags(array $tags, array $legacyTags)
488
    {
489
        $view = Craft::$app->getView();
490
        foreach (array_merge($tags, $legacyTags) as $tag) {
491
            if (!empty($tag)) {
492
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
493
                switch ($tag['type']) {
494
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
495
                        $view->registerJsFile(
496
                            $url,
497
                            $tag['options'],
498
                            md5($url . JsonHelper::encode($tag['options']))
499
                        );
500
                        break;
501
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
502
                        $view->registerCssFile(
503
                            $url,
504
                            $tag['options']
505
                        );
506
                        break;
507
                    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
508
                        $view->registerLinkTag(
509
                            array_filter([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
510
                                'crossorigin' => $tag['crossorigin'],
511
                                'href' => $url,
512
                                'rel' => 'modulepreload',
513
                                'integrity' => $tag['integrity'] ?? '',
514
                            ]),
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
515
                            md5($url)
516
                        );
517
                        break;
518
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
519
                        break;
520
                }
521
            }
522
        }
523
    }
524
525
    /**
526
     * Inject the error entry point JavaScript for auto-reloading of Twig error
527
     * pages
528
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
529
    protected function injectErrorEntry()
530
    {
531
        // If there's no error entry provided, return
532
        if (empty($this->errorEntry)) {
533
            return;
534
        }
535
        // If it's not a server error or a client error, return
536
        $response = Craft::$app->getResponse();
537
        if (!($response->isServerError || $response->isClientError)) {
538
            return;
539
        }
540
        // If the dev server isn't running, return
541
        if (!$this->devServerRunning()) {
542
            return;
543
        }
544
        // Inject the errorEntry script tags to enable HMR on this page
545
        try {
546
            $errorEntry = $this->errorEntry;
547
            if (is_string($errorEntry)) {
0 ignored issues
show
introduced by
The condition is_string($errorEntry) is always true.
Loading history...
548
                $errorEntry = [$errorEntry];
549
            }
550
            foreach ($errorEntry as $entry) {
551
                $tag = $this->script($entry);
552
                if ($tag !== null) {
553
                    echo $tag;
554
                }
555
            }
556
        } catch (Throwable $e) {
557
            // That's okay, Vite will have already logged the error
558
        }
559
    }
560
561
    /**
562
     * Iterate through all the tags, and return them
563
     *
564
     * @param array $tags
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
565
     * @param array $legacyTags
0 ignored issues
show
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
566
     * @return array
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
567
     */
568
    protected function manifestScriptTags(array $tags, array $legacyTags): array
569
    {
570
        $lines = [];
571
        foreach (array_merge($tags, $legacyTags) as $tag) {
572
            if (!empty($tag)) {
573
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
574
                switch ($tag['type']) {
575
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
576
                        $lines[] = HtmlHelper::jsFile($url, $tag['options']);
577
                        break;
578
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
579
                        $lines[] = HtmlHelper::cssFile($url, $tag['options']);
580
                        break;
581
                    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
582
                        $lines[] = HtmlHelper::tag('link', '', array_filter([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
583
                            'crossorigin' => $tag['crossorigin'],
584
                            'href' => $url,
585
                            'rel' => 'modulepreload',
586
                            'integrity' => $tag['integrity'] ?? '',
587
                        ]));
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
588
                        break;
589
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
590
                        break;
591
                }
592
            }
593
        }
594
595
        return $lines;
596
    }
597
}
598