| Total Complexity | 57 |
| Total Lines | 567 |
| Duplicated Lines | 0 % |
| Changes | 31 | ||
| Bugs | 1 | 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 | // Protected Properties |
||
| 95 | // ========================================================================= |
||
| 96 | |||
| 97 | /** |
||
| 98 | * @var bool Whether the manifest shims has been included yet or not |
||
| 99 | */ |
||
| 100 | protected $manifestShimsIncluded = false; |
||
| 101 | |||
| 102 | /** |
||
| 103 | * @var bool Whether the dev server shims has been included yet or not |
||
| 104 | */ |
||
| 105 | protected $devServerShimsIncluded = false; |
||
| 106 | |||
| 107 | /** |
||
| 108 | * @var null|bool Cached status of whether the devServer is running or not |
||
| 109 | */ |
||
| 110 | protected $devServerRunningCached = null; |
||
| 111 | |||
| 112 | // Public Methods |
||
| 113 | // ========================================================================= |
||
| 114 | |||
| 115 | /** |
||
| 116 | * @inheritDoc |
||
| 117 | */ |
||
| 118 | public function init() |
||
| 119 | { |
||
| 120 | parent::init(); |
||
| 121 | // Do nothing for console requests |
||
| 122 | $request = Craft::$app->getRequest(); |
||
| 123 | if ($request->getIsConsoleRequest()) { |
||
| 124 | return; |
||
| 125 | } |
||
| 126 | // Our component is lazily loaded, so the View will be instantiated by now |
||
| 127 | if (Craft::$app->getConfig()->getGeneral()->devMode) { |
||
| 128 | Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']); |
||
| 129 | } |
||
| 130 | } |
||
| 131 | |||
| 132 | /** |
||
| 133 | * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or |
||
| 134 | * extracting it from the manifest.json file |
||
| 135 | * |
||
| 136 | * @param string $path |
||
| 137 | * @param bool $asyncCss |
||
| 138 | * @param array $scriptTagAttrs |
||
| 139 | * @param array $cssTagAttrs |
||
| 140 | * |
||
| 141 | * @return void |
||
| 142 | * @throws InvalidConfigException |
||
| 143 | */ |
||
| 144 | public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 145 | { |
||
| 146 | if ($this->devServerRunning()) { |
||
| 147 | $this->devServerRegister($path, $scriptTagAttrs); |
||
| 148 | |||
| 149 | return; |
||
| 150 | } |
||
| 151 | |||
| 152 | $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 153 | } |
||
| 154 | |||
| 155 | /** |
||
| 156 | * Determine whether the Vite dev server is running |
||
| 157 | * |
||
| 158 | * @return bool |
||
| 159 | */ |
||
| 160 | public function devServerRunning(): bool |
||
| 161 | { |
||
| 162 | if ($this->devServerRunningCached !== null) { |
||
| 163 | return $this->devServerRunningCached; |
||
| 164 | } |
||
| 165 | // If the dev server is turned off via config, say it's not running |
||
| 166 | if (!$this->useDevServer) { |
||
| 167 | return false; |
||
| 168 | } |
||
| 169 | // If we're not supposed to check that the dev server is actually running, just assume it is |
||
| 170 | if (!$this->checkDevServer) { |
||
| 171 | return true; |
||
| 172 | } |
||
| 173 | // Check to see if the dev server is actually running by pinging it |
||
| 174 | $url = FileHelper::createUrl($this->devServerInternal, self::VITE_DEVSERVER_PING); |
||
| 175 | $this->devServerRunningCached = !($this->fetch($url) === null); |
||
| 176 | |||
| 177 | return $this->devServerRunningCached; |
||
| 178 | } |
||
| 179 | |||
| 180 | /** |
||
| 181 | * Return the contents of a local file (via path) or remote file (via URL), |
||
| 182 | * or null if the file doesn't exist or couldn't be fetched |
||
| 183 | * Yii2 aliases and/or environment variables may be used |
||
| 184 | * |
||
| 185 | * @param string $pathOrUrl |
||
| 186 | * @param callable|null $callback |
||
| 187 | * |
||
| 188 | * @return string|array|null |
||
| 189 | */ |
||
| 190 | public function fetch(string $pathOrUrl, callable $callback = null) |
||
| 193 | } |
||
| 194 | |||
| 195 | /** |
||
| 196 | * Register the script tag to the Craft View to load the script from the Vite dev server |
||
| 197 | * |
||
| 198 | * @param string $path |
||
| 199 | * @param array $scriptTagAttrs |
||
| 200 | * |
||
| 201 | * @return void |
||
| 202 | * @throws InvalidConfigException |
||
| 203 | */ |
||
| 204 | public function devServerRegister(string $path, array $scriptTagAttrs = []) |
||
| 235 | ); |
||
| 236 | } |
||
| 237 | |||
| 238 | /** |
||
| 239 | * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file |
||
| 240 | * |
||
| 241 | * @param string $path |
||
| 242 | * @param bool $asyncCss |
||
| 243 | * @param array $scriptTagAttrs |
||
| 244 | * @param array $cssTagAttrs |
||
| 245 | * |
||
| 246 | * @return void |
||
| 247 | * @throws InvalidConfigException |
||
| 248 | */ |
||
| 249 | public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 250 | { |
||
| 251 | $view = Craft::$app->getView(); |
||
| 252 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 253 | $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 254 | $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 255 | // Include any manifest shims |
||
| 256 | if (!$this->manifestShimsIncluded) { |
||
| 257 | // Handle the modulepreload-polyfill shim |
||
| 258 | if ($this->includeModulePreloadShim) { |
||
| 259 | $view->registerScript( |
||
| 260 | FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix), |
||
| 261 | $view::POS_HEAD, |
||
| 262 | ['type' => 'module'], |
||
| 263 | 'MODULEPRELOAD_POLYFILL' |
||
| 264 | ); |
||
| 265 | } |
||
| 266 | // Handle any legacy polyfills |
||
| 267 | if (!empty($legacyTags)) { |
||
| 268 | $view->registerScript( |
||
| 269 | FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix), |
||
| 270 | $view::POS_HEAD, |
||
| 271 | [], |
||
| 272 | 'SAFARI_NOMODULE_FIX' |
||
| 273 | ); |
||
| 274 | $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 275 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 276 | } |
||
| 277 | $this->manifestShimsIncluded = true; |
||
| 278 | } |
||
| 279 | $this->manifestRegisterTags($tags, $legacyTags); |
||
| 280 | } |
||
| 281 | |||
| 282 | /** |
||
| 283 | * Return the URL for the given entry |
||
| 284 | * |
||
| 285 | * @param string $path |
||
| 286 | * |
||
| 287 | * @return string |
||
| 288 | */ |
||
| 289 | public function entry(string $path): string |
||
| 295 | } |
||
| 296 | |||
| 297 | /** |
||
| 298 | * Return the URL for the given asset |
||
| 299 | * |
||
| 300 | * @param string $path |
||
| 301 | * |
||
| 302 | * @return string |
||
| 303 | */ |
||
| 304 | public function asset(string $path, bool $public=false): string |
||
| 305 | { |
||
| 306 | if ($this->devServerRunning()) { |
||
| 307 | return $this->devServerAsset($path); |
||
| 308 | } |
||
| 309 | |||
| 310 | if ($public) { |
||
| 311 | return $this->publicAsset($path); |
||
| 312 | } |
||
| 313 | |||
| 314 | return $this->manifestAsset($path); |
||
| 315 | } |
||
| 316 | |||
| 317 | /** |
||
| 318 | * Return the URL for the asset from the Vite dev server |
||
| 319 | * |
||
| 320 | * @param string $path |
||
| 321 | * |
||
| 322 | * @return string |
||
| 323 | */ |
||
| 324 | public function devServerAsset(string $path): string |
||
| 325 | { |
||
| 326 | // Return a URL to the given asset |
||
| 327 | return FileHelper::createUrl($this->devServerPublic, $path); |
||
| 328 | } |
||
| 329 | |||
| 330 | /** |
||
| 331 | * Return the URL for the asset from the public Vite folder |
||
| 332 | * |
||
| 333 | * @param string $path |
||
| 334 | * |
||
| 335 | * @return string |
||
| 336 | */ |
||
| 337 | public function publicAsset(string $path): string |
||
| 338 | { |
||
| 339 | // Return a URL to the given asset |
||
| 340 | return FileHelper::createUrl($this->serverPublic, $path); |
||
| 341 | } |
||
| 342 | |||
| 343 | /** |
||
| 344 | * Return the URL for the asset from the manifest.json file |
||
| 345 | * |
||
| 346 | * @param string $path |
||
| 347 | * |
||
| 348 | * @return string |
||
| 349 | */ |
||
| 350 | public function manifestAsset(string $path): string |
||
| 351 | { |
||
| 352 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 353 | $assets = ManifestHelper::extractAssetFiles(); |
||
| 354 | // Get just the file name |
||
| 355 | $assetKeyParts = explode('/', $path); |
||
| 356 | $assetKey = end($assetKeyParts); |
||
| 357 | foreach ($assets as $key => $value) { |
||
| 358 | if ($key === $assetKey) { |
||
| 359 | return FileHelper::createUrl($this->serverPublic, $value); |
||
| 360 | } |
||
| 361 | } |
||
| 362 | |||
| 363 | return ''; |
||
| 364 | } |
||
| 365 | |||
| 366 | /** |
||
| 367 | * Invalidate all of the Vite caches |
||
| 368 | */ |
||
| 369 | public function invalidateCaches() |
||
| 370 | { |
||
| 371 | $cache = Craft::$app->getCache(); |
||
| 372 | TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix); |
||
| 373 | Craft::info('All Vite caches cleared', __METHOD__); |
||
| 374 | } |
||
| 375 | |||
| 376 | /** |
||
| 377 | * Return the appropriate tags to load the Vite script, either via the dev server or |
||
| 378 | * extracting it from the manifest.json file |
||
| 379 | * |
||
| 380 | * @param string $path |
||
| 381 | * @param bool $asyncCss |
||
| 382 | * @param array $scriptTagAttrs |
||
| 383 | * @param array $cssTagAttrs |
||
| 384 | * |
||
| 385 | * @return string |
||
| 386 | */ |
||
| 387 | public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 388 | { |
||
| 389 | if ($this->devServerRunning()) { |
||
| 390 | return $this->devServerScript($path, $scriptTagAttrs); |
||
| 391 | } |
||
| 392 | |||
| 393 | return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 394 | } |
||
| 395 | |||
| 396 | /** |
||
| 397 | * Return the script tag to load the script from the Vite dev server |
||
| 398 | * |
||
| 399 | * @param string $path |
||
| 400 | * @param array $scriptTagAttrs |
||
| 401 | * |
||
| 402 | * @return string |
||
| 403 | */ |
||
| 404 | public function devServerScript(string $path, array $scriptTagAttrs = []): string |
||
| 405 | { |
||
| 406 | $lines = []; |
||
| 407 | // Include any dev server shims |
||
| 408 | if (!$this->devServerShimsIncluded) { |
||
| 409 | // Include the react-refresh-shim |
||
| 410 | if ($this->includeReactRefreshShim) { |
||
| 411 | $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix); |
||
| 412 | // Replace the hard-coded dev server URL with whatever they have theirs set to |
||
| 413 | $script = str_replace( |
||
| 414 | 'http://localhost:3000/', |
||
| 415 | rtrim($this->devServerPublic, '/') . '/', |
||
| 416 | $script |
||
| 417 | ); |
||
| 418 | $lines[] = HtmlHelper::script( |
||
| 419 | $script, |
||
| 420 | [ |
||
| 421 | 'type' => 'module', |
||
| 422 | ] |
||
| 423 | ); |
||
| 424 | } |
||
| 425 | $this->devServerShimsIncluded = true; |
||
| 426 | } |
||
| 427 | // Include the entry script |
||
| 428 | $url = FileHelper::createUrl($this->devServerPublic, $path); |
||
| 429 | $lines[] = HtmlHelper::jsFile($url, array_merge([ |
||
| 430 | 'type' => 'module', |
||
| 431 | ], $scriptTagAttrs)); |
||
| 432 | |||
| 433 | return implode("\r\n", $lines); |
||
| 434 | } |
||
| 435 | |||
| 436 | /** |
||
| 437 | * Return the script, module link, and CSS link tags for the script from the manifest.json file |
||
| 438 | * |
||
| 439 | * @param string $path |
||
| 440 | * @param bool $asyncCss |
||
| 441 | * @param array $scriptTagAttrs |
||
| 442 | * @param array $cssTagAttrs |
||
| 443 | * |
||
| 444 | * @return string |
||
| 445 | */ |
||
| 446 | public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 447 | { |
||
| 448 | $lines = []; |
||
| 449 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 450 | $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 451 | $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 452 | // Include any manifest shims |
||
| 453 | if (!$this->manifestShimsIncluded) { |
||
| 454 | // Handle the modulepreload-polyfill shim |
||
| 455 | if ($this->includeModulePreloadShim) { |
||
| 456 | $lines[] = HtmlHelper::script( |
||
| 457 | FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix), |
||
| 458 | ['type' => 'module'] |
||
| 459 | ); |
||
| 460 | } |
||
| 461 | // Handle any legacy polyfills |
||
| 462 | if (!empty($legacyTags)) { |
||
| 463 | $lines[] = HtmlHelper::script( |
||
| 464 | FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix), |
||
| 465 | [] |
||
| 466 | ); |
||
| 467 | $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 468 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 469 | } |
||
| 470 | $this->manifestShimsIncluded = true; |
||
| 471 | } |
||
| 472 | $lines = array_merge($lines, $this->manifestScriptTags($tags, $legacyTags)); |
||
| 473 | |||
| 474 | return implode("\r\n", $lines); |
||
| 475 | } |
||
| 476 | |||
| 477 | // Protected Methods |
||
| 478 | // ========================================================================= |
||
| 479 | |||
| 480 | /** |
||
| 481 | * Iterate through all the tags, and register them |
||
| 482 | * |
||
| 483 | * @param array $tags |
||
| 484 | * @param array $legacyTags |
||
| 485 | * @throws InvalidConfigException |
||
| 486 | */ |
||
| 487 | protected function manifestRegisterTags(array $tags, array $legacyTags) |
||
| 488 | { |
||
| 489 | $view = Craft::$app->getView(); |
||
| 490 | foreach (array_merge($tags, $legacyTags) as $tag) { |
||
| 491 | if (!empty($tag)) { |
||
| 492 | $url = FileHelper::createUrl($this->serverPublic, $tag['url']); |
||
| 493 | switch ($tag['type']) { |
||
| 494 | case 'file': |
||
| 495 | $view->registerJsFile( |
||
| 496 | $url, |
||
| 497 | $tag['options'], |
||
| 498 | md5($url . JsonHelper::encode($tag['options'])) |
||
| 499 | ); |
||
| 500 | break; |
||
| 501 | case 'css': |
||
| 502 | $view->registerCssFile( |
||
| 503 | $url, |
||
| 504 | $tag['options'] |
||
| 505 | ); |
||
| 506 | break; |
||
| 507 | case 'import': |
||
| 508 | $view->registerLinkTag( |
||
| 509 | array_filter([ |
||
| 510 | 'crossorigin' => $tag['crossorigin'], |
||
| 511 | 'href' => $url, |
||
| 512 | 'rel' => 'modulepreload', |
||
| 513 | 'integrity' => $tag['integrity'] ?? '', |
||
| 514 | ]), |
||
| 515 | md5($url) |
||
| 516 | ); |
||
| 517 | break; |
||
| 518 | default: |
||
| 519 | break; |
||
| 520 | } |
||
| 521 | } |
||
| 522 | } |
||
| 523 | } |
||
| 524 | |||
| 525 | /** |
||
| 526 | * Inject the error entry point JavaScript for auto-reloading of Twig error |
||
| 527 | * pages |
||
| 528 | */ |
||
| 529 | protected function injectErrorEntry() |
||
| 557 | // That's okay, Vite will have already logged the error |
||
| 558 | } |
||
| 559 | } |
||
| 560 | |||
| 561 | /** |
||
| 562 | * Iterate through all the tags, and return them |
||
| 563 | * |
||
| 564 | * @param array $tags |
||
| 565 | * @param array $legacyTags |
||
| 566 | * @return array |
||
| 567 | */ |
||
| 568 | protected function manifestScriptTags(array $tags, array $legacyTags): array |
||
| 596 | } |
||
| 597 | } |
||
| 598 |