Passed
Push — v1 ( fb7abb...482172 )
by Andrew
17:43 queued 14s
created

ViteService   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 628
Duplicated Lines 0 %

Importance

Changes 36
Bugs 2 Features 2
Metric Value
eloc 224
dl 0
loc 628
rs 2.88
c 36
b 2
f 2
wmc 69

19 Methods

Rating   Name   Duplication   Size   Complexity  
A fetch() 0 15 4
A integrity() 0 5 1
B injectErrorEntry() 0 28 9
A manifestScript() 0 29 4
A devServerRegister() 0 31 3
A init() 0 11 4
A devServerAsset() 0 4 1
A devServerScript() 0 30 3
B manifestRegisterTags() 0 36 7
A publicAsset() 0 4 1
A script() 0 14 3
A register() 0 16 3
A devServerRunning() 0 24 6
B manifestScriptTags() 0 31 7
A invalidateCaches() 0 5 1
A entry() 0 6 1
A asset() 0 11 3
A manifestAsset() 0 18 4
A manifestRegister() 0 31 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
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
95
     * @var bool Whether an onload handler should be added to <script> tags to fire a custom event when the script has loaded
96
     */
97
    public $includeScriptOnloadHandler = true;
98
99
    // Protected Properties
100
    // =========================================================================
101
102
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
103
     * @var bool Whether the manifest shims has been included yet or not
104
     */
105
    protected $manifestShimsIncluded = false;
106
107
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
108
     * @var bool Whether the dev server shims has been included yet or not
109
     */
110
    protected $devServerShimsIncluded = false;
111
112
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
113
     * @var null|bool Cached status of whether the devServer is running or not
114
     */
115
    protected $devServerRunningCached = null;
116
117
    // Public Methods
118
    // =========================================================================
119
120
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
121
     * @inheritDoc
122
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
123
    public function init()
124
    {
125
        parent::init();
126
        // Do nothing for console requests
127
        $request = Craft::$app->getRequest();
128
        if ($request->getIsConsoleRequest()) {
129
            return;
130
        }
131
        // Our component is lazily loaded, so the View will be instantiated by now
132
        if ($this->devServerRunning() && Craft::$app->getConfig()->getGeneral()->devMode) {
133
            Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']);
134
        }
135
    }
136
137
    /**
138
     * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or
139
     * extracting it from the manifest.json file
140
     *
141
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
142
     * @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...
143
     * @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...
144
     * @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...
145
     *
146
     * @return void
147
     * @throws InvalidConfigException
148
     */
149
    public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
150
    {
151
        // Filter out empty attributes, but preserve boolean values
152
        $preserveBools = function($value) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
153
            return is_bool($value) || !empty($value);
154
        };
155
        $scriptTagAttrs = array_filter($scriptTagAttrs, $preserveBools);
156
        $cssTagAttrs = array_filter($cssTagAttrs, $preserveBools);
157
158
        if ($this->devServerRunning()) {
159
            $this->devServerRegister($path, $scriptTagAttrs);
160
161
            return;
162
        }
163
164
        $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
165
    }
166
167
    /**
168
     * Determine whether the Vite dev server is running
169
     *
170
     * @return bool
171
     */
172
    public function devServerRunning(): bool
173
    {
174
        if ($this->devServerRunningCached !== null) {
175
            return $this->devServerRunningCached;
176
        }
177
        // If the dev server is turned off via config, say it's not running
178
        if (!$this->useDevServer) {
179
            return false;
180
        }
181
        // If we're not supposed to check that the dev server is actually running, just assume it is
182
        if (!$this->checkDevServer) {
183
            return true;
184
        }
185
        // Check to see if the dev server is actually running by pinging it
186
        $url = FileHelper::createUrl($this->devServerInternal, self::VITE_DEVSERVER_PING);
187
        $response = FileHelper::fetchResponse($url);
188
        $this->devServerRunningCached = false;
189
        // Status code of 200 or 404 means the dev server is running
190
        if ($response) {
0 ignored issues
show
introduced by
$response is of type Psr\Http\Message\ResponseInterface, thus it always evaluated to true.
Loading history...
191
            $statusCode = $response->getStatusCode();
192
            $this->devServerRunningCached = $statusCode === 200 || $statusCode === 404;
193
        }
194
195
        return $this->devServerRunningCached;
196
    }
197
198
    /**
199
     * Return the contents of a local file (via path) or remote file (via URL),
200
     * or null if the file doesn't exist or couldn't be fetched
201
     * Yii2 aliases and/or environment variables may be used
202
     *
203
     * @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...
204
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
205
     *
206
     * @return string|array|null
207
     */
208
    public function fetch(string $pathOrUrl, callable $callback = null)
209
    {
210
        // If the devServer is running, and this is a URL, swap in the devServerInternal URL
211
        if ($this->devServerRunning()) {
212
            if (!filter_var($pathOrUrl, FILTER_VALIDATE_URL) === false) {
213
                $devServerInternalUrl = str_replace($this->devServerPublic, '', $pathOrUrl);
214
                $devServerInternalUrl = FileHelper::createUrl($this->devServerInternal, $devServerInternalUrl);
215
                // If we get a result from the $devServerInternalUrl, return it
216
                if ($devServerInternalResult = FileHelper::fetch($devServerInternalUrl, $callback, $this->cacheKeySuffix)) {
217
                    return $devServerInternalResult;
218
                }
219
            }
220
        }
221
222
        return FileHelper::fetch($pathOrUrl, $callback, $this->cacheKeySuffix);
223
    }
224
225
    /**
226
     * Register the script tag to the Craft View to load the script from the Vite dev server
227
     *
228
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
229
     * @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...
230
     *
231
     * @return void
232
     * @throws InvalidConfigException
233
     */
234
    public function devServerRegister(string $path, array $scriptTagAttrs = [])
235
    {
236
        $view = Craft::$app->getView();
237
        // Include any dev server shims
238
        if (!$this->devServerShimsIncluded) {
239
            // Include the react-refresh-shim
240
            if ($this->includeReactRefreshShim) {
241
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
242
                // Replace the hard-coded dev server URL with whatever they have theirs set to
243
                $script = str_replace(
244
                    'http://localhost:3000/',
245
                    rtrim($this->devServerPublic, '/') . '/',
246
                    $script
247
                );
248
                $view->registerScript(
249
                    $script,
250
                    $view::POS_HEAD,
251
                    [
252
                        'type' => 'module',
253
                    ],
254
                    'REACT_REFRESH_SHIM'
255
                );
256
            }
257
            $this->devServerShimsIncluded = true;
258
        }
259
        // Include the entry script
260
        $url = FileHelper::createUrl($this->devServerPublic, $path);
261
        $view->registerJsFile(
262
            $url,
263
            array_merge(['type' => 'module'], $scriptTagAttrs),
264
            md5($url . JsonHelper::encode($scriptTagAttrs))
265
        );
266
    }
267
268
    /**
269
     * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file
270
     *
271
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
272
     * @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...
273
     * @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...
274
     * @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...
275
     *
276
     * @return void
277
     * @throws InvalidConfigException
278
     */
279
    public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
280
    {
281
        $view = Craft::$app->getView();
282
        ManifestHelper::fetchManifest($this->manifestPath);
283
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
284
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
285
        // Include any manifest shims
286
        if (!$this->manifestShimsIncluded) {
287
            // Handle the modulepreload-polyfill shim
288
            if ($this->includeModulePreloadShim) {
289
                $view->registerScript(
290
                    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
291
                    $view::POS_HEAD,
292
                    ['type' => 'module'],
293
                    'MODULEPRELOAD_POLYFILL'
294
                );
295
            }
296
            // Handle any legacy polyfills
297
            if (!empty($legacyTags)) {
298
                $view->registerScript(
299
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
300
                    $view::POS_HEAD,
301
                    [],
302
                    'SAFARI_NOMODULE_FIX'
303
                );
304
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
305
                $tags = array_merge($legacyPolyfillTags, $tags);
306
            }
307
            $this->manifestShimsIncluded = true;
308
        }
309
        $this->manifestRegisterTags($tags, $legacyTags);
310
    }
311
312
    /**
313
     * Return the URL for the given entry
314
     *
315
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
316
     *
317
     * @return string
318
     */
319
    public function entry(string $path): string
320
    {
321
        ManifestHelper::fetchManifest($this->manifestPath);
322
        $entry = ManifestHelper::extractEntry($path);
323
324
        return FileHelper::createUrl($this->serverPublic, $entry);
325
    }
326
327
    /**
328
     * Return the integrity hash (or an empty string if not present) for the given entry
329
     *
330
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
331
     *
332
     * @return string
333
     */
334
    public function integrity(string $path): string
335
    {
336
        ManifestHelper::fetchManifest($this->manifestPath);
337
338
        return ManifestHelper::extractIntegrity($path);
339
    }
340
341
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $public should have a doc-comment as per coding-style.
Loading history...
342
     * Return the URL for the given asset
343
     *
344
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
345
     *
346
     * @return string
347
     */
348
    public function asset(string $path, bool $public = false): string
349
    {
350
        if ($this->devServerRunning()) {
351
            return $this->devServerAsset($path);
352
        }
353
354
        if ($public) {
355
            return $this->publicAsset($path);
356
        }
357
358
        return $this->manifestAsset($path);
359
    }
360
361
    /**
362
     * Return the URL for the asset from the Vite dev server
363
     *
364
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
365
     *
366
     * @return string
367
     */
368
    public function devServerAsset(string $path): string
369
    {
370
        // Return a URL to the given asset
371
        return FileHelper::createUrl($this->devServerPublic, $path);
372
    }
373
374
    /**
375
     * Return the URL for the asset from the public Vite folder
376
     *
377
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
378
     *
379
     * @return string
380
     */
381
    public function publicAsset(string $path): string
382
    {
383
        // Return a URL to the given asset
384
        return FileHelper::createUrl($this->serverPublic, $path);
385
    }
386
387
    /**
388
     * Return the URL for the asset from the manifest.json file
389
     *
390
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
391
     *
392
     * @return string
393
     */
394
    public function manifestAsset(string $path): string
395
    {
396
        ManifestHelper::fetchManifest($this->manifestPath);
397
        $assets = ManifestHelper::extractAssetFiles();
398
        // Get just the file name
399
        $assetKeyParts = explode('/', $path);
400
        $assetKey = end($assetKeyParts);
401
        foreach ($assets as $key => $value) {
402
            if ($key === $assetKey) {
403
                return FileHelper::createUrl($this->serverPublic, $value);
404
            }
405
        }
406
407
        // With Vite 3.x or later, the assets are also included as top-level entries in the
408
        // manifest, so check there, too
409
        $entry = ManifestHelper::extractEntry($path);
410
411
        return $entry === '' ? '' : FileHelper::createUrl($this->serverPublic, $entry);
412
    }
413
414
    /**
415
     * Invalidate all of the Vite caches
416
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
417
    public function invalidateCaches()
418
    {
419
        $cache = Craft::$app->getCache();
420
        TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix);
421
        Craft::info('All Vite caches cleared', __METHOD__);
422
    }
423
424
    /**
425
     * Return the appropriate tags to load the Vite script, either via the dev server or
426
     * extracting it from the manifest.json file
427
     *
428
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
429
     * @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...
430
     * @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...
431
     * @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...
432
     *
433
     * @return string
434
     */
435
    public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
436
    {
437
        // Filter out empty attributes, but preserve boolean values
438
        $preserveBools = function($value) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
439
            return is_bool($value) || !empty($value);
440
        };
441
        $scriptTagAttrs = array_filter($scriptTagAttrs, $preserveBools);
442
        $cssTagAttrs = array_filter($cssTagAttrs, $preserveBools);
443
444
        if ($this->devServerRunning()) {
445
            return $this->devServerScript($path, $scriptTagAttrs);
446
        }
447
448
        return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
449
    }
450
451
    /**
452
     * Return the script tag to load the script from the Vite dev server
453
     *
454
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
455
     * @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...
456
     *
457
     * @return string
458
     */
459
    public function devServerScript(string $path, array $scriptTagAttrs = []): string
460
    {
461
        $lines = [];
462
        // Include any dev server shims
463
        if (!$this->devServerShimsIncluded) {
464
            // Include the react-refresh-shim
465
            if ($this->includeReactRefreshShim) {
466
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
467
                // Replace the hard-coded dev server URL with whatever they have theirs set to
468
                $script = str_replace(
469
                    'http://localhost:3000/',
470
                    rtrim($this->devServerPublic, '/') . '/',
471
                    $script
472
                );
473
                $lines[] = HtmlHelper::script(
474
                    $script,
475
                    [
476
                        'type' => 'module',
477
                    ]
478
                );
479
            }
480
            $this->devServerShimsIncluded = true;
481
        }
482
        // Include the entry script
483
        $url = FileHelper::createUrl($this->devServerPublic, $path);
484
        $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...
485
            'type' => 'module',
486
        ], $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...
487
488
        return implode("\r\n", $lines);
489
    }
490
491
    /**
492
     * Return the script, module link, and CSS link tags for the script from the manifest.json file
493
     *
494
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
495
     * @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...
496
     * @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...
497
     * @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...
498
     *
499
     * @return string
500
     */
501
    public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
502
    {
503
        $lines = [];
504
        ManifestHelper::fetchManifest($this->manifestPath);
505
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
506
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
507
        // Include any manifest shims
508
        if (!$this->manifestShimsIncluded) {
509
            // Handle the modulepreload-polyfill shim
510
            if ($this->includeModulePreloadShim) {
511
                $lines[] = HtmlHelper::script(
512
                    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
513
                    ['type' => 'module']
514
                );
515
            }
516
            // Handle any legacy polyfills
517
            if (!empty($legacyTags)) {
518
                $lines[] = HtmlHelper::script(
519
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
520
                    []
521
                );
522
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
523
                $tags = array_merge($legacyPolyfillTags, $tags);
524
            }
525
            $this->manifestShimsIncluded = true;
526
        }
527
        $lines = array_merge($lines, $this->manifestScriptTags($tags, $legacyTags));
528
529
        return implode("\r\n", $lines);
530
    }
531
532
    // Protected Methods
533
    // =========================================================================
534
535
    /**
536
     * Iterate through all the tags, and register them
537
     *
538
     * @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...
539
     * @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...
540
     * @throws InvalidConfigException
0 ignored issues
show
Coding Style introduced by
Tag @throws cannot be grouped with parameter tags in a doc comment
Loading history...
541
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
542
    protected function manifestRegisterTags(array $tags, array $legacyTags)
543
    {
544
        $view = Craft::$app->getView();
545
        foreach (array_merge($tags, $legacyTags) as $tag) {
546
            if (!empty($tag)) {
547
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
548
                switch ($tag['type']) {
549
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
550
                        if (!$this->includeScriptOnloadHandler) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
551
                            unset($tag['options']['onload']);
552
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
553
                        $view->registerJsFile(
554
                            $url,
555
                            $tag['options'],
556
                            md5($url . JsonHelper::encode($tag['options']))
557
                        );
558
                        break;
559
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
560
                        $view->registerCssFile(
561
                            $url,
562
                            $tag['options']
563
                        );
564
                        break;
565
                    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
566
                        $view->registerLinkTag(
567
                            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...
568
                                'crossorigin' => $tag['crossorigin'],
569
                                'href' => $url,
570
                                'rel' => 'modulepreload',
571
                                'integrity' => $tag['integrity'] ?? '',
572
                            ]),
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...
573
                            md5($url)
574
                        );
575
                        break;
576
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
577
                        break;
578
                }
579
            }
580
        }
581
    }
582
583
    /**
584
     * Inject the error entry point JavaScript for auto-reloading of Twig error
585
     * pages
586
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
587
    protected function injectErrorEntry()
588
    {
589
        // If there's no error entry provided, return
590
        if (empty($this->errorEntry)) {
591
            return;
592
        }
593
        // If it's not a server error or a client error, return
594
        $response = Craft::$app->getResponse();
595
        if (!($response->isServerError || $response->isClientError)) {
596
            return;
597
        }
598
        // If the dev server isn't running, return
599
        if (!$this->devServerRunning()) {
600
            return;
601
        }
602
        // Inject the errorEntry script tags to enable HMR on this page
603
        try {
604
            $errorEntry = $this->errorEntry;
605
            if (is_string($errorEntry)) {
0 ignored issues
show
introduced by
The condition is_string($errorEntry) is always true.
Loading history...
606
                $errorEntry = [$errorEntry];
607
            }
608
            foreach ($errorEntry as $entry) {
609
                $tag = $this->script($entry);
610
                if ($tag !== null) {
611
                    echo $tag;
612
                }
613
            }
614
        } catch (Throwable $e) {
615
            // That's okay, Vite will have already logged the error
616
        }
617
    }
618
619
    /**
620
     * Iterate through all the tags, and return them
621
     *
622
     * @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...
623
     * @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...
624
     * @return array
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
625
     */
626
    protected function manifestScriptTags(array $tags, array $legacyTags): array
627
    {
628
        $lines = [];
629
        foreach (array_merge($tags, $legacyTags) as $tag) {
630
            if (!empty($tag)) {
631
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
632
                switch ($tag['type']) {
633
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
634
                        if (!$this->includeScriptOnloadHandler) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
635
                            unset($tag['options']['onload']);
636
                        }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 20 spaces, found 24
Loading history...
637
                        $lines[] = HtmlHelper::jsFile($url, $tag['options']);
638
                        break;
639
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
640
                        $lines[] = HtmlHelper::cssFile($url, $tag['options']);
641
                        break;
642
                    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
643
                        $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...
644
                            'crossorigin' => $tag['crossorigin'],
645
                            'href' => $url,
646
                            'rel' => 'modulepreload',
647
                            'integrity' => $tag['integrity'] ?? '',
648
                        ]));
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...
649
                        break;
650
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
651
                        break;
652
                }
653
            }
654
        }
655
656
        return $lines;
657
    }
658
}
659