Total Complexity | 60 |
Total Lines | 534 |
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 |
||
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 |
||
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 |
||
197 | { |
||
198 | return <<<EOT |
||
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) |
||
217 | { |
||
218 | // Get the module entry |
||
219 | $module = self::getModuleEntry($config, $moduleName, $type, $soft); |
||
220 | if ($module !== null) { |
||
221 | $prefix = self::$isHot |
||
222 | ? $config['devServer']['publicPath'] |
||
223 | : $config['server']['publicPath']; |
||
224 | // If the module isn't a full URL, prefix it |
||
225 | if (!UrlHelper::isAbsoluteUrl($module)) { |
||
226 | $module = self::combinePaths($prefix, $module); |
||
227 | } |
||
228 | // Resolve any aliases |
||
229 | $alias = Craft::getAlias($module, false); |
||
230 | if ($alias) { |
||
231 | $module = $alias; |
||
232 | } |
||
233 | // Make sure it's a full URL |
||
234 | if (!UrlHelper::isAbsoluteUrl($module) && !is_file($module)) { |
||
235 | try { |
||
236 | $module = UrlHelper::siteUrl($module); |
||
237 | } catch (Exception $e) { |
||
238 | Craft::error($e->getMessage(), __METHOD__); |
||
239 | } |
||
240 | } |
||
241 | } |
||
242 | |||
243 | return $module; |
||
244 | } |
||
245 | |||
246 | /** |
||
247 | * Return a module's raw entry from the manifest |
||
248 | * |
||
249 | * @param array $config |
||
250 | * @param string $moduleName |
||
251 | * @param string $type |
||
252 | * @param bool $soft |
||
253 | * |
||
254 | * @return null|string |
||
255 | * @throws NotFoundHttpException |
||
256 | */ |
||
257 | public static function getModuleEntry( |
||
258 | array $config, |
||
259 | string $moduleName, |
||
260 | string $type = 'modern', |
||
261 | bool $soft = false |
||
262 | ) { |
||
263 | $module = null; |
||
264 | // Get the manifest file |
||
265 | $manifest = self::getManifestFile($config, $type); |
||
266 | if ($manifest !== null) { |
||
267 | // Make sure it exists in the manifest |
||
268 | if (empty($manifest[$moduleName])) { |
||
269 | self::reportError(Craft::t( |
||
270 | 'twigpack', |
||
271 | 'Module does not exist in the manifest: {moduleName}', |
||
272 | ['moduleName' => $moduleName] |
||
273 | ), $soft); |
||
274 | |||
275 | return null; |
||
276 | } |
||
277 | $module = $manifest[$moduleName]; |
||
278 | } |
||
279 | |||
280 | return $module; |
||
281 | } |
||
282 | |||
283 | /** |
||
284 | * Return a JSON-decoded manifest file |
||
285 | * |
||
286 | * @param array $config |
||
287 | * @param string $type |
||
288 | * |
||
289 | * @return null|array |
||
290 | * @throws NotFoundHttpException |
||
291 | */ |
||
292 | public static function getManifestFile(array $config, string $type = 'modern') |
||
293 | { |
||
294 | $manifest = null; |
||
295 | // Determine whether we should use the devServer for HMR or not |
||
296 | $devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
||
297 | self::$isHot = ($devMode && $config['useDevServer']); |
||
298 | // Try to get the manifest |
||
299 | while ($manifest === null) { |
||
300 | $manifestPath = self::$isHot |
||
301 | ? $config['devServer']['manifestPath'] |
||
302 | : $config['server']['manifestPath']; |
||
303 | // Normalize the path |
||
304 | $path = self::combinePaths($manifestPath, $config['manifest'][$type]); |
||
305 | $manifest = self::getJsonFile($path); |
||
306 | // If the manifest isn't found, and it was hot, fall back on non-hot |
||
307 | if ($manifest === null) { |
||
308 | // We couldn't find a manifest; throw an error |
||
309 | self::reportError(Craft::t( |
||
310 | 'twigpack', |
||
311 | 'Manifest file not found at: {manifestPath}', |
||
312 | ['manifestPath' => $manifestPath] |
||
313 | ), true); |
||
314 | if (self::$isHot) { |
||
315 | // Try again, but not with home module replacement |
||
316 | self::$isHot = false; |
||
317 | } else { |
||
318 | // Give up and return null |
||
319 | return null; |
||
320 | } |
||
321 | } |
||
322 | } |
||
323 | |||
324 | return $manifest; |
||
325 | } |
||
326 | |||
327 | /** |
||
328 | * Returns the contents of a file from a URI path |
||
329 | * |
||
330 | * @param string $path |
||
331 | * |
||
332 | * @return string |
||
333 | */ |
||
334 | public static function getFile(string $path): string |
||
335 | { |
||
336 | return self::getFileFromUri($path, null, true) ?? ''; |
||
337 | } |
||
338 | |||
339 | /** |
||
340 | * @param array $config |
||
341 | * @param string $fileName |
||
342 | * @param string $type |
||
343 | * |
||
344 | * @return string |
||
345 | */ |
||
346 | public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string |
||
347 | { |
||
348 | $path = null; |
||
349 | try { |
||
350 | $path = self::getModuleEntry($config, $fileName, $type, true); |
||
351 | } catch (NotFoundHttpException $e) { |
||
352 | Craft::error($e->getMessage(), __METHOD__); |
||
353 | } |
||
354 | if ($path !== null) { |
||
355 | $path = self::combinePaths( |
||
356 | $config['localFiles']['basePath'], |
||
357 | $path |
||
358 | ); |
||
359 | |||
360 | return self::getFileFromUri($path, null) ?? ''; |
||
361 | } |
||
362 | |||
363 | return ''; |
||
364 | } |
||
365 | |||
366 | /** |
||
367 | * Invalidate all of the manifest caches |
||
368 | */ |
||
369 | public static function invalidateCaches() |
||
370 | { |
||
371 | $cache = Craft::$app->getCache(); |
||
372 | TagDependency::invalidate($cache, self::CACHE_TAG); |
||
373 | Craft::info('All manifest caches cleared', __METHOD__); |
||
374 | } |
||
375 | |||
376 | /** |
||
377 | * Return the contents of a JSON file from a URI path |
||
378 | * |
||
379 | * @param string $path |
||
380 | * |
||
381 | * @return null|array |
||
382 | */ |
||
383 | protected static function getJsonFile(string $path) |
||
384 | { |
||
385 | return self::getFileFromUri($path, [self::class, 'jsonFileDecode']); |
||
386 | } |
||
387 | |||
388 | // Protected Static Methods |
||
389 | // ========================================================================= |
||
390 | |||
391 | /** |
||
392 | * Return the contents of a file from a URI path |
||
393 | * |
||
394 | * @param string $path |
||
395 | * @param callable|null $callback |
||
396 | * @param bool $pathOnly |
||
397 | * |
||
398 | * @return null|mixed |
||
399 | */ |
||
400 | protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false) |
||
401 | { |
||
402 | // Resolve any aliases |
||
403 | $alias = Craft::getAlias($path, false); |
||
404 | if ($alias && is_string($alias)) { |
||
405 | $path = $alias; |
||
406 | } |
||
407 | // If we only want the file via path, make sure it exists |
||
408 | if ($pathOnly && !is_file($path)) { |
||
409 | Craft::warning(Craft::t( |
||
410 | 'twigpack', |
||
411 | 'File does not exist: {path}', |
||
412 | ['path' => $path] |
||
413 | ), __METHOD__); |
||
414 | |||
415 | return ''; |
||
416 | } |
||
417 | // Make sure it's a full URL |
||
418 | if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) { |
||
419 | try { |
||
420 | $path = UrlHelper::siteUrl($path); |
||
421 | } catch (Exception $e) { |
||
422 | Craft::error($e->getMessage(), __METHOD__); |
||
423 | } |
||
424 | } |
||
425 | |||
426 | return self::getFileContents($path, $callback); |
||
427 | } |
||
428 | |||
429 | /** |
||
430 | * Return the contents of a file from the passed in path |
||
431 | * |
||
432 | * @param string $path |
||
433 | * @param callable $callback |
||
434 | * |
||
435 | * @return null|mixed |
||
436 | */ |
||
437 | protected static function getFileContents(string $path, callable $callback = null) |
||
495 | } |
||
496 | |||
497 | /** |
||
498 | * Combined the passed in paths, whether file system or URL |
||
499 | * |
||
500 | * @param string ...$paths |
||
501 | * |
||
502 | * @return string |
||
503 | */ |
||
504 | protected static function combinePaths(string ...$paths): string |
||
505 | { |
||
506 | $last_key = count($paths) - 1; |
||
507 | array_walk($paths, function (&$val, $key) use ($last_key) { |
||
508 | switch ($key) { |
||
509 | case 0: |
||
510 | $val = rtrim($val, '/ '); |
||
511 | break; |
||
512 | case $last_key: |
||
513 | $val = ltrim($val, '/ '); |
||
514 | break; |
||
515 | default: |
||
516 | $val = trim($val, '/ '); |
||
517 | break; |
||
518 | } |
||
519 | }); |
||
520 | |||
521 | $first = array_shift($paths); |
||
522 | $last = array_pop($paths); |
||
523 | $paths = array_filter($paths); |
||
524 | array_unshift($paths, $first); |
||
525 | $paths[] = $last; |
||
526 | |||
527 | return implode('/', $paths); |
||
528 | } |
||
529 | |||
530 | /** |
||
531 | * @param string $error |
||
532 | * @param bool $soft |
||
533 | * |
||
534 | * @throws NotFoundHttpException |
||
535 | */ |
||
536 | protected static function reportError(string $error, $soft = false) |
||
543 | } |
||
544 | |||
545 | // Private Static Methods |
||
546 | // ========================================================================= |
||
547 | |||
548 | /** |
||
549 | * @param $string |
||
550 | * |
||
551 | * @return null|array |
||
552 | */ |
||
553 | private static function jsonFileDecode($string) |
||
562 | } |
||
563 | } |
||
564 |