Total Complexity | 52 |
Total Lines | 458 |
Duplicated Lines | 0 % |
Changes | 1 | ||
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 |
||
27 | class Manifest |
||
28 | { |
||
29 | // Constants |
||
30 | // ========================================================================= |
||
31 | |||
32 | const CACHE_KEY = 'twigpack-transcoder'; |
||
33 | const CACHE_TAG = 'twigpack-transcoder'; |
||
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 | } |
||
206 | |||
207 | return $module; |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * Return a module's raw entry from the manifest |
||
212 | * |
||
213 | * @param array $config |
||
214 | * @param string $moduleName |
||
215 | * @param string $type |
||
216 | * @param bool $soft |
||
217 | * |
||
218 | * @return null|string |
||
219 | * @throws NotFoundHttpException |
||
220 | */ |
||
221 | public static function getModuleEntry(array $config, string $moduleName, string $type = 'modern', bool $soft = false) |
||
222 | { |
||
223 | $module = null; |
||
224 | // Get the manifest file |
||
225 | $manifest = self::getManifestFile($config, $type); |
||
226 | if ($manifest !== null) { |
||
227 | // Make sure it exists in the manifest |
||
228 | if (empty($manifest[$moduleName])) { |
||
229 | self::reportError(Craft::t( |
||
230 | 'transcoder', |
||
231 | 'Module does not exist in the manifest: {moduleName}', |
||
232 | ['moduleName' => $moduleName] |
||
233 | ), $soft); |
||
234 | |||
235 | return null; |
||
236 | } |
||
237 | $module = $manifest[$moduleName]; |
||
238 | } |
||
239 | |||
240 | return $module; |
||
241 | } |
||
242 | |||
243 | /** |
||
244 | * Return a JSON-decoded manifest file |
||
245 | * |
||
246 | * @param array $config |
||
247 | * @param string $type |
||
248 | * |
||
249 | * @return null|array |
||
250 | * @throws NotFoundHttpException |
||
251 | */ |
||
252 | public static function getManifestFile(array $config, string $type = 'modern') |
||
253 | { |
||
254 | $manifest = null; |
||
255 | // Determine whether we should use the devServer for HMR or not |
||
256 | $devMode = Craft::$app->getConfig()->getGeneral()->devMode; |
||
257 | self::$isHot = ($devMode && $config['useDevServer']); |
||
258 | // Try to get the manifest |
||
259 | while ($manifest === null) { |
||
260 | $manifestPath = self::$isHot |
||
261 | ? $config['devServer']['manifestPath'] |
||
262 | : $config['server']['manifestPath']; |
||
263 | // Normalize the path |
||
264 | $path = self::combinePaths($manifestPath, $config['manifest'][$type]); |
||
265 | $manifest = self::getJsonFile($path); |
||
266 | // If the manifest isn't found, and it was hot, fall back on non-hot |
||
267 | if ($manifest === null) { |
||
268 | // We couldn't find a manifest; throw an error |
||
269 | self::reportError(Craft::t( |
||
270 | 'transcoder', |
||
271 | 'Manifest file not found at: {manifestPath}', |
||
272 | ['manifestPath' => $manifestPath] |
||
273 | ), true); |
||
274 | if (self::$isHot) { |
||
275 | // Try again, but not with home module replacement |
||
276 | self::$isHot = false; |
||
277 | } else { |
||
278 | // Give up and return null |
||
279 | return null; |
||
280 | } |
||
281 | } |
||
282 | } |
||
283 | |||
284 | return $manifest; |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Returns the contents of a file from a URI path |
||
289 | * |
||
290 | * @param string $path |
||
291 | * |
||
292 | * @return string |
||
293 | */ |
||
294 | public static function getFile(string $path): string |
||
295 | { |
||
296 | return self::getFileFromUri($path, null) ?? ''; |
||
297 | } |
||
298 | |||
299 | /** |
||
300 | * @param array $config |
||
301 | * @param string $fileName |
||
302 | * @param string $type |
||
303 | * |
||
304 | * @return string |
||
305 | */ |
||
306 | public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string |
||
307 | { |
||
308 | try { |
||
309 | $path = self::getModuleEntry($config, $fileName, $type, true); |
||
310 | } catch (NotFoundHttpException $e) { |
||
311 | Craft::error($e->getMessage(), __METHOD__); |
||
312 | } |
||
313 | if ($path !== null) { |
||
314 | $path = self::combinePaths( |
||
315 | $config['localFiles']['basePath'], |
||
316 | $path |
||
317 | ); |
||
318 | |||
319 | return self::getFileFromUri($path, null) ?? ''; |
||
320 | } |
||
321 | |||
322 | return ''; |
||
323 | } |
||
324 | |||
325 | /** |
||
326 | * Return the contents of a JSON file from a URI path |
||
327 | * |
||
328 | * @param string $path |
||
329 | * |
||
330 | * @return null|array |
||
331 | */ |
||
332 | protected static function getJsonFile(string $path) |
||
333 | { |
||
334 | return self::getFileFromUri($path, [self::class, 'jsonFileDecode']); |
||
335 | } |
||
336 | |||
337 | /** |
||
338 | * Invalidate all of the manifest caches |
||
339 | */ |
||
340 | public static function invalidateCaches() |
||
341 | { |
||
342 | $cache = Craft::$app->getCache(); |
||
343 | TagDependency::invalidate($cache, self::CACHE_TAG); |
||
344 | Craft::info('All manifest caches cleared', __METHOD__); |
||
345 | } |
||
346 | |||
347 | // Protected Static Methods |
||
348 | // ========================================================================= |
||
349 | |||
350 | /** |
||
351 | * Return the contents of a file from a URI path |
||
352 | * |
||
353 | * @param string $path |
||
354 | * @param callable|null $callback |
||
355 | * |
||
356 | * @return null|mixed |
||
357 | */ |
||
358 | protected static function getFileFromUri(string $path, callable $callback = null) |
||
359 | { |
||
360 | // Resolve any aliases |
||
361 | $alias = Craft::getAlias($path, false); |
||
362 | if ($alias) { |
||
363 | $path = $alias; |
||
364 | } |
||
365 | // Make sure it's a full URL |
||
366 | if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) { |
||
367 | try { |
||
368 | $path = UrlHelper::siteUrl($path); |
||
369 | } catch (Exception $e) { |
||
370 | Craft::error($e->getMessage(), __METHOD__); |
||
371 | } |
||
372 | } |
||
373 | |||
374 | return self::getFileContents($path, $callback); |
||
375 | } |
||
376 | |||
377 | /** |
||
378 | * Return the contents of a file from the passed in path |
||
379 | * |
||
380 | * @param string $path |
||
381 | * @param callable $callback |
||
382 | * |
||
383 | * @return null|mixed |
||
384 | */ |
||
385 | protected static function getFileContents(string $path, callable $callback = null) |
||
424 | } |
||
425 | |||
426 | /** |
||
427 | * Combined the passed in paths, whether file system or URL |
||
428 | * |
||
429 | * @param string ...$paths |
||
430 | * |
||
431 | * @return string |
||
432 | */ |
||
433 | protected static function combinePaths(string ...$paths): string |
||
434 | { |
||
435 | $last_key = \count($paths) - 1; |
||
436 | array_walk($paths, function (&$val, $key) use ($last_key) { |
||
437 | switch ($key) { |
||
438 | case 0: |
||
439 | $val = rtrim($val, '/ '); |
||
440 | break; |
||
441 | case $last_key: |
||
442 | $val = ltrim($val, '/ '); |
||
443 | break; |
||
444 | default: |
||
445 | $val = trim($val, '/ '); |
||
446 | break; |
||
447 | } |
||
448 | }); |
||
449 | |||
450 | $first = array_shift($paths); |
||
451 | $last = array_pop($paths); |
||
452 | $paths = array_filter($paths); |
||
453 | array_unshift($paths, $first); |
||
454 | $paths[] = $last; |
||
455 | |||
456 | return implode('/', $paths); |
||
457 | } |
||
458 | |||
459 | /** |
||
460 | * @param string $error |
||
461 | * @param bool $soft |
||
462 | * |
||
463 | * @throws NotFoundHttpException |
||
464 | */ |
||
465 | protected static function reportError(string $error, $soft = false) |
||
472 | } |
||
473 | |||
474 | // Private Static Methods |
||
475 | // ========================================================================= |
||
476 | |||
477 | /** |
||
478 | * @param $string |
||
479 | * |
||
480 | * @return mixed |
||
481 | */ |
||
482 | private static function jsonFileDecode($string) |
||
485 | } |
||
486 | } |
||
487 |