Passed
Pull Request — v1 (#2)
by John D
08:05
created

ViteService::manifestScript()   C

Complexity

Conditions 12
Paths 120

Size

Total Lines 64
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 1
Metric Value
cc 12
eloc 43
c 7
b 0
f 1
nc 120
nop 4
dl 0
loc 64
rs 6.8

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 nystudio107\pluginvite\helpers\FileHelper;
14
use nystudio107\pluginvite\helpers\ManifestHelper;
15
16
use Craft;
17
use craft\base\Component;
18
use craft\helpers\Html as HtmlHelper;
19
use craft\helpers\Json as JsonHelper;
20
use craft\web\View;
21
22
use yii\base\InvalidConfigException;
23
use yii\caching\TagDependency;
24
25
use Throwable;
26
27
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
28
 * @author    nystudio107
0 ignored issues
show
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...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
29
 * @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...
30
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
31
 */
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...
32
class ViteService extends Component
33
{
34
    // Constants
35
    // =========================================================================
36
37
    const VITE_CLIENT = '@vite/client';
38
    const LEGACY_POLYFILLS = 'vite/legacy-polyfills';
39
40
    // Public Properties
41
    // =========================================================================
42
43
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
44
     * @var bool Should the dev server be used for?
45
     */
46
    public $useDevServer;
47
48
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
49
     * @var string File system path (or URL) to the Vite-built manifest.json
50
     */
51
    public $manifestPath;
52
53
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
54
     * @var string The public URL to the dev server (what appears in `<script src="">` tags
55
     */
56
    public $devServerPublic;
57
58
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
59
     * @var string The public URL to use when not using the dev server
60
     */
61
    public $serverPublic;
62
63
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
64
     * @var string The JavaScript entry from the manifest.json to inject on Twig error pages
65
     *              This can be a string or an array of strings
66
     */
67
    public $errorEntry = '';
68
69
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
70
     * @var string String to be appended to the cache key
71
     */
72
    public $cacheKeySuffix = '';
73
74
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
75
     * @var string The internal URL to the dev server, when accessed from the environment in which PHP is executing
76
     *              This can be the same as `$devServerPublic`, but may be different in containerized or VM setups.
77
     *              ONLY used if $checkDevServer = true
78
     */
79
    public $devServerInternal;
80
81
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
82
     * @var bool Should we check for the presence of the dev server by pinging $devServerInternal to make sure it's running?
83
     */
84
    public $checkDevServer = false;
85
86
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
87
     * @var bool Whether the react-refresh-shim should be included
88
     */
89
    public $includeReactRefreshShim = false;
90
91
    // Protected Properties
92
    // =========================================================================
93
94
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
95
     * @var bool Whether the manifest shims has been included yet or not
96
     */
97
    protected $manifestShimsIncluded = false;
98
99
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
100
     * @var bool Whether the dev server shims has been included yet or not
101
     */
102
    protected $devServerShimsIncluded = false;
103
104
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
105
     * @var bool Whether the modulepreload polyfill has been included yet or not
106
     */
107
    protected $modulepreloadPolyfillIncluded = false;
108
109
    // Public Methods
110
    // =========================================================================
111
112
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
113
     * @inheritDoc
114
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
115
    public function init()
116
    {
117
        parent::init();
118
        // Do nothing for console requests
119
        $request = Craft::$app->getRequest();
120
        if ($request->getIsConsoleRequest()) {
121
            return;
122
        }
123
        // Our component is lazily loaded, so the View will be instantiated by now
124
        if (Craft::$app->getConfig()->getGeneral()->devMode) {
125
            Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']);
126
        }
127
    }
128
129
    /**
130
     * Return the appropriate tags to load the Vite script, either via the dev server or
131
     * extracting it from the manifest.json file
132
     *
133
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
134
     * @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...
135
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
136
     * @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...
137
     *
138
     * @return string
139
     */
140
    public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
141
    {
142
        if ($this->devServerRunning()) {
143
            return $this->devServerScript($path, $scriptTagAttrs);
144
        }
145
146
        return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
147
    }
148
149
    /**
150
     * Return the script tag to load the script from the Vite dev server
151
     *
152
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
153
     * @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...
154
     *
155
     * @return string
156
     */
157
    public function devServerScript(string $path, array $scriptTagAttrs = []): string
158
    {
159
        $lines = [];
160
        // Include any dev server shims
161
        if (!$this->devServerShimsIncluded) {
162
            // Include the react-refresh-shim
163
            if ($this->includeReactRefreshShim) {
164
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
165
                // Replace the hard-coded dev server URL with whatever they have theirs set to
166
                $script = str_replace(
167
                    'http://localhost:3000/',
168
                    rtrim($this->devServerPublic, '/').'/',
169
                    $script
170
                );
171
                $lines[] = HtmlHelper::script(
172
                    $script,
173
                    [
174
                        'type' => 'module',
175
                    ]
176
                );
177
            }
178
            $this->devServerShimsIncluded = true;
179
        }
180
        // Include the entry script
181
        $url = FileHelper::createUrl($this->devServerPublic, $path);
182
        $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...
183
            'type' => 'module',
184
        ], $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...
185
186
        return implode("\r\n", $lines);
187
    }
188
189
    /**
190
     * Return the script, module link, and CSS link tags for the script from the manifest.json file
191
     *
192
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
193
     * @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...
194
     * @param array $scriptTagAttrs
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
195
     * @param array $cssTagAttrs
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
196
     *
197
     * @return string
198
     */
199
    public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
200
    {
201
        $lines = [];
202
        ManifestHelper::fetchManifest($this->manifestPath);
203
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
204
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
205
        // Include any manifest shims
206
        if (!$this->manifestShimsIncluded) {
207
            // Handle any legacy polyfills
208
            if (!empty($legacyTags)) {
209
                $lines[] = HtmlHelper::script(
210
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
211
                    []
212
                );
213
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
214
                $tags = array_merge($legacyPolyfillTags, $tags);
215
            }
216
            $this->manifestShimsIncluded = true;
217
        }
218
219
        foreach(array_merge($tags, $legacyTags) as $tag) {
0 ignored issues
show
Coding Style introduced by
Expected "foreach (...) {\n"; found "foreach(...) {\n"
Loading history...
220
            if (!empty($tag)) {
221
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
222
                switch ($tag['type']) {
223
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
224
                        $lines[] = HtmlHelper::jsFile($url, $tag['options']);
225
                        break;
226
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
227
                        $lines[] = HtmlHelper::cssFile($url, $tag['options']);
228
                        break;
229
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
230
                        break;
231
                }
232
            }
233
        }
234
235
        // modulepreload any imports from modern tags
236
	    $modulepreloadPolyfillRequired = false;
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 5
Loading history...
237
	    foreach($tags as $tag) {
0 ignored issues
show
Coding Style introduced by
Expected "foreach (...) {\n"; found "foreach(...) {\n"
Loading history...
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
238
		    if (!empty($tag)) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 6
Loading history...
239
			    $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 16 spaces, found 7
Loading history...
240
			    switch ($tag['type']) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 16 spaces, found 7
Loading history...
241
				    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 8
Loading history...
242
					    $lines[] = HtmlHelper::tag('link', '', [
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...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 9
Loading history...
Coding Style introduced by
Opening statement of multi-line function call not indented correctly; expected 8 spaces but found 9
Loading history...
243
						    'crossorigin' => $tag['crossorigin'],
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 10
Loading history...
244
						    'href' => $url,
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 10
Loading history...
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
245
						    'rel' => 'modulepreload',
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 10
Loading history...
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
246
					    ]);
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...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 9
Loading history...
247
					    $modulepreloadPolyfillRequired = true;
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 28 spaces, found 9
Loading history...
248
					    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 12 spaces, found 9
Loading history...
249
				    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 8
Loading history...
250
					    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 12 spaces, found 9
Loading history...
251
			    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 7
Loading history...
252
		    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 6
Loading history...
253
	    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
254
	    if($modulepreloadPolyfillRequired && ! $this->modulepreloadPolyfillIncluded) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
255
	        $this->modulepreloadPolyfillIncluded = true;
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 9
Loading history...
256
	        $lines[] = HtmlHelper::script(
0 ignored issues
show
Coding Style introduced by
Opening statement of multi-line function call not indented correctly; expected 8 spaces but found 9
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 9
Loading history...
257
		        FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 10
Loading history...
258
		        ['type' => 'module']
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 10
Loading history...
259
	        );
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 15 spaces, found 9
Loading history...
260
        }
0 ignored issues
show
Coding Style introduced by
Closing brace indented incorrectly; expected 5 spaces, found 8
Loading history...
261
262
        return implode("\r\n", $lines);
263
    }
264
265
    /**
266
     * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or
267
     * extracting it from the manifest.json file
268
     *
269
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
270
     * @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...
271
     * @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...
272
     * @param array $cssTagAttrs
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
273
     *
274
     * @return void
275
     * @throws InvalidConfigException
276
     */
277
    public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
278
    {
279
        if ($this->devServerRunning()) {
280
            $this->devServerRegister($path, $scriptTagAttrs);
281
282
            return;
283
        }
284
285
        $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
286
    }
287
288
    /**
289
     * Register the script tag to the Craft View to load the script from the Vite dev server
290
     *
291
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
292
     * @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...
293
     *
294
     * @return void
295
     * @throws InvalidConfigException
296
     */
297
    public function devServerRegister(string $path, array $scriptTagAttrs = [])
298
    {
299
        $view = Craft::$app->getView();
300
        // Include any dev server shims
301
        if (!$this->devServerShimsIncluded) {
302
            // Include the react-refresh-shim
303
            if ($this->includeReactRefreshShim) {
304
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
305
                // Replace the hard-coded dev server URL with whatever they have theirs set to
306
                $script = str_replace(
307
                    'http://localhost:3000/',
308
                    rtrim($this->devServerPublic, '/').'/',
309
                    $script
310
                );
311
                $view->registerScript(
312
                    $script,
313
                    $view::POS_HEAD,
314
                    [
315
                        'type' => 'module',
316
                    ],
317
                    'REACT_REFRESH_SHIM'
318
                );
319
            }
320
            $this->devServerShimsIncluded = true;
321
        }
322
        // Include the entry script
323
        $url = FileHelper::createUrl($this->devServerPublic, $path);
324
        $view->registerJsFile(
325
            $url,
326
            array_merge(['type' => 'module'], $scriptTagAttrs),
327
            md5($url . JsonHelper::encode($scriptTagAttrs))
328
        );
329
    }
330
331
    /**
332
     * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file
333
     *
334
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
335
     * @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...
336
     * @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...
337
     * @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...
338
     *
339
     * @return void
340
     * @throws InvalidConfigException
341
     */
342
    public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
343
    {
344
        $view = Craft::$app->getView();
345
        ManifestHelper::fetchManifest($this->manifestPath);
346
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
347
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
348
        // Include any manifest shims
349
        if (!$this->manifestShimsIncluded) {
350
            // Handle any legacy polyfills
351
            if (!empty($legacyTags)) {
352
                $view->registerScript(
353
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
354
                    $view::POS_HEAD,
355
                    [],
356
                    'SAFARI_NOMODULE_FIX'
357
                );
358
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
359
                $tags = array_merge($legacyPolyfillTags, $tags);
360
            }
361
            $this->manifestShimsIncluded = true;
362
        }
363
        foreach(array_merge($tags, $legacyTags) as $tag) {
0 ignored issues
show
Coding Style introduced by
Expected "foreach (...) {\n"; found "foreach(...) {\n"
Loading history...
364
            if (!empty($tag)) {
365
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
366
                switch ($tag['type']) {
367
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
368
                        $view->registerJsFile(
369
                            $url,
370
                            $tag['options'],
371
                            md5($url . JsonHelper::encode($tag['options']))
372
                        );
373
                        break;
374
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
375
                        $view->registerCssFile(
376
                            $url,
377
                            $tag['options']
378
                        );
379
                        break;
380
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
381
                        break;
382
                }
383
            }
384
        }
385
386
	    // modulepreload any imports from modern tags
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 5
Loading history...
387
	    $modulepreloadPolyfillRequired = false;
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 5
Loading history...
388
	    foreach($tags as $tag) {
0 ignored issues
show
Coding Style introduced by
Expected "foreach (...) {\n"; found "foreach(...) {\n"
Loading history...
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
389
		    if (!empty($tag)) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 6
Loading history...
390
			    $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 16 spaces, found 7
Loading history...
391
			    switch ($tag['type']) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 16 spaces, found 7
Loading history...
392
				    case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 8
Loading history...
393
					    $view->registerLinkTag(
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 9
Loading history...
Coding Style introduced by
Opening statement of multi-line function call not indented correctly; expected 8 spaces but found 9
Loading history...
394
						    [
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 10
Loading history...
395
							    'crossorigin' => $tag['crossorigin'],
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 11.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 11
Loading history...
396
							    'href' => $url,
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 11.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 11
Loading history...
397
							    'rel' => 'modulepreload',
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 11.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 11
Loading history...
398
						    ],
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 10
Loading history...
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
399
						    md5($url)
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 10
Loading history...
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 13 spaces, but found 10.
Loading history...
400
					    );
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 28 spaces, found 9
Loading history...
401
					    $modulepreloadPolyfillRequired = true;
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 28 spaces, found 9
Loading history...
402
					    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 12 spaces, found 9
Loading history...
403
				    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 8
Loading history...
404
					    break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 12 spaces, found 9
Loading history...
405
			    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 7
Loading history...
406
		    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 6
Loading history...
407
	    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
408
	    if($modulepreloadPolyfillRequired && ! $this->modulepreloadPolyfillIncluded) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
409
		    $this->modulepreloadPolyfillIncluded = true;
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 6
Loading history...
410
		    $view->registerScript(
0 ignored issues
show
Coding Style introduced by
Opening statement of multi-line function call not indented correctly; expected 4 spaces but found 6
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 6
Loading history...
411
			    FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 10 spaces, but found 7.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 7
Loading history...
412
			    $view::POS_HEAD,
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 10 spaces, but found 7.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 7
Loading history...
413
			    ['type' => 'module'],
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 10 spaces, but found 7.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 7
Loading history...
414
			    'MODULEPRELOAD_POLYFILL'
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 12 spaces, found 7
Loading history...
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 10 spaces, but found 7.
Loading history...
415
		    );
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 15 spaces, found 6
Loading history...
416
	    }
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 8 spaces, found 5
Loading history...
417
    }
418
419
    /**
420
     * Return the contents of a local file (via path) or remote file (via URL),
421
     * or null if the file doesn't exist or couldn't be fetched
422
     * Yii2 aliases and/or environment variables may be used
423
     *
424
     * @param string $pathOrUrl
0 ignored issues
show
Coding Style introduced by
Expected 8 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
425
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
426
     *
427
     * @return string|array|null
428
     */
429
    public function fetch(string $pathOrUrl, callable $callback = null)
430
    {
431
        return FileHelper::fetch($pathOrUrl, $callback, $this->cacheKeySuffix);
432
    }
433
434
    /**
435
     * Determine whether the Vite dev server is running
436
     *
437
     * @return bool
438
     */
439
    public function devServerRunning(): bool
440
    {
441
        // If the dev server is turned off via config, say it's not running
442
        if (!$this->useDevServer) {
443
            return false;
444
        }
445
        // If we're not supposed to check that the dev server is actually running, just assume it is
446
        if (!$this->checkDevServer) {
447
            return true;
448
        }
449
        // Check to see if the dev server is actually running by pinging it
450
        $url = FileHelper::createUrl($this->devServerInternal, self::VITE_CLIENT);
451
452
        return !($this->fetch($url) === null);
453
    }
454
455
    /**
456
     * Invalidate all of the Vite caches
457
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
458
    public function invalidateCaches()
459
    {
460
        $cache = Craft::$app->getCache();
461
        TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix);
462
        Craft::info('All Vite caches cleared', __METHOD__);
463
    }
464
465
    // Protected Methods
466
    // =========================================================================
467
468
    /**
469
     * Inject the error entry point JavaScript for auto-reloading of Twig error
470
     * pages
471
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
472
    protected function injectErrorEntry()
473
    {
474
        // If there's no error entry provided, return
475
        if (empty($this->errorEntry)) {
476
            return;
477
        }
478
        // If it's not a server error or a client error, return
479
        $response = Craft::$app->getResponse();
480
        if (!($response->isServerError || $response->isClientError)) {
481
            return;
482
        }
483
        // If the dev server isn't running, return
484
        if (!$this->devServerRunning()) {
485
            return;
486
        }
487
        // Inject the errorEntry script tags to enable HMR on this page
488
        try {
489
            $errorEntry = $this->errorEntry;
490
            if (is_string($errorEntry)) {
0 ignored issues
show
introduced by
The condition is_string($errorEntry) is always true.
Loading history...
491
                $errorEntry = [$errorEntry];
492
            }
493
            foreach ($errorEntry as $entry) {
494
                $tag = $this->script($entry);
495
                if ($tag !== null) {
496
                    echo $tag;
497
                }
498
            }
499
        } catch (Throwable $e) {
500
            // That's okay, Vite will have already logged the error
501
        }
502
    }
503
}
504