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