| Total Complexity | 52 |
| Total Lines | 460 |
| Duplicated Lines | 0 % |
| Changes | 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 |
||
| 27 | class Manifest |
||
| 28 | { |
||
| 29 | // Constants |
||
| 30 | // ========================================================================= |
||
| 31 | |||
| 32 | const CACHE_KEY = 'twigpack-webperf'; |
||
| 33 | const CACHE_TAG = 'twigpack-webperf'; |
||
| 34 | |||
| 35 | const DEVMODE_CACHE_DURATION = 1; |
||
| 36 | |||
| 37 | // Protected Static Properties |
||
| 38 | // ========================================================================= |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @var array |
||
| 42 | */ |
||
| 43 | protected static $files; |
||
| 44 | |||
| 45 | /** |
||
| 46 | * @var bool |
||
| 47 | */ |
||
| 48 | protected static $isHot = false; |
||
| 49 | |||
| 50 | // Public Static Methods |
||
| 51 | // ========================================================================= |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @param array $config |
||
| 55 | * @param string $moduleName |
||
| 56 | * @param bool $async |
||
| 57 | * |
||
| 58 | * @return string |
||
| 59 | * @throws NotFoundHttpException |
||
| 60 | */ |
||
| 61 | public static function getCssModuleTags(array $config, string $moduleName, bool $async): string |
||
| 62 | { |
||
| 63 | $legacyModule = self::getModule($config, $moduleName, 'legacy', true); |
||
| 64 | if ($legacyModule === null) { |
||
| 65 | return ''; |
||
| 66 | } |
||
| 67 | $lines = []; |
||
| 68 | if ($async) { |
||
| 69 | $lines[] = "<link rel=\"preload\" href=\"{$legacyModule}\" as=\"style\" onload=\"this.onload=null;this.rel='stylesheet'\" />"; |
||
| 70 | $lines[] = "<noscript><link rel=\"stylesheet\" href=\"{$legacyModule}\"></noscript>"; |
||
| 71 | } else { |
||
| 72 | $lines[] = "<link rel=\"stylesheet\" href=\"{$legacyModule}\" />"; |
||
| 73 | } |
||
| 74 | |||
| 75 | return implode("\r\n", $lines); |
||
| 76 | } |
||
| 77 | |||
| 78 | /** |
||
| 79 | * @param string $path |
||
| 80 | * |
||
| 81 | * @return string |
||
| 82 | */ |
||
| 83 | public static function getCssInlineTags(string $path): string |
||
| 84 | { |
||
| 85 | $result = self::getFile($path); |
||
| 86 | if ($result) { |
||
| 87 | $result = "<style>\r\n".$result."</style>\r\n"; |
||
| 88 | return $result; |
||
| 89 | } |
||
| 90 | |||
| 91 | return ''; |
||
| 92 | } |
||
| 93 | |||
| 94 | /** |
||
| 95 | * Returns the uglified loadCSS rel=preload Polyfill as per: |
||
| 96 | * https://github.com/filamentgroup/loadCSS#how-to-use-loadcss-recommended-example |
||
| 97 | * |
||
| 98 | * @return string |
||
| 99 | */ |
||
| 100 | public static function getCssRelPreloadPolyfill(): string |
||
| 101 | { |
||
| 102 | return <<<EOT |
||
| 103 | <script> |
||
| 104 | /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */ |
||
| 105 | !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); |
||
| 106 | </script> |
||
| 107 | EOT; |
||
| 108 | } |
||
| 109 | |||
| 110 | /** |
||
| 111 | * @param array $config |
||
| 112 | * @param string $moduleName |
||
| 113 | * @param bool $async |
||
| 114 | * |
||
| 115 | * @return null|string |
||
| 116 | * @throws NotFoundHttpException |
||
| 117 | */ |
||
| 118 | public static function getJsModuleTags(array $config, string $moduleName, bool $async) |
||
| 119 | { |
||
| 120 | $legacyModule = self::getModule($config, $moduleName, 'legacy'); |
||
| 121 | if ($legacyModule === null) { |
||
| 122 | return ''; |
||
| 123 | } |
||
| 124 | if ($async) { |
||
| 125 | $modernModule = self::getModule($config, $moduleName, 'modern'); |
||
| 126 | if ($modernModule === null) { |
||
| 127 | return ''; |
||
| 128 | } |
||
| 129 | } |
||
| 130 | $lines = []; |
||
| 131 | if ($async) { |
||
| 132 | $lines[] = "<script type=\"module\" src=\"{$modernModule}\"></script>"; |
||
| 133 | $lines[] = "<script nomodule src=\"{$legacyModule}\"></script>"; |
||
| 134 | } else { |
||
| 135 | $lines[] = "<script src=\"{$legacyModule}\"></script>"; |
||
| 136 | } |
||
| 137 | |||
| 138 | return implode("\r\n", $lines); |
||
| 139 | } |
||
| 140 | |||
| 141 | /** |
||
| 142 | * Safari 10.1 supports modules, but does not support the `nomodule` |
||
| 143 | * attribute - it will load <script nomodule> anyway. This snippet solve |
||
| 144 | * this problem, but only for script tags that load external code, e.g.: |
||
| 145 | * <script nomodule src="nomodule.js"></script> |
||
| 146 | * |
||
| 147 | * Again: this will **not* # prevent inline script, e.g.: |
||
| 148 | * <script nomodule>alert('no modules');</script>. |
||
| 149 | * |
||
| 150 | * This workaround is possible because Safari supports the non-standard |
||
| 151 | * 'beforeload' event. This allows us to trap the module and nomodule load. |
||
| 152 | * |
||
| 153 | * Note also that `nomodule` is supported in later versions of Safari - |
||
| 154 | * it's just 10.1 that omits this attribute. |
||
| 155 | * |
||
| 156 | * c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc |
||
| 157 | * |
||
| 158 | * @return string |
||
| 159 | */ |
||
| 160 | public static function getSafariNomoduleFix(): string |
||
| 161 | { |
||
| 162 | return <<<EOT |
||
| 163 | <script> |
||
| 164 | !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()}}(); |
||
| 165 | </script> |
||
| 166 | EOT; |
||
| 167 | } |
||
| 168 | |||
| 169 | /** |
||
| 170 | * Return the URI to a module |
||
| 171 | * |
||
| 172 | * @param array $config |
||
| 173 | * @param string $moduleName |
||
| 174 | * @param string $type |
||
| 175 | * @param bool $soft |
||
| 176 | * |
||
| 177 | * @return null|string |
||
| 178 | * @throws NotFoundHttpException |
||
| 179 | */ |
||
| 180 | public static function getModule(array $config, string $moduleName, string $type = 'modern', bool $soft = false) |
||
| 181 | { |
||
| 182 | // Get the module entry |
||
| 183 | $module = self::getModuleEntry($config, $moduleName, $type, $soft); |
||
| 184 | if ($module !== null) { |
||
| 185 | $prefix = self::$isHot |
||
| 186 | ? $config['devServer']['publicPath'] |
||
| 187 | : $config['server']['publicPath']; |
||
| 188 | // If the module isn't a full URL, prefix it |
||
| 189 | if (!UrlHelper::isAbsoluteUrl($module)) { |
||
| 190 | $module = self::combinePaths($prefix, $module); |
||
| 191 | } |
||
| 192 | // Resolve any aliases |
||
| 193 | $alias = Craft::getAlias($module, false); |
||
| 194 | if ($alias) { |
||
| 195 | $module = $alias; |
||
| 196 | } |
||
| 197 | // Make sure it's a full URL |
||
| 198 | if (!UrlHelper::isAbsoluteUrl($module) && !is_file($module)) { |
||
| 199 | try { |
||
| 200 | $module = UrlHelper::siteUrl($module); |
||
| 201 | } catch (Exception $e) { |
||
| 202 | Craft::error($e->getMessage(), __METHOD__); |
||
| 203 | } |
||
| 204 | } |
||
| 205 | } else { |
||
| 206 | $module = ''; |
||
| 207 | } |
||
| 208 | |||
| 209 | return $module; |
||
| 210 | } |
||
| 211 | |||
| 212 | /** |
||
| 213 | * Return a module's raw entry from the manifest |
||
| 214 | * |
||
| 215 | * @param array $config |
||
| 216 | * @param string $moduleName |
||
| 217 | * @param string $type |
||
| 218 | * @param bool $soft |
||
| 219 | * |
||
| 220 | * @return null|string |
||
| 221 | * @throws NotFoundHttpException |
||
| 222 | */ |
||
| 223 | public static function getModuleEntry(array $config, string $moduleName, string $type = 'modern', bool $soft = false) |
||
| 224 | { |
||
| 225 | $module = null; |
||
| 226 | // Get the manifest file |
||
| 227 | $manifest = self::getManifestFile($config, $type); |
||
| 228 | if ($manifest !== null) { |
||
| 229 | // Make sure it exists in the manifest |
||
| 230 | if (empty($manifest[$moduleName])) { |
||
| 231 | self::reportError(Craft::t( |
||
| 232 | 'webperf', |
||
| 233 | 'Module does not exist in the manifest: {moduleName}', |
||
| 234 | ['moduleName' => $moduleName] |
||
| 235 | ), $soft); |
||
| 236 | |||
| 237 | return null; |
||
| 238 | } |
||
| 239 | $module = $manifest[$moduleName]; |
||
| 240 | } |
||
| 241 | |||
| 242 | return $module; |
||
| 243 | } |
||
| 244 | |||
| 245 | /** |
||
| 246 | * Return a JSON-decoded manifest file |
||
| 247 | * |
||
| 248 | * @param array $config |
||
| 249 | * @param string $type |
||
| 250 | * |
||
| 251 | * @return null|array |
||
| 252 | * @throws NotFoundHttpException |
||
| 253 | */ |
||
| 254 | public static function getManifestFile(array $config, string $type = 'modern') |
||
| 255 | { |
||
| 256 | $manifest = null; |
||
| 257 | // Determine whether we should use the devServer for HMR or not |
||
| 258 | $devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
||
| 259 | self::$isHot = ($devMode && $config['useDevServer']); |
||
| 260 | // Try to get the manifest |
||
| 261 | while ($manifest === null) { |
||
| 262 | $manifestPath = self::$isHot |
||
| 263 | ? $config['devServer']['manifestPath'] |
||
| 264 | : $config['server']['manifestPath']; |
||
| 265 | // Normalize the path |
||
| 266 | $path = self::combinePaths($manifestPath, $config['manifest'][$type]); |
||
| 267 | $manifest = self::getJsonFile($path); |
||
| 268 | // If the manifest isn't found, and it was hot, fall back on non-hot |
||
| 269 | if ($manifest === null) { |
||
| 270 | // We couldn't find a manifest; throw an error |
||
| 271 | self::reportError(Craft::t( |
||
| 272 | 'webperf', |
||
| 273 | 'Manifest file not found at: {manifestPath}', |
||
| 274 | ['manifestPath' => $manifestPath] |
||
| 275 | ), true); |
||
| 276 | if (self::$isHot) { |
||
| 277 | // Try again, but not with home module replacement |
||
| 278 | self::$isHot = false; |
||
| 279 | } else { |
||
| 280 | // Give up and return null |
||
| 281 | return null; |
||
| 282 | } |
||
| 283 | } |
||
| 284 | } |
||
| 285 | |||
| 286 | return $manifest; |
||
| 287 | } |
||
| 288 | |||
| 289 | /** |
||
| 290 | * Returns the contents of a file from a URI path |
||
| 291 | * |
||
| 292 | * @param string $path |
||
| 293 | * |
||
| 294 | * @return string |
||
| 295 | */ |
||
| 296 | public static function getFile(string $path): string |
||
| 297 | { |
||
| 298 | return self::getFileFromUri($path, null) ?? ''; |
||
| 299 | } |
||
| 300 | |||
| 301 | /** |
||
| 302 | * @param array $config |
||
| 303 | * @param string $fileName |
||
| 304 | * @param string $type |
||
| 305 | * |
||
| 306 | * @return string |
||
| 307 | */ |
||
| 308 | public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string |
||
| 325 | } |
||
| 326 | |||
| 327 | /** |
||
| 328 | * Return the contents of a JSON file from a URI path |
||
| 329 | * |
||
| 330 | * @param string $path |
||
| 331 | * |
||
| 332 | * @return null|array |
||
| 333 | */ |
||
| 334 | protected static function getJsonFile(string $path) |
||
| 335 | { |
||
| 336 | return self::getFileFromUri($path, [self::class, 'jsonFileDecode']); |
||
| 337 | } |
||
| 338 | |||
| 339 | /** |
||
| 340 | * Invalidate all of the manifest caches |
||
| 341 | */ |
||
| 342 | public static function invalidateCaches() |
||
| 343 | { |
||
| 344 | $cache = Craft::$app->getCache(); |
||
| 345 | TagDependency::invalidate($cache, self::CACHE_TAG); |
||
| 346 | Craft::info('All manifest caches cleared', __METHOD__); |
||
| 347 | } |
||
| 348 | |||
| 349 | // Protected Static Methods |
||
| 350 | // ========================================================================= |
||
| 351 | |||
| 352 | /** |
||
| 353 | * Return the contents of a file from a URI path |
||
| 354 | * |
||
| 355 | * @param string $path |
||
| 356 | * @param callable|null $callback |
||
| 357 | * |
||
| 358 | * @return null|mixed |
||
| 359 | */ |
||
| 360 | protected static function getFileFromUri(string $path, callable $callback = null) |
||
| 377 | } |
||
| 378 | |||
| 379 | /** |
||
| 380 | * Return the contents of a file from the passed in path |
||
| 381 | * |
||
| 382 | * @param string $path |
||
| 383 | * @param callable $callback |
||
| 384 | * |
||
| 385 | * @return null|mixed |
||
| 386 | */ |
||
| 387 | protected static function getFileContents(string $path, callable $callback = null) |
||
| 388 | { |
||
| 389 | // Return the memoized manifest if it exists |
||
| 390 | if (!empty(self::$files[$path])) { |
||
| 391 | return self::$files[$path]; |
||
| 392 | } |
||
| 393 | // Create the dependency tags |
||
| 394 | $dependency = new TagDependency([ |
||
| 395 | 'tags' => [ |
||
| 396 | self::CACHE_TAG, |
||
| 397 | self::CACHE_TAG.$path, |
||
| 398 | ], |
||
| 399 | ]); |
||
| 400 | // Set the cache duration based on devMode |
||
| 401 | $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode |
||
| 402 | ? self::DEVMODE_CACHE_DURATION |
||
| 403 | : null; |
||
| 404 | // Get the result from the cache, or parse the file |
||
| 405 | $cache = Craft::$app->getCache(); |
||
| 406 | $file = $cache->getOrSet( |
||
| 407 | self::CACHE_KEY.$path, |
||
| 408 | function () use ($path, $callback) { |
||
| 409 | $result = null; |
||
| 410 | $contents = @file_get_contents($path); |
||
| 411 | if ($contents) { |
||
| 412 | $result = $contents; |
||
| 413 | if ($callback) { |
||
| 414 | $result = $callback($result); |
||
| 415 | } |
||
| 416 | } |
||
| 417 | |||
| 418 | return $result; |
||
| 419 | }, |
||
| 420 | $cacheDuration, |
||
| 421 | $dependency |
||
| 422 | ); |
||
| 423 | self::$files[$path] = $file; |
||
| 424 | |||
| 425 | return $file; |
||
| 426 | } |
||
| 427 | |||
| 428 | /** |
||
| 429 | * Combined the passed in paths, whether file system or URL |
||
| 430 | * |
||
| 431 | * @param string ...$paths |
||
| 432 | * |
||
| 433 | * @return string |
||
| 434 | */ |
||
| 435 | protected static function combinePaths(string ...$paths): string |
||
| 459 | } |
||
| 460 | |||
| 461 | /** |
||
| 462 | * @param string $error |
||
| 463 | * @param bool $soft |
||
| 464 | * |
||
| 465 | * @throws NotFoundHttpException |
||
| 466 | */ |
||
| 467 | protected static function reportError(string $error, $soft = false) |
||
| 468 | { |
||
| 469 | $devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
||
| 470 | if ($devMode && !$soft) { |
||
| 471 | throw new NotFoundHttpException($error); |
||
| 472 | } |
||
| 473 | Craft::error($error, __METHOD__); |
||
| 474 | } |
||
| 475 | |||
| 476 | // Private Static Methods |
||
| 477 | // ========================================================================= |
||
| 478 | |||
| 479 | /** |
||
| 480 | * @param $string |
||
| 481 | * |
||
| 482 | * @return mixed |
||
| 483 | */ |
||
| 484 | private static function jsonFileDecode($string) |
||
| 487 | } |
||
| 488 | } |
||
| 489 |