| Total Complexity | 60 |
| Total Lines | 573 |
| Duplicated Lines | 0 % |
| Changes | 32 | ||
| 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 | // 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 ($this->devServerRunning() && 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 = []) |
||
| 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 | $response = FileHelper::fetchResponse($url); |
||
| 176 | $this->devServerRunningCached = false; |
||
| 177 | // Status code of 200 or 404 means the dev server is running |
||
| 178 | if ($response) { |
||
| 179 | $statusCode = $response->getStatusCode(); |
||
| 180 | $this->devServerRunningCached = $statusCode === 200 || $statusCode === 404; |
||
| 181 | } |
||
| 182 | |||
| 183 | return $this->devServerRunningCached; |
||
| 184 | } |
||
| 185 | |||
| 186 | /** |
||
| 187 | * Return the contents of a local file (via path) or remote file (via URL), |
||
| 188 | * or null if the file doesn't exist or couldn't be fetched |
||
| 189 | * Yii2 aliases and/or environment variables may be used |
||
| 190 | * |
||
| 191 | * @param string $pathOrUrl |
||
| 192 | * @param callable|null $callback |
||
| 193 | * |
||
| 194 | * @return string|array|null |
||
| 195 | */ |
||
| 196 | public function fetch(string $pathOrUrl, callable $callback = null) |
||
| 199 | } |
||
| 200 | |||
| 201 | /** |
||
| 202 | * Register the script tag to the Craft View to load the script from the Vite dev server |
||
| 203 | * |
||
| 204 | * @param string $path |
||
| 205 | * @param array $scriptTagAttrs |
||
| 206 | * |
||
| 207 | * @return void |
||
| 208 | * @throws InvalidConfigException |
||
| 209 | */ |
||
| 210 | public function devServerRegister(string $path, array $scriptTagAttrs = []) |
||
| 211 | { |
||
| 212 | $view = Craft::$app->getView(); |
||
| 213 | // Include any dev server shims |
||
| 214 | if (!$this->devServerShimsIncluded) { |
||
| 215 | // Include the react-refresh-shim |
||
| 216 | if ($this->includeReactRefreshShim) { |
||
| 217 | $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix); |
||
| 218 | // Replace the hard-coded dev server URL with whatever they have theirs set to |
||
| 219 | $script = str_replace( |
||
| 220 | 'http://localhost:3000/', |
||
| 221 | rtrim($this->devServerPublic, '/') . '/', |
||
| 222 | $script |
||
| 223 | ); |
||
| 224 | $view->registerScript( |
||
| 225 | $script, |
||
| 226 | $view::POS_HEAD, |
||
| 227 | [ |
||
| 228 | 'type' => 'module', |
||
| 229 | ], |
||
| 230 | 'REACT_REFRESH_SHIM' |
||
| 231 | ); |
||
| 232 | } |
||
| 233 | $this->devServerShimsIncluded = true; |
||
| 234 | } |
||
| 235 | // Include the entry script |
||
| 236 | $url = FileHelper::createUrl($this->devServerPublic, $path); |
||
| 237 | $view->registerJsFile( |
||
| 238 | $url, |
||
| 239 | array_merge(['type' => 'module'], $scriptTagAttrs), |
||
| 240 | md5($url . JsonHelper::encode($scriptTagAttrs)) |
||
| 241 | ); |
||
| 242 | } |
||
| 243 | |||
| 244 | /** |
||
| 245 | * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file |
||
| 246 | * |
||
| 247 | * @param string $path |
||
| 248 | * @param bool $asyncCss |
||
| 249 | * @param array $scriptTagAttrs |
||
| 250 | * @param array $cssTagAttrs |
||
| 251 | * |
||
| 252 | * @return void |
||
| 253 | * @throws InvalidConfigException |
||
| 254 | */ |
||
| 255 | public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 256 | { |
||
| 257 | $view = Craft::$app->getView(); |
||
| 258 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 259 | $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 260 | $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 261 | // Include any manifest shims |
||
| 262 | if (!$this->manifestShimsIncluded) { |
||
| 263 | // Handle the modulepreload-polyfill shim |
||
| 264 | if ($this->includeModulePreloadShim) { |
||
| 265 | $view->registerScript( |
||
| 266 | FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix), |
||
| 267 | $view::POS_HEAD, |
||
| 268 | ['type' => 'module'], |
||
| 269 | 'MODULEPRELOAD_POLYFILL' |
||
| 270 | ); |
||
| 271 | } |
||
| 272 | // Handle any legacy polyfills |
||
| 273 | if (!empty($legacyTags)) { |
||
| 274 | $view->registerScript( |
||
| 275 | FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix), |
||
| 276 | $view::POS_HEAD, |
||
| 277 | [], |
||
| 278 | 'SAFARI_NOMODULE_FIX' |
||
| 279 | ); |
||
| 280 | $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 281 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 282 | } |
||
| 283 | $this->manifestShimsIncluded = true; |
||
| 284 | } |
||
| 285 | $this->manifestRegisterTags($tags, $legacyTags); |
||
| 286 | } |
||
| 287 | |||
| 288 | /** |
||
| 289 | * Return the URL for the given entry |
||
| 290 | * |
||
| 291 | * @param string $path |
||
| 292 | * |
||
| 293 | * @return string |
||
| 294 | */ |
||
| 295 | public function entry(string $path): string |
||
| 296 | { |
||
| 297 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 298 | $entry = ManifestHelper::extractEntry($path); |
||
| 299 | |||
| 300 | return FileHelper::createUrl($this->serverPublic, $entry); |
||
| 301 | } |
||
| 302 | |||
| 303 | /** |
||
| 304 | * Return the URL for the given asset |
||
| 305 | * |
||
| 306 | * @param string $path |
||
| 307 | * |
||
| 308 | * @return string |
||
| 309 | */ |
||
| 310 | public function asset(string $path, bool $public = false): string |
||
| 311 | { |
||
| 312 | if ($this->devServerRunning()) { |
||
| 313 | return $this->devServerAsset($path); |
||
| 314 | } |
||
| 315 | |||
| 316 | if ($public) { |
||
| 317 | return $this->publicAsset($path); |
||
| 318 | } |
||
| 319 | |||
| 320 | return $this->manifestAsset($path); |
||
| 321 | } |
||
| 322 | |||
| 323 | /** |
||
| 324 | * Return the URL for the asset from the Vite dev server |
||
| 325 | * |
||
| 326 | * @param string $path |
||
| 327 | * |
||
| 328 | * @return string |
||
| 329 | */ |
||
| 330 | public function devServerAsset(string $path): string |
||
| 331 | { |
||
| 332 | // Return a URL to the given asset |
||
| 333 | return FileHelper::createUrl($this->devServerPublic, $path); |
||
| 334 | } |
||
| 335 | |||
| 336 | /** |
||
| 337 | * Return the URL for the asset from the public Vite folder |
||
| 338 | * |
||
| 339 | * @param string $path |
||
| 340 | * |
||
| 341 | * @return string |
||
| 342 | */ |
||
| 343 | public function publicAsset(string $path): string |
||
| 344 | { |
||
| 345 | // Return a URL to the given asset |
||
| 346 | return FileHelper::createUrl($this->serverPublic, $path); |
||
| 347 | } |
||
| 348 | |||
| 349 | /** |
||
| 350 | * Return the URL for the asset from the manifest.json file |
||
| 351 | * |
||
| 352 | * @param string $path |
||
| 353 | * |
||
| 354 | * @return string |
||
| 355 | */ |
||
| 356 | public function manifestAsset(string $path): string |
||
| 357 | { |
||
| 358 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 359 | $assets = ManifestHelper::extractAssetFiles(); |
||
| 360 | // Get just the file name |
||
| 361 | $assetKeyParts = explode('/', $path); |
||
| 362 | $assetKey = end($assetKeyParts); |
||
| 363 | foreach ($assets as $key => $value) { |
||
| 364 | if ($key === $assetKey) { |
||
| 365 | return FileHelper::createUrl($this->serverPublic, $value); |
||
| 366 | } |
||
| 367 | } |
||
| 368 | |||
| 369 | return ''; |
||
| 370 | } |
||
| 371 | |||
| 372 | /** |
||
| 373 | * Invalidate all of the Vite caches |
||
| 374 | */ |
||
| 375 | public function invalidateCaches() |
||
| 376 | { |
||
| 377 | $cache = Craft::$app->getCache(); |
||
| 378 | TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix); |
||
| 379 | Craft::info('All Vite caches cleared', __METHOD__); |
||
| 380 | } |
||
| 381 | |||
| 382 | /** |
||
| 383 | * Return the appropriate tags to load the Vite script, either via the dev server or |
||
| 384 | * extracting it from the manifest.json file |
||
| 385 | * |
||
| 386 | * @param string $path |
||
| 387 | * @param bool $asyncCss |
||
| 388 | * @param array $scriptTagAttrs |
||
| 389 | * @param array $cssTagAttrs |
||
| 390 | * |
||
| 391 | * @return string |
||
| 392 | */ |
||
| 393 | public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 394 | { |
||
| 395 | if ($this->devServerRunning()) { |
||
| 396 | return $this->devServerScript($path, $scriptTagAttrs); |
||
| 397 | } |
||
| 398 | |||
| 399 | return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 400 | } |
||
| 401 | |||
| 402 | /** |
||
| 403 | * Return the script tag to load the script from the Vite dev server |
||
| 404 | * |
||
| 405 | * @param string $path |
||
| 406 | * @param array $scriptTagAttrs |
||
| 407 | * |
||
| 408 | * @return string |
||
| 409 | */ |
||
| 410 | public function devServerScript(string $path, array $scriptTagAttrs = []): string |
||
| 411 | { |
||
| 412 | $lines = []; |
||
| 413 | // Include any dev server shims |
||
| 414 | if (!$this->devServerShimsIncluded) { |
||
| 415 | // Include the react-refresh-shim |
||
| 416 | if ($this->includeReactRefreshShim) { |
||
| 417 | $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix); |
||
| 418 | // Replace the hard-coded dev server URL with whatever they have theirs set to |
||
| 419 | $script = str_replace( |
||
| 420 | 'http://localhost:3000/', |
||
| 421 | rtrim($this->devServerPublic, '/') . '/', |
||
| 422 | $script |
||
| 423 | ); |
||
| 424 | $lines[] = HtmlHelper::script( |
||
| 425 | $script, |
||
| 426 | [ |
||
| 427 | 'type' => 'module', |
||
| 428 | ] |
||
| 429 | ); |
||
| 430 | } |
||
| 431 | $this->devServerShimsIncluded = true; |
||
| 432 | } |
||
| 433 | // Include the entry script |
||
| 434 | $url = FileHelper::createUrl($this->devServerPublic, $path); |
||
| 435 | $lines[] = HtmlHelper::jsFile($url, array_merge([ |
||
| 436 | 'type' => 'module', |
||
| 437 | ], $scriptTagAttrs)); |
||
| 438 | |||
| 439 | return implode("\r\n", $lines); |
||
| 440 | } |
||
| 441 | |||
| 442 | /** |
||
| 443 | * Return the script, module link, and CSS link tags for the script from the manifest.json file |
||
| 444 | * |
||
| 445 | * @param string $path |
||
| 446 | * @param bool $asyncCss |
||
| 447 | * @param array $scriptTagAttrs |
||
| 448 | * @param array $cssTagAttrs |
||
| 449 | * |
||
| 450 | * @return string |
||
| 451 | */ |
||
| 452 | public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 453 | { |
||
| 454 | $lines = []; |
||
| 455 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 456 | $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 457 | $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 458 | // Include any manifest shims |
||
| 459 | if (!$this->manifestShimsIncluded) { |
||
| 460 | // Handle the modulepreload-polyfill shim |
||
| 461 | if ($this->includeModulePreloadShim) { |
||
| 462 | $lines[] = HtmlHelper::script( |
||
| 463 | FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix), |
||
| 464 | ['type' => 'module'] |
||
| 465 | ); |
||
| 466 | } |
||
| 467 | // Handle any legacy polyfills |
||
| 468 | if (!empty($legacyTags)) { |
||
| 469 | $lines[] = HtmlHelper::script( |
||
| 470 | FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix), |
||
| 471 | [] |
||
| 472 | ); |
||
| 473 | $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 474 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 475 | } |
||
| 476 | $this->manifestShimsIncluded = true; |
||
| 477 | } |
||
| 478 | $lines = array_merge($lines, $this->manifestScriptTags($tags, $legacyTags)); |
||
| 479 | |||
| 480 | return implode("\r\n", $lines); |
||
| 481 | } |
||
| 482 | |||
| 483 | // Protected Methods |
||
| 484 | // ========================================================================= |
||
| 485 | |||
| 486 | /** |
||
| 487 | * Iterate through all the tags, and register them |
||
| 488 | * |
||
| 489 | * @param array $tags |
||
| 490 | * @param array $legacyTags |
||
| 491 | * @throws InvalidConfigException |
||
| 492 | */ |
||
| 493 | protected function manifestRegisterTags(array $tags, array $legacyTags) |
||
| 494 | { |
||
| 495 | $view = Craft::$app->getView(); |
||
| 496 | foreach (array_merge($tags, $legacyTags) as $tag) { |
||
| 497 | if (!empty($tag)) { |
||
| 498 | $url = FileHelper::createUrl($this->serverPublic, $tag['url']); |
||
| 499 | switch ($tag['type']) { |
||
| 500 | case 'file': |
||
| 501 | $view->registerJsFile( |
||
| 502 | $url, |
||
| 503 | $tag['options'], |
||
| 504 | md5($url . JsonHelper::encode($tag['options'])) |
||
| 505 | ); |
||
| 506 | break; |
||
| 507 | case 'css': |
||
| 508 | $view->registerCssFile( |
||
| 509 | $url, |
||
| 510 | $tag['options'] |
||
| 511 | ); |
||
| 512 | break; |
||
| 513 | case 'import': |
||
| 514 | $view->registerLinkTag( |
||
| 515 | array_filter([ |
||
| 516 | 'crossorigin' => $tag['crossorigin'], |
||
| 517 | 'href' => $url, |
||
| 518 | 'rel' => 'modulepreload', |
||
| 519 | 'integrity' => $tag['integrity'] ?? '', |
||
| 520 | ]), |
||
| 521 | md5($url) |
||
| 522 | ); |
||
| 523 | break; |
||
| 524 | default: |
||
| 525 | break; |
||
| 526 | } |
||
| 527 | } |
||
| 528 | } |
||
| 529 | } |
||
| 530 | |||
| 531 | /** |
||
| 532 | * Inject the error entry point JavaScript for auto-reloading of Twig error |
||
| 533 | * pages |
||
| 534 | */ |
||
| 535 | protected function injectErrorEntry() |
||
| 563 | // That's okay, Vite will have already logged the error |
||
| 564 | } |
||
| 565 | } |
||
| 566 | |||
| 567 | /** |
||
| 568 | * Iterate through all the tags, and return them |
||
| 569 | * |
||
| 570 | * @param array $tags |
||
| 571 | * @param array $legacyTags |
||
| 572 | * @return array |
||
| 573 | */ |
||
| 574 | protected function manifestScriptTags(array $tags, array $legacyTags): array |
||
| 602 | } |
||
| 603 | } |
||
| 604 |