Total Complexity | 69 |
Total Lines | 628 |
Duplicated Lines | 0 % |
Changes | 36 | ||
Bugs | 2 | Features | 2 |
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 |
||
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 | /** |
||
42 | * @var bool Should the dev server be used for? |
||
43 | */ |
||
44 | public $useDevServer; |
||
45 | |||
46 | /** |
||
47 | * @var string File system path (or URL) to the Vite-built manifest.json |
||
48 | */ |
||
49 | public $manifestPath; |
||
50 | |||
51 | /** |
||
52 | * @var string The public URL to the dev server (what appears in `<script src="">` tags |
||
53 | */ |
||
54 | public $devServerPublic; |
||
55 | |||
56 | /** |
||
57 | * @var string The public URL to use when not using the dev server |
||
58 | */ |
||
59 | public $serverPublic; |
||
60 | |||
61 | /** |
||
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 | /** |
||
68 | * @var string String to be appended to the cache key |
||
69 | */ |
||
70 | public $cacheKeySuffix = ''; |
||
71 | |||
72 | /** |
||
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 | /** |
||
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 | /** |
||
85 | * @var bool Whether the react-refresh-shim should be included |
||
86 | */ |
||
87 | public $includeReactRefreshShim = false; |
||
88 | |||
89 | /** |
||
90 | * @var bool Whether the modulepreload-polyfill shim should be included |
||
91 | */ |
||
92 | public $includeModulePreloadShim = true; |
||
93 | |||
94 | /** |
||
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 | /** |
||
103 | * @var bool Whether the manifest shims has been included yet or not |
||
104 | */ |
||
105 | protected $manifestShimsIncluded = false; |
||
106 | |||
107 | /** |
||
108 | * @var bool Whether the dev server shims has been included yet or not |
||
109 | */ |
||
110 | protected $devServerShimsIncluded = false; |
||
111 | |||
112 | /** |
||
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 | /** |
||
121 | * @inheritDoc |
||
122 | */ |
||
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 |
||
142 | * @param bool $asyncCss |
||
143 | * @param array $scriptTagAttrs |
||
144 | * @param array $cssTagAttrs |
||
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) { |
||
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) { |
||
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 |
||
204 | * @param callable|null $callback |
||
205 | * |
||
206 | * @return string|array|null |
||
207 | */ |
||
208 | public function fetch(string $pathOrUrl, callable $callback = null) |
||
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 |
||
229 | * @param array $scriptTagAttrs |
||
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 |
||
272 | * @param bool $asyncCss |
||
273 | * @param array $scriptTagAttrs |
||
274 | * @param array $cssTagAttrs |
||
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 |
||
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 |
||
331 | * |
||
332 | * @return string |
||
333 | */ |
||
334 | public function integrity(string $path): string |
||
339 | } |
||
340 | |||
341 | /** |
||
342 | * Return the URL for the given asset |
||
343 | * |
||
344 | * @param string $path |
||
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 |
||
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 |
||
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 |
||
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 | */ |
||
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 |
||
429 | * @param bool $asyncCss |
||
430 | * @param array $scriptTagAttrs |
||
431 | * @param array $cssTagAttrs |
||
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) { |
||
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 |
||
455 | * @param array $scriptTagAttrs |
||
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([ |
||
485 | 'type' => 'module', |
||
486 | ], $scriptTagAttrs)); |
||
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 |
||
495 | * @param bool $asyncCss |
||
496 | * @param array $scriptTagAttrs |
||
497 | * @param array $cssTagAttrs |
||
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 |
||
539 | * @param array $legacyTags |
||
540 | * @throws InvalidConfigException |
||
541 | */ |
||
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': |
||
550 | if (!$this->includeScriptOnloadHandler) { |
||
551 | unset($tag['options']['onload']); |
||
552 | } |
||
553 | $view->registerJsFile( |
||
554 | $url, |
||
555 | $tag['options'], |
||
556 | md5($url . JsonHelper::encode($tag['options'])) |
||
557 | ); |
||
558 | break; |
||
559 | case 'css': |
||
560 | $view->registerCssFile( |
||
561 | $url, |
||
562 | $tag['options'] |
||
563 | ); |
||
564 | break; |
||
565 | case 'import': |
||
566 | $view->registerLinkTag( |
||
567 | array_filter([ |
||
568 | 'crossorigin' => $tag['crossorigin'], |
||
569 | 'href' => $url, |
||
570 | 'rel' => 'modulepreload', |
||
571 | 'integrity' => $tag['integrity'] ?? '', |
||
572 | ]), |
||
573 | md5($url) |
||
574 | ); |
||
575 | break; |
||
576 | default: |
||
577 | break; |
||
578 | } |
||
579 | } |
||
580 | } |
||
581 | } |
||
582 | |||
583 | /** |
||
584 | * Inject the error entry point JavaScript for auto-reloading of Twig error |
||
585 | * pages |
||
586 | */ |
||
587 | protected function injectErrorEntry() |
||
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 |
||
623 | * @param array $legacyTags |
||
624 | * @return array |
||
625 | */ |
||
626 | protected function manifestScriptTags(array $tags, array $legacyTags): array |
||
657 | } |
||
658 | } |
||
659 |