| Total Complexity | 51 |
| Total Lines | 468 |
| Duplicated Lines | 0 % |
| Changes | 23 | ||
| Bugs | 0 | 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 |
||
| 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 | /** |
||
| 44 | * @var bool Should the dev server be used for? |
||
| 45 | */ |
||
| 46 | public $useDevServer; |
||
| 47 | |||
| 48 | /** |
||
| 49 | * @var string File system path (or URL) to the Vite-built manifest.json |
||
| 50 | */ |
||
| 51 | public $manifestPath; |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @var string The public URL to the dev server (what appears in `<script src="">` tags |
||
| 55 | */ |
||
| 56 | public $devServerPublic; |
||
| 57 | |||
| 58 | /** |
||
| 59 | * @var string The public URL to use when not using the dev server |
||
| 60 | */ |
||
| 61 | public $serverPublic; |
||
| 62 | |||
| 63 | /** |
||
| 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 | /** |
||
| 70 | * @var string String to be appended to the cache key |
||
| 71 | */ |
||
| 72 | public $cacheKeySuffix = ''; |
||
| 73 | |||
| 74 | /** |
||
| 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 | /** |
||
| 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 | /** |
||
| 87 | * @var bool Whether the react-refresh-shim should be included |
||
| 88 | */ |
||
| 89 | public $includeReactRefreshShim = false; |
||
| 90 | |||
| 91 | // Protected Properties |
||
| 92 | // ========================================================================= |
||
| 93 | |||
| 94 | /** |
||
| 95 | * @var bool Whether the manifest shims has been included yet or not |
||
| 96 | */ |
||
| 97 | protected $manifestShimsIncluded = false; |
||
| 98 | |||
| 99 | /** |
||
| 100 | * @var bool Whether the dev server shims has been included yet or not |
||
| 101 | */ |
||
| 102 | protected $devServerShimsIncluded = false; |
||
| 103 | |||
| 104 | /** |
||
| 105 | * @var bool Whether the modulepreload polyfill has been included yet or not |
||
| 106 | */ |
||
| 107 | protected $modulepreloadPolyfillIncluded = false; |
||
| 108 | |||
| 109 | // Public Methods |
||
| 110 | // ========================================================================= |
||
| 111 | |||
| 112 | /** |
||
| 113 | * @inheritDoc |
||
| 114 | */ |
||
| 115 | public function init() |
||
| 116 | { |
||
| 117 | parent::init(); |
||
| 118 | // Do nothing for console requests |
||
| 119 | $request = Craft::$app->getRequest(); |
||
| 120 | if ($request->getIsConsoleRequest()) { |
||
| 121 | return; |
||
| 122 | } |
||
| 123 | // Our component is lazily loaded, so the View will be instantiated by now |
||
| 124 | if (Craft::$app->getConfig()->getGeneral()->devMode) { |
||
| 125 | Craft::$app->getView()->on(View::EVENT_END_BODY, [$this, 'injectErrorEntry']); |
||
| 126 | } |
||
| 127 | } |
||
| 128 | |||
| 129 | /** |
||
| 130 | * Return the appropriate tags to load the Vite script, either via the dev server or |
||
| 131 | * extracting it from the manifest.json file |
||
| 132 | * |
||
| 133 | * @param string $path |
||
| 134 | * @param bool $asyncCss |
||
| 135 | * @param array $scriptTagAttrs |
||
| 136 | * @param array $cssTagAttrs |
||
| 137 | * |
||
| 138 | * @return string |
||
| 139 | */ |
||
| 140 | public function script(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 141 | { |
||
| 142 | if ($this->devServerRunning()) { |
||
| 143 | return $this->devServerScript($path, $scriptTagAttrs); |
||
| 144 | } |
||
| 145 | |||
| 146 | return $this->manifestScript($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 147 | } |
||
| 148 | |||
| 149 | /** |
||
| 150 | * Return the script tag to load the script from the Vite dev server |
||
| 151 | * |
||
| 152 | * @param string $path |
||
| 153 | * @param array $scriptTagAttrs |
||
| 154 | * |
||
| 155 | * @return string |
||
| 156 | */ |
||
| 157 | public function devServerScript(string $path, array $scriptTagAttrs = []): string |
||
| 158 | { |
||
| 159 | $lines = []; |
||
| 160 | // Include any dev server shims |
||
| 161 | if (!$this->devServerShimsIncluded) { |
||
| 162 | // Include the react-refresh-shim |
||
| 163 | if ($this->includeReactRefreshShim) { |
||
| 164 | $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix); |
||
| 165 | // Replace the hard-coded dev server URL with whatever they have theirs set to |
||
| 166 | $script = str_replace( |
||
| 167 | 'http://localhost:3000/', |
||
| 168 | rtrim($this->devServerPublic, '/').'/', |
||
| 169 | $script |
||
| 170 | ); |
||
| 171 | $lines[] = HtmlHelper::script( |
||
| 172 | $script, |
||
| 173 | [ |
||
| 174 | 'type' => 'module', |
||
| 175 | ] |
||
| 176 | ); |
||
| 177 | } |
||
| 178 | $this->devServerShimsIncluded = true; |
||
| 179 | } |
||
| 180 | // Include the entry script |
||
| 181 | $url = FileHelper::createUrl($this->devServerPublic, $path); |
||
| 182 | $lines[] = HtmlHelper::jsFile($url, array_merge([ |
||
| 183 | 'type' => 'module', |
||
| 184 | ], $scriptTagAttrs)); |
||
| 185 | |||
| 186 | return implode("\r\n", $lines); |
||
| 187 | } |
||
| 188 | |||
| 189 | /** |
||
| 190 | * Return the script, module link, and CSS link tags for the script from the manifest.json file |
||
| 191 | * |
||
| 192 | * @param string $path |
||
| 193 | * @param bool $asyncCss |
||
| 194 | * @param array $scriptTagAttrs |
||
| 195 | * @param array $cssTagAttrs |
||
| 196 | * |
||
| 197 | * @return string |
||
| 198 | */ |
||
| 199 | public function manifestScript(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []): string |
||
| 200 | { |
||
| 201 | $lines = []; |
||
| 202 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 203 | $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 204 | $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 205 | // Include any manifest shims |
||
| 206 | if (!$this->manifestShimsIncluded) { |
||
| 207 | // Handle any legacy polyfills |
||
| 208 | if (!empty($legacyTags)) { |
||
| 209 | $lines[] = HtmlHelper::script( |
||
| 210 | FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix), |
||
| 211 | [] |
||
| 212 | ); |
||
| 213 | $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 214 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 215 | } |
||
| 216 | $this->manifestShimsIncluded = true; |
||
| 217 | } |
||
| 218 | |||
| 219 | foreach(array_merge($tags, $legacyTags) as $tag) { |
||
| 220 | if (!empty($tag)) { |
||
| 221 | $url = FileHelper::createUrl($this->serverPublic, $tag['url']); |
||
| 222 | switch ($tag['type']) { |
||
| 223 | case 'file': |
||
| 224 | $lines[] = HtmlHelper::jsFile($url, $tag['options']); |
||
| 225 | break; |
||
| 226 | case 'css': |
||
| 227 | $lines[] = HtmlHelper::cssFile($url, $tag['options']); |
||
| 228 | break; |
||
| 229 | default: |
||
| 230 | break; |
||
| 231 | } |
||
| 232 | } |
||
| 233 | } |
||
| 234 | |||
| 235 | // modulepreload any imports from modern tags |
||
| 236 | $modulepreloadPolyfillRequired = false; |
||
| 237 | foreach($tags as $tag) { |
||
| 238 | if (!empty($tag)) { |
||
| 239 | $url = FileHelper::createUrl($this->serverPublic, $tag['url']); |
||
| 240 | switch ($tag['type']) { |
||
| 241 | case 'import': |
||
| 242 | $lines[] = HtmlHelper::tag('link', '', [ |
||
| 243 | 'crossorigin' => $tag['crossorigin'], |
||
| 244 | 'href' => $url, |
||
| 245 | 'rel' => 'modulepreload', |
||
| 246 | ]); |
||
| 247 | $modulepreloadPolyfillRequired = true; |
||
| 248 | break; |
||
| 249 | default: |
||
| 250 | break; |
||
| 251 | } |
||
| 252 | } |
||
| 253 | } |
||
| 254 | if($modulepreloadPolyfillRequired && ! $this->modulepreloadPolyfillIncluded) { |
||
| 255 | $this->modulepreloadPolyfillIncluded = true; |
||
| 256 | $lines[] = HtmlHelper::script( |
||
| 257 | FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix), |
||
| 258 | ['type' => 'module'] |
||
| 259 | ); |
||
| 260 | } |
||
| 261 | |||
| 262 | return implode("\r\n", $lines); |
||
| 263 | } |
||
| 264 | |||
| 265 | /** |
||
| 266 | * Register the appropriate tags to the Craft View to load the Vite script, either via the dev server or |
||
| 267 | * extracting it from the manifest.json file |
||
| 268 | * |
||
| 269 | * @param string $path |
||
| 270 | * @param bool $asyncCss |
||
| 271 | * @param array $scriptTagAttrs |
||
| 272 | * @param array $cssTagAttrs |
||
| 273 | * |
||
| 274 | * @return void |
||
| 275 | * @throws InvalidConfigException |
||
| 276 | */ |
||
| 277 | public function register(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 278 | { |
||
| 279 | if ($this->devServerRunning()) { |
||
| 280 | $this->devServerRegister($path, $scriptTagAttrs); |
||
| 281 | |||
| 282 | return; |
||
| 283 | } |
||
| 284 | |||
| 285 | $this->manifestRegister($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 286 | } |
||
| 287 | |||
| 288 | /** |
||
| 289 | * Register the script tag to the Craft View to load the script from the Vite dev server |
||
| 290 | * |
||
| 291 | * @param string $path |
||
| 292 | * @param array $scriptTagAttrs |
||
| 293 | * |
||
| 294 | * @return void |
||
| 295 | * @throws InvalidConfigException |
||
| 296 | */ |
||
| 297 | public function devServerRegister(string $path, array $scriptTagAttrs = []) |
||
| 298 | { |
||
| 299 | $view = Craft::$app->getView(); |
||
| 300 | // Include any dev server shims |
||
| 301 | if (!$this->devServerShimsIncluded) { |
||
| 302 | // Include the react-refresh-shim |
||
| 303 | if ($this->includeReactRefreshShim) { |
||
| 304 | $script = FileHelper::fetchScript('react-refresh-shim.min.js', $this->cacheKeySuffix); |
||
| 305 | // Replace the hard-coded dev server URL with whatever they have theirs set to |
||
| 306 | $script = str_replace( |
||
| 307 | 'http://localhost:3000/', |
||
| 308 | rtrim($this->devServerPublic, '/').'/', |
||
| 309 | $script |
||
| 310 | ); |
||
| 311 | $view->registerScript( |
||
| 312 | $script, |
||
| 313 | $view::POS_HEAD, |
||
| 314 | [ |
||
| 315 | 'type' => 'module', |
||
| 316 | ], |
||
| 317 | 'REACT_REFRESH_SHIM' |
||
| 318 | ); |
||
| 319 | } |
||
| 320 | $this->devServerShimsIncluded = true; |
||
| 321 | } |
||
| 322 | // Include the entry script |
||
| 323 | $url = FileHelper::createUrl($this->devServerPublic, $path); |
||
| 324 | $view->registerJsFile( |
||
| 325 | $url, |
||
| 326 | array_merge(['type' => 'module'], $scriptTagAttrs), |
||
| 327 | md5($url . JsonHelper::encode($scriptTagAttrs)) |
||
| 328 | ); |
||
| 329 | } |
||
| 330 | |||
| 331 | /** |
||
| 332 | * Register the script, module link, and CSS link tags to the Craft View for the script from the manifest.json file |
||
| 333 | * |
||
| 334 | * @param string $path |
||
| 335 | * @param bool $asyncCss |
||
| 336 | * @param array $scriptTagAttrs |
||
| 337 | * @param array $cssTagAttrs |
||
| 338 | * |
||
| 339 | * @return void |
||
| 340 | * @throws InvalidConfigException |
||
| 341 | */ |
||
| 342 | public function manifestRegister(string $path, bool $asyncCss = true, array $scriptTagAttrs = [], array $cssTagAttrs = []) |
||
| 343 | { |
||
| 344 | $view = Craft::$app->getView(); |
||
| 345 | ManifestHelper::fetchManifest($this->manifestPath); |
||
| 346 | $tags = ManifestHelper::manifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 347 | $legacyTags = ManifestHelper::legacyManifestTags($path, $asyncCss, $scriptTagAttrs, $cssTagAttrs); |
||
| 348 | // Include any manifest shims |
||
| 349 | if (!$this->manifestShimsIncluded) { |
||
| 350 | // Handle any legacy polyfills |
||
| 351 | if (!empty($legacyTags)) { |
||
| 352 | $view->registerScript( |
||
| 353 | FileHelper::fetchScript('safari-nomodule-fix.min.js', $this->cacheKeySuffix), |
||
| 354 | $view::POS_HEAD, |
||
| 355 | [], |
||
| 356 | 'SAFARI_NOMODULE_FIX' |
||
| 357 | ); |
||
| 358 | $legacyPolyfillTags = ManifestHelper::extractManifestTags(self::LEGACY_POLYFILLS, $asyncCss, $scriptTagAttrs, $cssTagAttrs, true); |
||
| 359 | $tags = array_merge($legacyPolyfillTags, $tags); |
||
| 360 | } |
||
| 361 | $this->manifestShimsIncluded = true; |
||
| 362 | } |
||
| 363 | foreach(array_merge($tags, $legacyTags) as $tag) { |
||
| 364 | if (!empty($tag)) { |
||
| 365 | $url = FileHelper::createUrl($this->serverPublic, $tag['url']); |
||
| 366 | switch ($tag['type']) { |
||
| 367 | case 'file': |
||
| 368 | $view->registerJsFile( |
||
| 369 | $url, |
||
| 370 | $tag['options'], |
||
| 371 | md5($url . JsonHelper::encode($tag['options'])) |
||
| 372 | ); |
||
| 373 | break; |
||
| 374 | case 'css': |
||
| 375 | $view->registerCssFile( |
||
| 376 | $url, |
||
| 377 | $tag['options'] |
||
| 378 | ); |
||
| 379 | break; |
||
| 380 | default: |
||
| 381 | break; |
||
| 382 | } |
||
| 383 | } |
||
| 384 | } |
||
| 385 | |||
| 386 | // modulepreload any imports from modern tags |
||
| 387 | $modulepreloadPolyfillRequired = false; |
||
| 388 | foreach($tags as $tag) { |
||
| 389 | if (!empty($tag)) { |
||
| 390 | $url = FileHelper::createUrl($this->serverPublic, $tag['url']); |
||
| 391 | switch ($tag['type']) { |
||
| 392 | case 'import': |
||
| 393 | $view->registerLinkTag( |
||
| 394 | [ |
||
| 395 | 'crossorigin' => $tag['crossorigin'], |
||
| 396 | 'href' => $url, |
||
| 397 | 'rel' => 'modulepreload', |
||
| 398 | ], |
||
| 399 | md5($url) |
||
| 400 | ); |
||
| 401 | $modulepreloadPolyfillRequired = true; |
||
| 402 | break; |
||
| 403 | default: |
||
| 404 | break; |
||
| 405 | } |
||
| 406 | } |
||
| 407 | } |
||
| 408 | if($modulepreloadPolyfillRequired && ! $this->modulepreloadPolyfillIncluded) { |
||
| 409 | $this->modulepreloadPolyfillIncluded = true; |
||
| 410 | $view->registerScript( |
||
| 411 | FileHelper::fetchScript('modulepreload-polyfill.min.js', $this->cacheKeySuffix), |
||
| 412 | $view::POS_HEAD, |
||
| 413 | ['type' => 'module'], |
||
| 414 | 'MODULEPRELOAD_POLYFILL' |
||
| 415 | ); |
||
| 416 | } |
||
| 417 | } |
||
| 418 | |||
| 419 | /** |
||
| 420 | * Return the contents of a local file (via path) or remote file (via URL), |
||
| 421 | * or null if the file doesn't exist or couldn't be fetched |
||
| 422 | * Yii2 aliases and/or environment variables may be used |
||
| 423 | * |
||
| 424 | * @param string $pathOrUrl |
||
| 425 | * @param callable|null $callback |
||
| 426 | * |
||
| 427 | * @return string|array|null |
||
| 428 | */ |
||
| 429 | public function fetch(string $pathOrUrl, callable $callback = null) |
||
| 432 | } |
||
| 433 | |||
| 434 | /** |
||
| 435 | * Determine whether the Vite dev server is running |
||
| 436 | * |
||
| 437 | * @return bool |
||
| 438 | */ |
||
| 439 | public function devServerRunning(): bool |
||
| 440 | { |
||
| 441 | // If the dev server is turned off via config, say it's not running |
||
| 442 | if (!$this->useDevServer) { |
||
| 443 | return false; |
||
| 444 | } |
||
| 445 | // If we're not supposed to check that the dev server is actually running, just assume it is |
||
| 446 | if (!$this->checkDevServer) { |
||
| 447 | return true; |
||
| 448 | } |
||
| 449 | // Check to see if the dev server is actually running by pinging it |
||
| 450 | $url = FileHelper::createUrl($this->devServerInternal, self::VITE_CLIENT); |
||
| 451 | |||
| 452 | return !($this->fetch($url) === null); |
||
| 453 | } |
||
| 454 | |||
| 455 | /** |
||
| 456 | * Invalidate all of the Vite caches |
||
| 457 | */ |
||
| 458 | public function invalidateCaches() |
||
| 459 | { |
||
| 460 | $cache = Craft::$app->getCache(); |
||
| 461 | TagDependency::invalidate($cache, FileHelper::CACHE_TAG . $this->cacheKeySuffix); |
||
| 462 | Craft::info('All Vite caches cleared', __METHOD__); |
||
| 463 | } |
||
| 464 | |||
| 465 | // Protected Methods |
||
| 466 | // ========================================================================= |
||
| 467 | |||
| 468 | /** |
||
| 469 | * Inject the error entry point JavaScript for auto-reloading of Twig error |
||
| 470 | * pages |
||
| 471 | */ |
||
| 472 | protected function injectErrorEntry() |
||
| 500 | // That's okay, Vite will have already logged the error |
||
| 501 | } |
||
| 502 | } |
||
| 503 | } |
||
| 504 |