Passed
Push — develop ( a7365f...99a311 )
by Andrew
04:13
created

ViteService   F

Complexity

Total Complexity 60

Size/Duplication

Total Lines 573
Duplicated Lines 0 %

Importance

Changes 32
Bugs 2 Features 2
Metric Value
eloc 202
c 32
b 2
f 2
dl 0
loc 573
rs 3.6
wmc 60

18 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 9 2
A fetch() 0 3 1
B injectErrorEntry() 0 28 9
A manifestScript() 0 29 4
A devServerRegister() 0 31 3
A devServerAsset() 0 4 1
A devServerScript() 0 30 3
B manifestRegisterTags() 0 33 6
A publicAsset() 0 4 1
A script() 0 7 2
A devServerRunning() 0 24 6
B manifestScriptTags() 0 28 6
A invalidateCaches() 0 5 1
A entry() 0 6 1
A asset() 0 11 3
A manifestAsset() 0 14 3
A manifestRegister() 0 31 4
A init() 0 11 4

How to fix   Complexity   

Complex Class

Complex classes like ViteService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ViteService, and based on these observations, apply Extract Interface, too.

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 ($this->devServerRunning() && 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
        $response = FileHelper::fetchResponse($url);
176
        $this->devServerRunningCached = false;
177
        // Status code of 200 or 404 means the dev server is running
178
        if ($response) {
0 ignored issues
show
introduced by
$response is of type Psr\Http\Message\ResponseInterface, thus it always evaluated to true.
Loading history...
179
            $statusCode = $response->getStatusCode();
180
            $this->devServerRunningCached = $statusCode === 200 || $statusCode === 404;
181
        }
182
183
        return $this->devServerRunningCached;
184
    }
185
186
    /**
187
     * Return the contents of a local file (via path) or remote file (via URL),
188
     * or null if the file doesn't exist or couldn't be fetched
189
     * Yii2 aliases and/or environment variables may be used
190
     *
191
     * @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...
192
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
193
     *
194
     * @return string|array|null
195
     */
196
    public function fetch(string $pathOrUrl, callable $callback = null)
197
    {
198
        return FileHelper::fetch($pathOrUrl, $callback, $this->cacheKeySuffix);
199
    }
200
201
    /**
202
     * Register the script tag to the Craft View to load the script from the Vite dev server
203
     *
204
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
205
     * @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...
206
     *
207
     * @return void
208
     * @throws InvalidConfigException
209
     */
210
    public function devServerRegister(string $path, array $scriptTagAttrs = [])
211
    {
212
        $view = Craft::$app->getView();
213
        // Include any dev server shims
214
        if (!$this->devServerShimsIncluded) {
215
            // Include the react-refresh-shim
216
            if ($this->includeReactRefreshShim) {
217
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
218
                // Replace the hard-coded dev server URL with whatever they have theirs set to
219
                $script = str_replace(
220
                    'http://localhost:3000/',
221
                    rtrim($this->devServerPublic, '/') . '/',
222
                    $script
223
                );
224
                $view->registerScript(
225
                    $script,
226
                    $view::POS_HEAD,
227
                    [
228
                        'type' => 'module',
229
                    ],
230
                    'REACT_REFRESH_SHIM'
231
                );
232
            }
233
            $this->devServerShimsIncluded = true;
234
        }
235
        // Include the entry script
236
        $url = FileHelper::createUrl($this->devServerPublic, $path);
237
        $view->registerJsFile(
238
            $url,
239
            array_merge(['type' => 'module'], $scriptTagAttrs),
240
            md5($url . JsonHelper::encode($scriptTagAttrs))
241
        );
242
    }
243
244
    /**
245
     * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file
246
     *
247
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
248
     * @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...
249
     * @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...
250
     * @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...
251
     *
252
     * @return void
253
     * @throws InvalidConfigException
254
     */
255
    public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
256
    {
257
        $view = Craft::$app->getView();
258
        ManifestHelper::fetchManifest($this->manifestPath);
259
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
260
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
261
        // Include any manifest shims
262
        if (!$this->manifestShimsIncluded) {
263
            // Handle the modulepreload-polyfill shim
264
            if ($this->includeModulePreloadShim) {
265
                $view->registerScript(
266
                    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
267
                    $view::POS_HEAD,
268
                    ['type' => 'module'],
269
                    'MODULEPRELOAD_POLYFILL'
270
                );
271
            }
272
            // Handle any legacy polyfills
273
            if (!empty($legacyTags)) {
274
                $view->registerScript(
275
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
276
                    $view::POS_HEAD,
277
                    [],
278
                    'SAFARI_NOMODULE_FIX'
279
                );
280
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
281
                $tags = array_merge($legacyPolyfillTags, $tags);
282
            }
283
            $this->manifestShimsIncluded = true;
284
        }
285
        $this->manifestRegisterTags($tags, $legacyTags);
286
    }
287
288
    /**
289
     * Return the URL for the given entry
290
     *
291
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
292
     *
293
     * @return string
294
     */
295
    public function entry(string $path): string
296
    {
297
        ManifestHelper::fetchManifest($this->manifestPath);
298
        $entry = ManifestHelper::extractEntry($path);
299
300
        return FileHelper::createUrl($this->serverPublic, $entry);
301
    }
302
303
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $public should have a doc-comment as per coding-style.
Loading history...
304
     * Return the URL for the given asset
305
     *
306
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
307
     *
308
     * @return string
309
     */
310
    public function asset(string $path, bool $public = false): string
311
    {
312
        if ($this->devServerRunning()) {
313
            return $this->devServerAsset($path);
314
        }
315
316
        if ($public) {
317
            return $this->publicAsset($path);
318
        }
319
320
        return $this->manifestAsset($path);
321
    }
322
323
    /**
324
     * Return the URL for the asset from the Vite dev server
325
     *
326
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
327
     *
328
     * @return string
329
     */
330
    public function devServerAsset(string $path): string
331
    {
332
        // Return a URL to the given asset
333
        return FileHelper::createUrl($this->devServerPublic, $path);
334
    }
335
336
    /**
337
     * Return the URL for the asset from the public Vite folder
338
     *
339
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
340
     *
341
     * @return string
342
     */
343
    public function publicAsset(string $path): string
344
    {
345
        // Return a URL to the given asset
346
        return FileHelper::createUrl($this->serverPublic, $path);
347
    }
348
349
    /**
350
     * Return the URL for the asset from the manifest.json file
351
     *
352
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
353
     *
354
     * @return string
355
     */
356
    public function manifestAsset(string $path): string
357
    {
358
        ManifestHelper::fetchManifest($this->manifestPath);
359
        $assets = ManifestHelper::extractAssetFiles();
360
        // Get just the file name
361
        $assetKeyParts = explode('/', $path);
362
        $assetKey = end($assetKeyParts);
363
        foreach ($assets as $key => $value) {
364
            if ($key === $assetKey) {
365
                return FileHelper::createUrl($this->serverPublic, $value);
366
            }
367
        }
368
369
        return '';
370
    }
371
372
    /**
373
     * Invalidate all of the Vite caches
374
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
375
    public function invalidateCaches()
376
    {
377
        $cache = Craft::$app->getCache();
378
        TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix);
379
        Craft::info('All Vite caches cleared', __METHOD__);
380
    }
381
382
    /**
383
     * Return the appropriate tags to load the Vite script, either via the dev server or
384
     * extracting it from the manifest.json file
385
     *
386
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
387
     * @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...
388
     * @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...
389
     * @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...
390
     *
391
     * @return string
392
     */
393
    public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
394
    {
395
        if ($this->devServerRunning()) {
396
            return $this->devServerScript($path, $scriptTagAttrs);
397
        }
398
399
        return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
400
    }
401
402
    /**
403
     * Return the script tag to load the script from the Vite dev server
404
     *
405
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
406
     * @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...
407
     *
408
     * @return string
409
     */
410
    public function devServerScript(string $path, array $scriptTagAttrs = []): string
411
    {
412
        $lines = [];
413
        // Include any dev server shims
414
        if (!$this->devServerShimsIncluded) {
415
            // Include the react-refresh-shim
416
            if ($this->includeReactRefreshShim) {
417
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
418
                // Replace the hard-coded dev server URL with whatever they have theirs set to
419
                $script = str_replace(
420
                    'http://localhost:3000/',
421
                    rtrim($this->devServerPublic, '/') . '/',
422
                    $script
423
                );
424
                $lines[] = HtmlHelper::script(
425
                    $script,
426
                    [
427
                        'type' => 'module',
428
                    ]
429
                );
430
            }
431
            $this->devServerShimsIncluded = true;
432
        }
433
        // Include the entry script
434
        $url = FileHelper::createUrl($this->devServerPublic, $path);
435
        $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...
436
            'type' => 'module',
437
        ], $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...
438
439
        return implode("\r\n", $lines);
440
    }
441
442
    /**
443
     * Return the script, module link, and CSS link tags for the script from the manifest.json file
444
     *
445
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
446
     * @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...
447
     * @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...
448
     * @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...
449
     *
450
     * @return string
451
     */
452
    public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
453
    {
454
        $lines = [];
455
        ManifestHelper::fetchManifest($this->manifestPath);
456
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
457
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
458
        // Include any manifest shims
459
        if (!$this->manifestShimsIncluded) {
460
            // Handle the modulepreload-polyfill shim
461
            if ($this->includeModulePreloadShim) {
462
                $lines[] = HtmlHelper::script(
463
                    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
464
                    ['type' => 'module']
465
                );
466
            }
467
            // Handle any legacy polyfills
468
            if (!empty($legacyTags)) {
469
                $lines[] = HtmlHelper::script(
470
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
471
                    []
472
                );
473
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
474
                $tags = array_merge($legacyPolyfillTags, $tags);
475
            }
476
            $this->manifestShimsIncluded = true;
477
        }
478
        $lines = array_merge($lines, $this->manifestScriptTags($tags, $legacyTags));
479
480
        return implode("\r\n", $lines);
481
    }
482
483
    // Protected Methods
484
    // =========================================================================
485
486
    /**
487
     * Iterate through all the tags, and register them
488
     *
489
     * @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...
490
     * @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...
491
     * @throws InvalidConfigException
0 ignored issues
show
Coding Style introduced by
Tag @throws cannot be grouped with parameter tags in a doc comment
Loading history...
492
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
493
    protected function manifestRegisterTags(array $tags, array $legacyTags)
494
    {
495
        $view = Craft::$app->getView();
496
        foreach (array_merge($tags, $legacyTags) as $tag) {
497
            if (!empty($tag)) {
498
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
499
                switch ($tag['type']) {
500
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
501
                        $view->registerJsFile(
502
                            $url,
503
                            $tag['options'],
504
                            md5($url . JsonHelper::encode($tag['options']))
505
                        );
506
                        break;
507
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
508
                        $view->registerCssFile(
509
                            $url,
510
                            $tag['options']
511
                        );
512
                        break;
513
                    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
514
                        $view->registerLinkTag(
515
                            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...
516
                                'crossorigin' => $tag['crossorigin'],
517
                                'href' => $url,
518
                                'rel' => 'modulepreload',
519
                                'integrity' => $tag['integrity'] ?? '',
520
                            ]),
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...
521
                            md5($url)
522
                        );
523
                        break;
524
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
525
                        break;
526
                }
527
            }
528
        }
529
    }
530
531
    /**
532
     * Inject the error entry point JavaScript for auto-reloading of Twig error
533
     * pages
534
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
535
    protected function injectErrorEntry()
536
    {
537
        // If there's no error entry provided, return
538
        if (empty($this->errorEntry)) {
539
            return;
540
        }
541
        // If it's not a server error or a client error, return
542
        $response = Craft::$app->getResponse();
543
        if (!($response->isServerError || $response->isClientError)) {
544
            return;
545
        }
546
        // If the dev server isn't running, return
547
        if (!$this->devServerRunning()) {
548
            return;
549
        }
550
        // Inject the errorEntry script tags to enable HMR on this page
551
        try {
552
            $errorEntry = $this->errorEntry;
553
            if (is_string($errorEntry)) {
0 ignored issues
show
introduced by
The condition is_string($errorEntry) is always true.
Loading history...
554
                $errorEntry = [$errorEntry];
555
            }
556
            foreach ($errorEntry as $entry) {
557
                $tag = $this->script($entry);
558
                if ($tag !== null) {
559
                    echo $tag;
560
                }
561
            }
562
        } catch (Throwable $e) {
563
            // That's okay, Vite will have already logged the error
564
        }
565
    }
566
567
    /**
568
     * Iterate through all the tags, and return them
569
     *
570
     * @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...
571
     * @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...
572
     * @return array
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
573
     */
574
    protected function manifestScriptTags(array $tags, array $legacyTags): array
575
    {
576
        $lines = [];
577
        foreach (array_merge($tags, $legacyTags) as $tag) {
578
            if (!empty($tag)) {
579
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
580
                switch ($tag['type']) {
581
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
582
                        $lines[] = HtmlHelper::jsFile($url, $tag['options']);
583
                        break;
584
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
585
                        $lines[] = HtmlHelper::cssFile($url, $tag['options']);
586
                        break;
587
                    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
588
                        $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...
589
                            'crossorigin' => $tag['crossorigin'],
590
                            'href' => $url,
591
                            'rel' => 'modulepreload',
592
                            'integrity' => $tag['integrity'] ?? '',
593
                        ]));
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...
594
                        break;
595
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
596
                        break;
597
                }
598
            }
599
        }
600
601
        return $lines;
602
    }
603
}
604