| Total Complexity | 70 |
| Total Lines | 593 |
| Duplicated Lines | 0 % |
| Changes | 17 | ||
| Bugs | 0 | Features | 0 |
Complex classes like Manifest 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 Manifest, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 28 | class Manifest |
||
| 29 | { |
||
| 30 | // Constants |
||
| 31 | // ========================================================================= |
||
| 32 | |||
| 33 | const CACHE_KEY = 'twigpack'; |
||
| 34 | const CACHE_TAG = 'twigpack'; |
||
| 35 | |||
| 36 | const DEVMODE_CACHE_DURATION = 1; |
||
| 37 | |||
| 38 | // Protected Static Properties |
||
| 39 | // ========================================================================= |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @var array |
||
| 43 | */ |
||
| 44 | protected static $files; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @var bool |
||
| 48 | */ |
||
| 49 | protected static $isHot = false; |
||
| 50 | |||
| 51 | // Public Static Methods |
||
| 52 | // ========================================================================= |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @param array $config |
||
| 56 | * @param string $moduleName |
||
| 57 | * @param bool $async |
||
| 58 | * |
||
| 59 | * @return string |
||
| 60 | * @throws NotFoundHttpException |
||
| 61 | */ |
||
| 62 | public static function getCssModuleTags(array $config, string $moduleName, bool $async): string |
||
| 77 | } |
||
| 78 | |||
| 79 | /** |
||
| 80 | * @param string $path |
||
| 81 | * |
||
| 82 | * @return string |
||
| 83 | */ |
||
| 84 | public static function getCssInlineTags(string $path): string |
||
| 85 | { |
||
| 86 | $result = self::getFile($path); |
||
| 87 | if ($result) { |
||
| 88 | $result = "<style>\r\n".$result."</style>\r\n"; |
||
| 89 | |||
| 90 | return $result; |
||
| 91 | } |
||
| 92 | |||
| 93 | return ''; |
||
| 94 | } |
||
| 95 | |||
| 96 | /** |
||
| 97 | * @param array $config |
||
| 98 | * @param null|string $name |
||
| 99 | * |
||
| 100 | * @return string |
||
| 101 | */ |
||
| 102 | public static function getCriticalCssTags(array $config, $name = null): string |
||
| 103 | { |
||
| 104 | // Resolve the template name |
||
| 105 | $template = Craft::$app->getView()->resolveTemplate($name ?? Twigpack::$templateName ?? ''); |
||
| 106 | if ($template) { |
||
| 107 | $name = self::combinePaths( |
||
| 108 | pathinfo($template, PATHINFO_DIRNAME), |
||
| 109 | pathinfo($template, PATHINFO_FILENAME) |
||
| 110 | ); |
||
| 111 | $dirPrefix = 'templates/'; |
||
| 112 | if (defined('CRAFT_TEMPLATES_PATH')) { |
||
| 113 | $dirPrefix = CRAFT_TEMPLATES_PATH; |
||
| 114 | } |
||
| 115 | $name = strstr($name, $dirPrefix); |
||
| 116 | $name = (string)str_replace($dirPrefix, '', $name); |
||
| 117 | $path = self::combinePaths( |
||
| 118 | $config['localFiles']['basePath'], |
||
| 119 | $config['localFiles']['criticalPrefix'], |
||
| 120 | $name |
||
| 121 | ).$config['localFiles']['criticalSuffix']; |
||
| 122 | |||
| 123 | return self::getCssInlineTags($path); |
||
| 124 | } |
||
| 125 | |||
| 126 | return ''; |
||
| 127 | } |
||
| 128 | |||
| 129 | /** |
||
| 130 | * Returns the uglified loadCSS rel=preload Polyfill as per: |
||
| 131 | * https://github.com/filamentgroup/loadCSS#how-to-use-loadcss-recommended-example |
||
| 132 | * |
||
| 133 | * @return string |
||
| 134 | */ |
||
| 135 | public static function getCssRelPreloadPolyfill(): string |
||
| 138 | <script> |
||
| 139 | /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */ |
||
| 140 | !function(t){"use strict";t.loadCSS||(t.loadCSS=function(){});var e=loadCSS.relpreload={};if(e.support=function(){var e;try{e=t.document.createElement("link").relList.supports("preload")}catch(t){e=!1}return function(){return e}}(),e.bindMediaToggle=function(t){var e=t.media||"all";function a(){t.media=e}t.addEventListener?t.addEventListener("load",a):t.attachEvent&&t.attachEvent("onload",a),setTimeout(function(){t.rel="stylesheet",t.media="only x"}),setTimeout(a,3e3)},e.poly=function(){if(!e.support())for(var a=t.document.getElementsByTagName("link"),n=0;n<a.length;n++){var o=a[n];"preload"!==o.rel||"style"!==o.getAttribute("as")||o.getAttribute("data-loadcss")||(o.setAttribute("data-loadcss",!0),e.bindMediaToggle(o))}},!e.support()){e.poly();var a=t.setInterval(e.poly,500);t.addEventListener?t.addEventListener("load",function(){e.poly(),t.clearInterval(a)}):t.attachEvent&&t.attachEvent("onload",function(){e.poly(),t.clearInterval(a)})}"undefined"!=typeof exports?exports.loadCSS=loadCSS:t.loadCSS=loadCSS}("undefined"!=typeof global?global:this); |
||
| 141 | </script> |
||
| 142 | EOT; |
||
| 143 | } |
||
| 144 | |||
| 145 | /** |
||
| 146 | * @param array $config |
||
| 147 | * @param string $moduleName |
||
| 148 | * @param bool $async |
||
| 149 | * |
||
| 150 | * @return null|string |
||
| 151 | * @throws NotFoundHttpException |
||
| 152 | */ |
||
| 153 | public static function getJsModuleTags(array $config, string $moduleName, bool $async) |
||
| 154 | { |
||
| 155 | $legacyModule = self::getModule($config, $moduleName, 'legacy', true); |
||
| 156 | if ($legacyModule === null) { |
||
| 157 | return ''; |
||
| 158 | } |
||
| 159 | $modernModule = ''; |
||
| 160 | if ($async) { |
||
| 161 | $modernModule = self::getModule($config, $moduleName, 'modern', true); |
||
| 162 | if ($modernModule === null) { |
||
| 163 | return ''; |
||
| 164 | } |
||
| 165 | } |
||
| 166 | $lines = []; |
||
| 167 | if ($async) { |
||
| 168 | $lines[] = "<script type=\"module\" src=\"{$modernModule}\"></script>"; |
||
| 169 | $lines[] = "<script nomodule src=\"{$legacyModule}\"></script>"; |
||
| 170 | } else { |
||
| 171 | $lines[] = "<script src=\"{$legacyModule}\"></script>"; |
||
| 172 | } |
||
| 173 | |||
| 174 | return implode("\r\n", $lines); |
||
| 175 | } |
||
| 176 | |||
| 177 | /** |
||
| 178 | * Safari 10.1 supports modules, but does not support the `nomodule` |
||
| 179 | * attribute - it will load <script nomodule> anyway. This snippet solve |
||
| 180 | * this problem, but only for script tags that load external code, e.g.: |
||
| 181 | * <script nomodule src="nomodule.js"></script> |
||
| 182 | * |
||
| 183 | * Again: this will **not* # prevent inline script, e.g.: |
||
| 184 | * <script nomodule>alert('no modules');</script>. |
||
| 185 | * |
||
| 186 | * This workaround is possible because Safari supports the non-standard |
||
| 187 | * 'beforeload' event. This allows us to trap the module and nomodule load. |
||
| 188 | * |
||
| 189 | * Note also that `nomodule` is supported in later versions of Safari - |
||
| 190 | * it's just 10.1 that omits this attribute. |
||
| 191 | * |
||
| 192 | * c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc |
||
| 193 | * |
||
| 194 | * @return string |
||
| 195 | */ |
||
| 196 | public static function getSafariNomoduleFix(): string |
||
| 199 | <script> |
||
| 200 | !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()}}(); |
||
| 201 | </script> |
||
| 202 | EOT; |
||
| 203 | } |
||
| 204 | |||
| 205 | /** |
||
| 206 | * Return the URI to a module |
||
| 207 | * |
||
| 208 | * @param array $config |
||
| 209 | * @param string $moduleName |
||
| 210 | * @param string $type |
||
| 211 | * @param bool $soft |
||
| 212 | * |
||
| 213 | * @return null|string |
||
| 214 | * @throws NotFoundHttpException |
||
| 215 | */ |
||
| 216 | public static function getModule(array $config, string $moduleName, string $type = 'modern', bool $soft = false) |
||
| 247 | } |
||
| 248 | |||
| 249 | /** |
||
| 250 | * Return the HASH value from to module |
||
| 251 | * |
||
| 252 | * @param array $config |
||
| 253 | * @param string $moduleName |
||
| 254 | * @param string $type |
||
| 255 | * @param bool $soft |
||
| 256 | * |
||
| 257 | * @return null|string |
||
| 258 | * @throws NotFoundHttpException |
||
| 259 | */ |
||
| 260 | public static function getModuleHash(array $config, string $moduleName, string $type = 'modern', bool $soft = false) |
||
| 261 | { |
||
| 262 | |||
| 263 | try { |
||
| 264 | // Get the module entry |
||
| 265 | $module = self::getModuleEntry($config, $moduleName, $type, $soft); |
||
| 266 | if ($module !== null) { |
||
| 267 | $prefix = self::$isHot |
||
| 268 | ? $config['devServer']['publicPath'] |
||
| 269 | : $config['server']['publicPath']; |
||
| 270 | // Extract only the Hash Value |
||
| 271 | $modulePath = pathinfo($module); |
||
| 272 | $moduleFilename = $modulePath['filename']; |
||
| 273 | $moduleHash = substr($moduleFilename, strpos($moduleFilename, ".") + 1); |
||
| 274 | } |
||
| 275 | } catch (Exception $e) { |
||
| 276 | // return emtpt string if no module is found |
||
| 277 | return ''; |
||
| 278 | } |
||
| 279 | |||
| 280 | return $moduleHash; |
||
| 281 | } |
||
| 282 | |||
| 283 | /** |
||
| 284 | * Return a module's raw entry from the manifest |
||
| 285 | * |
||
| 286 | * @param array $config |
||
| 287 | * @param string $moduleName |
||
| 288 | * @param string $type |
||
| 289 | * @param bool $soft |
||
| 290 | * |
||
| 291 | * @return null|string |
||
| 292 | * @throws NotFoundHttpException |
||
| 293 | */ |
||
| 294 | public static function getModuleEntry( |
||
| 318 | } |
||
| 319 | |||
| 320 | /** |
||
| 321 | * Return a JSON-decoded manifest file |
||
| 322 | * |
||
| 323 | * @param array $config |
||
| 324 | * @param string $type |
||
| 325 | * |
||
| 326 | * @return null|array |
||
| 327 | * @throws NotFoundHttpException |
||
| 328 | */ |
||
| 329 | public static function getManifestFile(array $config, string $type = 'modern') |
||
| 330 | { |
||
| 331 | $manifest = null; |
||
| 332 | // Determine whether we should use the devServer for HMR or not |
||
| 333 | $devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
||
| 334 | self::$isHot = ($devMode && $config['useDevServer']); |
||
| 335 | // Try to get the manifest |
||
| 336 | while ($manifest === null) { |
||
| 337 | $manifestPath = self::$isHot |
||
| 338 | ? $config['devServer']['manifestPath'] |
||
| 339 | : $config['server']['manifestPath']; |
||
| 340 | // Normalize the path |
||
| 341 | $path = self::combinePaths($manifestPath, $config['manifest'][$type]); |
||
| 342 | $manifest = self::getJsonFile($path); |
||
| 343 | // If the manifest isn't found, and it was hot, fall back on non-hot |
||
| 344 | if ($manifest === null) { |
||
| 345 | // We couldn't find a manifest; throw an error |
||
| 346 | self::reportError(Craft::t( |
||
| 347 | 'twigpack', |
||
| 348 | 'Manifest file not found at: {manifestPath}', |
||
| 349 | ['manifestPath' => $manifestPath] |
||
| 350 | ), true); |
||
| 351 | if (self::$isHot) { |
||
| 352 | // Try again, but not with home module replacement |
||
| 353 | self::$isHot = false; |
||
| 354 | } else { |
||
| 355 | // Give up and return null |
||
| 356 | return null; |
||
| 357 | } |
||
| 358 | } |
||
| 359 | } |
||
| 360 | |||
| 361 | return $manifest; |
||
| 362 | } |
||
| 363 | |||
| 364 | /** |
||
| 365 | * Returns the contents of a file from a URI path |
||
| 366 | * |
||
| 367 | * @param string $path |
||
| 368 | * |
||
| 369 | * @return string |
||
| 370 | */ |
||
| 371 | public static function getFile(string $path): string |
||
| 374 | } |
||
| 375 | |||
| 376 | /** |
||
| 377 | * @param array $config |
||
| 378 | * @param string $fileName |
||
| 379 | * @param string $type |
||
| 380 | * |
||
| 381 | * @return string |
||
| 382 | */ |
||
| 383 | public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string |
||
| 384 | { |
||
| 385 | $path = null; |
||
| 386 | try { |
||
| 387 | $path = self::getModuleEntry($config, $fileName, $type, true); |
||
| 388 | } catch (NotFoundHttpException $e) { |
||
| 389 | Craft::error($e->getMessage(), __METHOD__); |
||
| 390 | } |
||
| 391 | if ($path !== null) { |
||
| 392 | // Determine whether we should use the devServer for HMR or not |
||
| 393 | $devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
||
| 394 | if ($devMode) { |
||
| 395 | $devServerPrefix = $config['devServer']['publicPath']; |
||
| 396 | $devServerPath = self::combinePaths( |
||
| 397 | $devServerPrefix, |
||
| 398 | $path |
||
| 399 | ); |
||
| 400 | $devServerFile = self::getFileFromUri($devServerPath, null); |
||
| 401 | if ($devServerFile) { |
||
| 402 | return $devServerFile; |
||
| 403 | } |
||
| 404 | } |
||
| 405 | // Otherwise, try not-hot files |
||
| 406 | $localPrefix = $config['localFiles']['basePath'].$config['localFiles']['criticalPrefix']; |
||
| 407 | $localPath = self::combinePaths( |
||
| 408 | $localPrefix, |
||
| 409 | $path |
||
| 410 | ); |
||
| 411 | $alias = Craft::getAlias($localPath, false); |
||
| 412 | if ($alias && is_string($alias)) { |
||
| 413 | $localPath = $alias; |
||
| 414 | } |
||
| 415 | if (is_file($localPath)) { |
||
| 416 | return self::getFile($localPath) ?? ''; |
||
| 417 | } |
||
| 418 | } |
||
| 419 | |||
| 420 | return ''; |
||
| 421 | } |
||
| 422 | |||
| 423 | /** |
||
| 424 | * Invalidate all of the manifest caches |
||
| 425 | */ |
||
| 426 | public static function invalidateCaches() |
||
| 427 | { |
||
| 428 | $cache = Craft::$app->getCache(); |
||
| 429 | TagDependency::invalidate($cache, self::CACHE_TAG); |
||
| 430 | Craft::info('All manifest caches cleared', __METHOD__); |
||
| 431 | } |
||
| 432 | |||
| 433 | /** |
||
| 434 | * Return the contents of a JSON file from a URI path |
||
| 435 | * |
||
| 436 | * @param string $path |
||
| 437 | * |
||
| 438 | * @return null|array |
||
| 439 | */ |
||
| 440 | protected static function getJsonFile(string $path) |
||
| 441 | { |
||
| 442 | return self::getFileFromUri($path, [self::class, 'jsonFileDecode']); |
||
| 443 | } |
||
| 444 | |||
| 445 | // Protected Static Methods |
||
| 446 | // ========================================================================= |
||
| 447 | |||
| 448 | /** |
||
| 449 | * Return the contents of a file from a URI path |
||
| 450 | * |
||
| 451 | * @param string $path |
||
| 452 | * @param callable|null $callback |
||
| 453 | * @param bool $pathOnly |
||
| 454 | * |
||
| 455 | * @return null|mixed |
||
| 456 | */ |
||
| 457 | protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false) |
||
| 458 | { |
||
| 459 | // Resolve any aliases |
||
| 460 | $alias = Craft::getAlias($path, false); |
||
| 461 | if ($alias && is_string($alias)) { |
||
| 462 | $path = $alias; |
||
| 463 | } |
||
| 464 | // If we only want the file via path, make sure it exists |
||
| 465 | if ($pathOnly && !is_file($path)) { |
||
| 466 | Craft::warning(Craft::t( |
||
| 467 | 'twigpack', |
||
| 468 | 'File does not exist: {path}', |
||
| 469 | ['path' => $path] |
||
| 470 | ), __METHOD__); |
||
| 471 | |||
| 472 | return ''; |
||
| 473 | } |
||
| 474 | // Make sure it's a full URL |
||
| 475 | if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) { |
||
| 476 | try { |
||
| 477 | $path = UrlHelper::siteUrl($path); |
||
| 478 | } catch (Exception $e) { |
||
| 479 | Craft::error($e->getMessage(), __METHOD__); |
||
| 480 | } |
||
| 481 | } |
||
| 482 | |||
| 483 | return self::getFileContents($path, $callback); |
||
| 484 | } |
||
| 485 | |||
| 486 | /** |
||
| 487 | * Return the contents of a file from the passed in path |
||
| 488 | * |
||
| 489 | * @param string $path |
||
| 490 | * @param callable $callback |
||
| 491 | * |
||
| 492 | * @return null|mixed |
||
| 493 | */ |
||
| 494 | protected static function getFileContents(string $path, callable $callback = null) |
||
| 554 | } |
||
| 555 | |||
| 556 | /** |
||
| 557 | * Combined the passed in paths, whether file system or URL |
||
| 558 | * |
||
| 559 | * @param string ...$paths |
||
| 560 | * |
||
| 561 | * @return string |
||
| 562 | */ |
||
| 563 | protected static function combinePaths(string ...$paths): string |
||
| 564 | { |
||
| 565 | $last_key = count($paths) - 1; |
||
| 566 | array_walk($paths, function (&$val, $key) use ($last_key) { |
||
| 567 | switch ($key) { |
||
| 568 | case 0: |
||
| 569 | $val = rtrim($val, '/ '); |
||
| 570 | break; |
||
| 571 | case $last_key: |
||
| 572 | $val = ltrim($val, '/ '); |
||
| 573 | break; |
||
| 574 | default: |
||
| 575 | $val = trim($val, '/ '); |
||
| 576 | break; |
||
| 577 | } |
||
| 578 | }); |
||
| 579 | |||
| 580 | $first = array_shift($paths); |
||
| 581 | $last = array_pop($paths); |
||
| 582 | $paths = array_filter($paths); |
||
| 583 | array_unshift($paths, $first); |
||
| 584 | $paths[] = $last; |
||
| 585 | |||
| 586 | return implode('/', $paths); |
||
| 587 | } |
||
| 588 | |||
| 589 | /** |
||
| 590 | * @param string $error |
||
| 591 | * @param bool $soft |
||
| 592 | * |
||
| 593 | * @throws NotFoundHttpException |
||
| 594 | */ |
||
| 595 | protected static function reportError(string $error, $soft = false) |
||
| 602 | } |
||
| 603 | |||
| 604 | // Private Static Methods |
||
| 605 | // ========================================================================= |
||
| 606 | |||
| 607 | /** |
||
| 608 | * @param $string |
||
| 609 | * |
||
| 610 | * @return null|array |
||
| 611 | */ |
||
| 612 | private static function jsonFileDecode($string) |
||
| 621 | } |
||
| 622 | } |
||
| 623 |