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

ViteService::manifestScript()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 44
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 0 Features 1
Metric Value
cc 8
eloc 30
nc 18
nop 4
dl 0
loc 44
rs 8.1954
c 7
b 0
f 1
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
    // Public Methods
105
    // =========================================================================
106
107
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
108
     * @inheritDoc
109
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
110
    public function init()
111
    {
112
        parent::init();
113
        // Do nothing for console requests
114
        $request = Craft::$app->getRequest();
115
        if ($request->getIsConsoleRequest()) {
116
            return;
117
        }
118
        // Our component is lazily loaded, so the View will be instantiated by now
119
        if (Craft::$app->getConfig()->getGeneral()->devMode) {
120
            Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']);
121
        }
122
    }
123
124
    /**
125
     * Return the appropriate tags to load the Vite script, either via the dev server or
126
     * extracting it from the manifest.json file
127
     *
128
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
129
     * @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...
130
     * @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...
131
     * @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...
132
     *
133
     * @return string
134
     */
135
    public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
136
    {
137
        if ($this->devServerRunning()) {
138
            return $this->devServerScript($path, $scriptTagAttrs);
139
        }
140
141
        return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
142
    }
143
144
    /**
145
     * Return the script tag to load the script from the Vite dev server
146
     *
147
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
148
     * @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...
149
     *
150
     * @return string
151
     */
152
    public function devServerScript(string $path, array $scriptTagAttrs = []): string
153
    {
154
        $lines = [];
155
        // Include any dev server shims
156
        if (!$this->devServerShimsIncluded) {
157
            // Include the react-refresh-shim
158
            if ($this->includeReactRefreshShim) {
159
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
160
                // Replace the hard-coded dev server URL with whatever they have theirs set to
161
                $script = str_replace(
162
                    'http://localhost:3000/',
163
                    rtrim($this->devServerPublic, '/').'/',
164
                    $script
165
                );
166
                $lines[] = HtmlHelper::script(
167
                    $script,
168
                    [
169
                        'type' => 'module',
170
                    ]
171
                );
172
            }
173
            $this->devServerShimsIncluded = true;
174
        }
175
        // Include the entry script
176
        $url = FileHelper::createUrl($this->devServerPublic, $path);
177
        $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...
178
            'type' => 'module',
179
        ], $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...
180
181
        return implode("\r\n", $lines);
182
    }
183
184
    /**
185
     * Return the script, module link, and CSS link tags for the script from the manifest.json file
186
     *
187
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
188
     * @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...
189
     * @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...
190
     * @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...
191
     *
192
     * @return string
193
     */
194
    public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string
195
    {
196
        $lines = [];
197
        ManifestHelper::fetchManifest($this->manifestPath);
198
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
199
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
200
        // Include any manifest shims
201
        if (!$this->manifestShimsIncluded) {
202
            // Handle any legacy polyfills
203
            if (!empty($legacyTags)) {
204
                $lines[] = HtmlHelper::script(
205
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
206
                    []
207
                );
208
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
209
                $tags = array_merge($legacyPolyfillTags, $tags);
210
            }
211
            $this->manifestShimsIncluded = true;
212
        }
213
214
        foreach(array_merge($tags, $legacyTags) as $tag) {
0 ignored issues
show
Coding Style introduced by
Expected "foreach (...) {\n"; found "foreach(...) {\n"
Loading history...
215
            if (!empty($tag)) {
216
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
217
                switch ($tag['type']) {
218
	                case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 17
Loading history...
219
		                $lines[] = HtmlHelper::tag('link', '', [
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 18
Loading history...
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
Opening statement of multi-line function call not indented correctly; expected 16 spaces but found 18
Loading history...
220
			                '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 22 spaces, but found 19.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 19
Loading history...
221
			                '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 22 spaces, but found 19.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 19
Loading history...
222
			                '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 22 spaces, but found 19.
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 20 spaces, found 19
Loading history...
223
		                ]);
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 18
Loading history...
224
	                	break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 21 spaces, found 18
Loading history...
225
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
226
                        $lines[] = HtmlHelper::jsFile($url, $tag['options']);
227
                        break;
228
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
229
                        $lines[] = HtmlHelper::cssFile($url, $tag['options']);
230
                        break;
231
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
232
                        break;
233
                }
234
            }
235
        }
236
237
        return implode("\r\n", $lines);
238
    }
239
240
    /**
241
     * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or
242
     * extracting it from the manifest.json file
243
     *
244
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
245
     * @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...
246
     * @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...
247
     * @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...
248
     *
249
     * @return void
250
     * @throws InvalidConfigException
251
     */
252
    public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
253
    {
254
        if ($this->devServerRunning()) {
255
            $this->devServerRegister($path, $scriptTagAttrs);
256
257
            return;
258
        }
259
260
        $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
261
    }
262
263
    /**
264
     * Register the script tag to the Craft View to load the script from the Vite dev server
265
     *
266
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
267
     * @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...
268
     *
269
     * @return void
270
     * @throws InvalidConfigException
271
     */
272
    public function devServerRegister(string $path, array $scriptTagAttrs = [])
273
    {
274
        $view = Craft::$app->getView();
275
        // Include any dev server shims
276
        if (!$this->devServerShimsIncluded) {
277
            // Include the react-refresh-shim
278
            if ($this->includeReactRefreshShim) {
279
                $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix);
280
                // Replace the hard-coded dev server URL with whatever they have theirs set to
281
                $script = str_replace(
282
                    'http://localhost:3000/',
283
                    rtrim($this->devServerPublic, '/').'/',
284
                    $script
285
                );
286
                $view->registerScript(
287
                    $script,
288
                    $view::POS_HEAD,
289
                    [
290
                        'type' => 'module',
291
                    ],
292
                    'REACT_REFRESH_SHIM'
293
                );
294
            }
295
            $this->devServerShimsIncluded = true;
296
        }
297
        // Include the entry script
298
        $url = FileHelper::createUrl($this->devServerPublic, $path);
299
        $view->registerJsFile(
300
            $url,
301
            array_merge(['type' => 'module'], $scriptTagAttrs),
302
            md5($url . JsonHelper::encode($scriptTagAttrs))
303
        );
304
    }
305
306
    /**
307
     * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file
308
     *
309
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
310
     * @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...
311
     * @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...
312
     * @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...
313
     *
314
     * @return void
315
     * @throws InvalidConfigException
316
     */
317
    public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [])
318
    {
319
        $view = Craft::$app->getView();
320
        ManifestHelper::fetchManifest($this->manifestPath);
321
        $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
322
        $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs);
323
        // Include any manifest shims
324
        if (!$this->manifestShimsIncluded) {
325
            // Handle any legacy polyfills
326
            if (!empty($legacyTags)) {
327
                $view->registerScript(
328
                    FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix),
329
                    $view::POS_HEAD,
330
                    [],
331
                    'SAFARI_NOMODULE_FIX'
332
                );
333
                $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true);
334
                $tags = array_merge($legacyPolyfillTags, $tags);
335
            }
336
            $this->manifestShimsIncluded = true;
337
        }
338
        foreach(array_merge($tags, $legacyTags) as $tag) {
0 ignored issues
show
Coding Style introduced by
Expected "foreach (...) {\n"; found "foreach(...) {\n"
Loading history...
339
            if (!empty($tag)) {
340
                $url = FileHelper::createUrl($this->serverPublic, $tag['url']);
341
                switch ($tag['type']) {
342
	                case 'import':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 17
Loading history...
343
                        $view->registerLinkTag(
344
	                        [
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 28 spaces, but found 25.
Loading history...
345
		                        '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 28 spaces, but found 26.
Loading history...
346
		                        '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 28 spaces, but found 26.
Loading history...
347
		                        '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 28 spaces, but found 26.
Loading history...
348
	                        ],
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 28 spaces, but found 25.
Loading history...
349
	                        md5($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 28 spaces, but found 25.
Loading history...
350
                        );
351
		                break;
0 ignored issues
show
Coding Style introduced by
Case breaking statement indented incorrectly; expected 21 spaces, found 18
Loading history...
352
                    case 'file':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
353
                        $view->registerJsFile(
354
                            $url,
355
                            $tag['options'],
356
                            md5($url . JsonHelper::encode($tag['options']))
357
                        );
358
                        break;
359
                    case 'css':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
360
                        $view->registerCssFile(
361
                            $url,
362
                            $tag['options']
363
                        );
364
                        break;
365
                    default:
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 16 spaces, found 20
Loading history...
366
                        break;
367
                }
368
            }
369
        }
370
    }
371
372
    /**
373
     * Return the contents of a local file (via path) or remote file (via URL),
374
     * or null if the file doesn't exist or couldn't be fetched
375
     * Yii2 aliases and/or environment variables may be used
376
     *
377
     * @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...
378
     * @param callable|null $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
379
     *
380
     * @return string|array|null
381
     */
382
    public function fetch(string $pathOrUrl, callable $callback = null)
383
    {
384
        return FileHelper::fetch($pathOrUrl, $callback, $this->cacheKeySuffix);
385
    }
386
387
    /**
388
     * Determine whether the Vite dev server is running
389
     *
390
     * @return bool
391
     */
392
    public function devServerRunning(): bool
393
    {
394
        // If the dev server is turned off via config, say it's not running
395
        if (!$this->useDevServer) {
396
            return false;
397
        }
398
        // If we're not supposed to check that the dev server is actually running, just assume it is
399
        if (!$this->checkDevServer) {
400
            return true;
401
        }
402
        // Check to see if the dev server is actually running by pinging it
403
        $url = FileHelper::createUrl($this->devServerInternal, self::VITE_CLIENT);
404
405
        return !($this->fetch($url) === null);
406
    }
407
408
    /**
409
     * Invalidate all of the Vite caches
410
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
411
    public function invalidateCaches()
412
    {
413
        $cache = Craft::$app->getCache();
414
        TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix);
415
        Craft::info('All Vite caches cleared', __METHOD__);
416
    }
417
418
    // Protected Methods
419
    // =========================================================================
420
421
    /**
422
     * Inject the error entry point JavaScript for auto-reloading of Twig error
423
     * pages
424
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
425
    protected function injectErrorEntry()
426
    {
427
        // If there's no error entry provided, return
428
        if (empty($this->errorEntry)) {
429
            return;
430
        }
431
        // If it's not a server error or a client error, return
432
        $response = Craft::$app->getResponse();
433
        if (!($response->isServerError || $response->isClientError)) {
434
            return;
435
        }
436
        // If the dev server isn't running, return
437
        if (!$this->devServerRunning()) {
438
            return;
439
        }
440
        // Inject the errorEntry script tags to enable HMR on this page
441
        try {
442
            $errorEntry = $this->errorEntry;
443
            if (is_string($errorEntry)) {
0 ignored issues
show
introduced by
The condition is_string($errorEntry) is always true.
Loading history...
444
                $errorEntry = [$errorEntry];
445
            }
446
            foreach ($errorEntry as $entry) {
447
                $tag = $this->script($entry);
448
                if ($tag !== null) {
449
                    echo $tag;
450
                }
451
            }
452
        } catch (Throwable $e) {
453
            // That's okay, Vite will have already logged the error
454
        }
455
    }
456
}
457