| Total Complexity | 60 |
| Total Lines | 566 |
| Duplicated Lines | 0 % |
| Changes | 14 | ||
| Bugs | 0 | Features | 1 |
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 |
||
| 35 | class ViteService extends Component |
||
| 36 | { |
||
| 37 | // Constants |
||
| 38 | // ========================================================================= |
||
| 39 | |||
| 40 | const VITE_CLIENT = '@vite/client.js'; |
||
| 41 | const LEGACY_EXTENSION = '-legacy.'; |
||
| 42 | const LEGACY_POLYFILLS = 'vite/legacy-polyfills'; |
||
| 43 | |||
| 44 | const CACHE_KEY = 'vite'; |
||
| 45 | const CACHE_TAG = 'vite'; |
||
| 46 | |||
| 47 | const DEVMODE_CACHE_DURATION = 30; |
||
| 48 | |||
| 49 | const USER_AGENT_STRING = 'User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'; |
||
| 50 | |||
| 51 | const SAFARI_NOMODULE_FIX = '!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();'; |
||
| 52 | |||
| 53 | // Public Properties |
||
| 54 | // ========================================================================= |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @var bool Should the dev server be used for? |
||
| 58 | */ |
||
| 59 | public $useDevServer; |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @var string File system path (or URL) to the Vite-built manifest.json |
||
| 63 | */ |
||
| 64 | public $manifestPath; |
||
| 65 | |||
| 66 | /** |
||
| 67 | * @var string The public URL to the dev server (what appears in `<script src="">` tags |
||
| 68 | */ |
||
| 69 | public $devServerPublic; |
||
| 70 | |||
| 71 | /** |
||
| 72 | * @var string The public URL to use when not using the dev server |
||
| 73 | */ |
||
| 74 | public $serverPublic; |
||
| 75 | |||
| 76 | /** |
||
| 77 | * @var string The JavaScript entry from the manifest.json to inject on Twig error pages |
||
| 78 | * This can be a string or an array of strings |
||
| 79 | */ |
||
| 80 | public $errorEntry = ''; |
||
| 81 | |||
| 82 | /** |
||
| 83 | * @var string String to be appended to the cache key |
||
| 84 | */ |
||
| 85 | public $cacheKeySuffix = ''; |
||
| 86 | |||
| 87 | /** |
||
| 88 | * @var string The internal URL to the dev server, when accessed from the environment in which PHP is executing |
||
| 89 | * This can be the same as `$devServerPublic`, but may be different in containerized or VM setups. |
||
| 90 | * ONLY used if $checkDevServer = true |
||
| 91 | */ |
||
| 92 | public $devServerInternal; |
||
| 93 | |||
| 94 | /** |
||
| 95 | * @var bool Should we check for the presence of the dev server by pinging $devServerInternal to make sure it's running? |
||
| 96 | */ |
||
| 97 | public $checkDevServer = false; |
||
| 98 | |||
| 99 | // Protected Properties |
||
| 100 | // ========================================================================= |
||
| 101 | |||
| 102 | /** |
||
| 103 | * @var bool Whether any legacy tags were found in this request |
||
| 104 | */ |
||
| 105 | protected $hasLegacyTags = false; |
||
| 106 | |||
| 107 | /** |
||
| 108 | * @var bool Whether the legacy polyfill has been included yet or not |
||
| 109 | */ |
||
| 110 | protected $legacyPolyfillIncluded = false; |
||
| 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 | * Return the appropriate tags 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 string |
||
| 142 | */ |
||
| 143 | public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 144 | { |
||
| 145 | if ($this->devServerRunning()) { |
||
| 146 | return $this->devServerScript($path, $scriptTagAttrs); |
||
| 147 | } |
||
| 148 | |||
| 149 | return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 150 | } |
||
| 151 | |||
| 152 | /** |
||
| 153 | * Return the script tag to load the script from the Vite dev server |
||
| 154 | * |
||
| 155 | * @param string $path |
||
| 156 | * @param array $scriptTagAttrs |
||
| 157 | * |
||
| 158 | * @return string |
||
| 159 | */ |
||
| 160 | public function devServerScript(string $path, array $scriptTagAttrs = []): string |
||
| 161 | { |
||
| 162 | $lines = []; |
||
| 163 | // Include the entry script |
||
| 164 | $url = $this->createUrl($this->devServerPublic, $path); |
||
| 165 | $lines[] = HtmlHelper::jsFile($url, array_merge([ |
||
| 166 | 'type' => 'module', |
||
| 167 | ], $scriptTagAttrs)); |
||
| 168 | |||
| 169 | return implode("\r\n", $lines); |
||
| 170 | } |
||
| 171 | |||
| 172 | /** |
||
| 173 | * Return the script, module link, and CSS link tags for the script from the manifest.json file |
||
| 174 | * |
||
| 175 | * @param string $path |
||
| 176 | * @param bool $asyncCss |
||
| 177 | * @param array $scriptTagAttrs |
||
| 178 | * @param array $cssTagAttrs |
||
| 179 | * |
||
| 180 | * @return string |
||
| 181 | */ |
||
| 182 | public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 183 | { |
||
| 184 | $lines = []; |
||
| 185 | $tags = $this->manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 186 | // Handle any legacy polyfills |
||
| 187 | if ($this->hasLegacyTags && !$this->legacyPolyfillIncluded) { |
||
| 188 | $lines[] = HtmlHelper::script(self::SAFARI_NOMODULE_FIX, []); |
||
| 189 | $legacyPolyfillTags = $this->extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 190 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 191 | $this->legacyPolyfillIncluded = true; |
||
| 192 | } |
||
| 193 | foreach($tags as $tag) { |
||
| 194 | if (!empty($tag)) { |
||
| 195 | switch ($tag['type']) { |
||
| 196 | case 'file': |
||
| 197 | $lines[] = HtmlHelper::jsFile($tag['url'], $tag['options']); |
||
| 198 | break; |
||
| 199 | case 'css': |
||
| 200 | $lines[] = HtmlHelper::cssFile($tag['url'], $tag['options']); |
||
| 201 | break; |
||
| 202 | default: |
||
| 203 | break; |
||
| 204 | } |
||
| 205 | } |
||
| 206 | } |
||
| 207 | |||
| 208 | return implode("\r\n", $lines); |
||
| 209 | } |
||
| 210 | |||
| 211 | /** |
||
| 212 | * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or |
||
| 213 | * extracting it from the manifest.json file |
||
| 214 | * |
||
| 215 | * @param string $path |
||
| 216 | * @param bool $asyncCss |
||
| 217 | * @param array $scriptTagAttrs |
||
| 218 | * @param array $cssTagAttrs |
||
| 219 | * |
||
| 220 | * @return void |
||
| 221 | * @throws InvalidConfigException |
||
| 222 | */ |
||
| 223 | public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 224 | { |
||
| 225 | if ($this->devServerRunning()) { |
||
| 226 | $this->devServerRegister($path, $scriptTagAttrs); |
||
| 227 | |||
| 228 | return; |
||
| 229 | } |
||
| 230 | |||
| 231 | $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 232 | } |
||
| 233 | |||
| 234 | /** |
||
| 235 | * Register the script tag to the Craft View to load the script from the Vite dev server |
||
| 236 | * |
||
| 237 | * @param string $path |
||
| 238 | * @param array $scriptTagAttrs |
||
| 239 | * |
||
| 240 | * @return void |
||
| 241 | * @throws InvalidConfigException |
||
| 242 | */ |
||
| 243 | public function devServerRegister(string $path, array $scriptTagAttrs = []) |
||
| 244 | { |
||
| 245 | $view = Craft::$app->getView(); |
||
| 246 | // Include the entry script |
||
| 247 | $url = $this->createUrl($this->devServerPublic, $path); |
||
| 248 | $view->registerJsFile( |
||
| 249 | $url, |
||
| 250 | array_merge(['type' => 'module'], $scriptTagAttrs), |
||
| 251 | md5($url . JsonHelper::encode($scriptTagAttrs)) |
||
| 252 | ); |
||
| 253 | } |
||
| 254 | |||
| 255 | /** |
||
| 256 | * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file |
||
| 257 | * |
||
| 258 | * @param string $path |
||
| 259 | * @param bool $asyncCss |
||
| 260 | * @param array $scriptTagAttrs |
||
| 261 | * @param array $cssTagAttrs |
||
| 262 | * |
||
| 263 | * @return void |
||
| 264 | * @throws InvalidConfigException |
||
| 265 | */ |
||
| 266 | public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 267 | { |
||
| 268 | $view = Craft::$app->getView(); |
||
| 269 | $tags = $this->manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 270 | // Handle any legacy polyfills |
||
| 271 | if ($this->hasLegacyTags && !$this->legacyPolyfillIncluded) { |
||
| 272 | $view->registerScript(self::SAFARI_NOMODULE_FIX, $view::POS_HEAD, [], 'SAFARI_NOMODULE_FIX'); |
||
| 273 | $legacyPolyfillTags = $this->extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 274 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 275 | $this->legacyPolyfillIncluded = true; |
||
| 276 | } |
||
| 277 | foreach($tags as $tag) { |
||
| 278 | if (!empty($tag)) { |
||
| 279 | switch ($tag['type']) { |
||
| 280 | case 'file': |
||
| 281 | $view->registerJsFile( |
||
| 282 | $tag['url'], |
||
| 283 | $tag['options'], |
||
| 284 | md5($tag['url'] . JsonHelper::encode($tag['options'])) |
||
| 285 | ); |
||
| 286 | break; |
||
| 287 | case 'css': |
||
| 288 | $view->registerCssFile( |
||
| 289 | $tag['url'], |
||
| 290 | $tag['options'] |
||
| 291 | ); |
||
| 292 | break; |
||
| 293 | default: |
||
| 294 | break; |
||
| 295 | } |
||
| 296 | } |
||
| 297 | } |
||
| 298 | } |
||
| 299 | |||
| 300 | /** |
||
| 301 | * Return the contents of a local file (via path) or remote file (via URL), |
||
| 302 | * or null if the file doesn't exist or couldn't be fetched |
||
| 303 | * Yii2 aliases and/or environment variables may be used |
||
| 304 | * |
||
| 305 | * @param string $pathOrUrl |
||
| 306 | * @param callable|null $callback |
||
| 307 | * |
||
| 308 | * @return string|null |
||
| 309 | */ |
||
| 310 | public function fetch(string $pathOrUrl, callable $callback = null) |
||
| 378 | ); |
||
| 379 | } |
||
| 380 | |||
| 381 | /** |
||
| 382 | * Determine whether the Vite dev server is running |
||
| 383 | * |
||
| 384 | * @return bool |
||
| 385 | */ |
||
| 386 | public function devServerRunning(): bool |
||
| 387 | { |
||
| 388 | // If the dev server is turned off via config, say it's not running |
||
| 389 | if (!$this->useDevServer) { |
||
| 390 | return false; |
||
| 391 | } |
||
| 392 | // If we're not supposed to check that the dev server is actually running, just assume it is |
||
| 393 | if (!$this->checkDevServer) { |
||
| 394 | return true; |
||
| 395 | } |
||
| 396 | // Check to see if the dev server is actually running by pinging it |
||
| 397 | $url = $this->createUrl($this->devServerInternal, self::VITE_CLIENT); |
||
| 398 | |||
| 399 | return !($this->fetch($url) === null); |
||
| 400 | } |
||
| 401 | |||
| 402 | /** |
||
| 403 | * Invalidate all of the Vite caches |
||
| 404 | */ |
||
| 405 | public function invalidateCaches() |
||
| 406 | { |
||
| 407 | $cache = Craft::$app->getCache(); |
||
| 408 | TagDependency::invalidate($cache, self::CACHE_TAG . $this->cacheKeySuffix); |
||
| 409 | Craft::info('All Vite caches cleared', __METHOD__); |
||
| 410 | } |
||
| 411 | |||
| 412 | // Protected Methods |
||
| 413 | // ========================================================================= |
||
| 414 | |||
| 415 | /** |
||
| 416 | * Inject the error entry point JavaScript for auto-reloading of Twig error |
||
| 417 | * pages |
||
| 418 | */ |
||
| 419 | protected function injectErrorEntry() |
||
| 447 | // That's okay, Vite will have already logged the error |
||
| 448 | } |
||
| 449 | } |
||
| 450 | |||
| 451 | /** |
||
| 452 | * Return an array of tags from the manifest, for both modern and legacy builds |
||
| 453 | * |
||
| 454 | * @param string $path |
||
| 455 | * @param bool $asyncCss |
||
| 456 | * @param array $scriptTagAttrs |
||
| 457 | * @param array $cssTagAttrs |
||
| 458 | * |
||
| 459 | * @return array |
||
| 460 | */ |
||
| 461 | protected function manifestTags(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): array |
||
| 462 | { |
||
| 463 | // Get the modern tags for this $path |
||
| 464 | $tags = $this->extractManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 465 | // Look for a legacy version of this $path too |
||
| 466 | $parts = pathinfo($path); |
||
| 467 | $legacyPath = $parts['dirname'] |
||
| 468 | . '/' |
||
| 469 | . $parts['filename'] |
||
| 470 | . self::LEGACY_EXTENSION |
||
| 471 | . $parts['extension']; |
||
| 472 | $legacyTags = $this->extractManifestTags($legacyPath, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 473 | // Set a flag to indicate the some legacy gets were found |
||
| 474 | $legacyPolyfillTags = []; |
||
| 475 | if (!empty($legacyTags)) { |
||
| 476 | $this->hasLegacyTags = true; |
||
| 477 | } |
||
| 478 | return array_merge( |
||
| 479 | $legacyPolyfillTags, |
||
| 480 | $tags, |
||
| 481 | $legacyTags |
||
| 482 | ); |
||
| 483 | } |
||
| 484 | |||
| 485 | /** |
||
| 486 | * Return an array of data describing the script, module link, and CSS link tags for the |
||
| 487 | * script from the manifest.json file |
||
| 488 | * |
||
| 489 | * @param string $path |
||
| 490 | * @param bool $asyncCss |
||
| 491 | * @param array $scriptTagAttrs |
||
| 492 | * @param array $cssTagAttrs |
||
| 493 | * @param bool $legacy |
||
| 494 | * |
||
| 495 | * @return array |
||
| 496 | */ |
||
| 497 | protected function extractManifestTags(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = [], bool $legacy = false): array |
||
| 498 | { |
||
| 499 | $tags = []; |
||
| 500 | // Grab the manifest |
||
| 501 | $pathOrUrl = (string)Craft::parseEnv($this->manifestPath); |
||
| 502 | $manifest = $this->fetch($pathOrUrl, [JsonHelper::class, 'decodeIfJson']); |
||
| 503 | // If no manifest file is found, bail |
||
| 504 | if ($manifest === null) { |
||
| 505 | Craft::error('Manifest not found at ' . $this->manifestPath, __METHOD__); |
||
| 506 | |||
| 507 | return []; |
||
| 508 | } |
||
| 509 | // Set the async CSS args |
||
| 510 | $asyncCssOptions = []; |
||
| 511 | if ($asyncCss) { |
||
| 512 | $asyncCssOptions = [ |
||
| 513 | 'media' => 'print', |
||
| 514 | 'onload' => "this.media='all'", |
||
| 515 | ]; |
||
| 516 | } |
||
| 517 | // Set the script args |
||
| 518 | $scriptOptions = [ |
||
| 519 | 'type' => 'module', |
||
| 520 | 'crossorigin' => true, |
||
| 521 | ]; |
||
| 522 | if ($legacy) { |
||
| 523 | $scriptOptions = [ |
||
| 524 | 'type' => 'nomodule', |
||
| 525 | ]; |
||
| 526 | } |
||
| 527 | // Iterate through the manifest |
||
| 528 | /* @var array $manifest */ |
||
| 529 | foreach ($manifest as $manifestKey => $entry) { |
||
|
1 ignored issue
–
show
|
|||
| 530 | // If it's not an entry, skip it |
||
| 531 | if (!isset($entry['isEntry']) || !$entry['isEntry']) { |
||
| 532 | continue; |
||
| 533 | } |
||
| 534 | // If there's no file, skip it |
||
| 535 | if (!isset($entry['file'])) { |
||
| 536 | continue; |
||
| 537 | } |
||
| 538 | // If the $path isn't in the $manifestKey, skip it |
||
| 539 | if (strpos($path, $manifestKey) === false) { |
||
| 540 | continue; |
||
| 541 | } |
||
| 542 | // Include the entry script |
||
| 543 | $tags[] = [ |
||
| 544 | 'type' => 'file', |
||
| 545 | 'url' => $this->createUrl($this->serverPublic, $entry['file']), |
||
| 546 | 'options' => array_merge($scriptOptions, $scriptTagAttrs) |
||
| 547 | ]; |
||
| 548 | // Include any CSS tags |
||
| 549 | $cssFiles = []; |
||
| 550 | $this->extractCssFiles($manifest, $manifestKey, $cssFiles); |
||
| 551 | foreach ($cssFiles as $cssFile) { |
||
| 552 | $tags[] = [ |
||
| 553 | 'type' => 'css', |
||
| 554 | 'url' => $this->createUrl($this->serverPublic, $cssFile), |
||
| 555 | 'options' => array_merge([ |
||
| 556 | 'rel' => 'stylesheet', |
||
| 557 | ], $asyncCssOptions, $cssTagAttrs) |
||
| 558 | ]; |
||
| 559 | } |
||
| 560 | } |
||
| 561 | |||
| 562 | return $tags; |
||
| 563 | } |
||
| 564 | |||
| 565 | /** |
||
| 566 | * Extract any CSS files from entries recursively |
||
| 567 | * |
||
| 568 | * @param array $manifest |
||
| 569 | * @param string $manifestKey |
||
| 570 | * @param array $cssFiles |
||
| 571 | * |
||
| 572 | * @return array |
||
| 573 | */ |
||
| 574 | protected function extractCssFiles(array $manifest, string $manifestKey, array &$cssFiles): array |
||
| 587 | } |
||
| 588 | |||
| 589 | /** |
||
| 590 | * Combine a path with a URL to create a URL |
||
| 591 | * |
||
| 592 | * @param string $url |
||
| 593 | * @param string $path |
||
| 594 | * |
||
| 595 | * @return string |
||
| 596 | */ |
||
| 597 | protected function createUrl(string $url, string $path): string |
||
| 601 | } |
||
| 602 | } |
||
| 603 |