Passed
Pull Request — v1 (#26)
by
unknown
07:17
created

Manifest   F

Complexity

Total Complexity 65

Size/Duplication

Total Lines 555
Duplicated Lines 0 %

Importance

Changes 13
Bugs 0 Features 0
Metric Value
eloc 222
c 13
b 0
f 0
dl 0
loc 555
rs 3.2
wmc 65

18 Methods

Rating   Name   Duplication   Size   Complexity  
A getCssModuleTags() 0 15 3
A getCssRelPreloadPolyfill() 0 3 1
A getModuleEntry() 0 24 3
A getSafariNomoduleFix() 0 3 1
A getCriticalCssTags() 0 25 3
B getModule() 0 28 8
A getJsModuleTags() 0 22 5
A getFile() 0 3 1
A getCssInlineTags() 0 10 2
B getManifestFile() 0 33 6
B getFileContents() 0 60 6
A getJsonFile() 0 3 1
A reportError() 0 7 3
B getFileFromUri() 0 27 8
A invalidateCaches() 0 5 1
A jsonFileDecode() 0 9 2
A combinePaths() 0 24 3
B getFileFromManifest() 0 37 8

How to fix   Complexity   

Complex Class

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
2
/**
3
 * Twigpack plugin for Craft CMS 3.x
4
 *
5
 * Twigpack is the conduit between Twig and webpack, with manifest.json &
6
 * webpack-dev-server HMR support
7
 *
8
 * @link      https://nystudio107.com/
9
 * @copyright Copyright (c) 2018 nystudio107
10
 */
11
12
namespace nystudio107\twigpack\helpers;
13
14
use Craft;
15
use craft\helpers\Json as JsonHelper;
16
use craft\helpers\UrlHelper;
17
18
use nystudio107\twigpack\Twigpack;
19
use yii\base\Exception;
20
use yii\caching\TagDependency;
21
use yii\web\NotFoundHttpException;
22
23
/**
24
 * @author    nystudio107
25
 * @package   Twigpack
26
 * @since     1.0.0
27
 */
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
63
    {
64
        $legacyModule = self::getModule($config, $moduleName, 'legacy', true);
65
        if ($legacyModule === null) {
66
            return '';
67
        }
68
        $lines = [];
69
        if ($async) {
70
            $lines[] = "<link rel=\"preload\" href=\"{$legacyModule}\" as=\"style\" onload=\"this.onload=null;this.rel='stylesheet'\" />";
71
            $lines[] = "<noscript><link rel=\"stylesheet\" href=\"{$legacyModule}\"></noscript>";
72
        } else {
73
            $lines[] = "<link rel=\"stylesheet\" href=\"{$legacyModule}\" />";
74
        }
75
76
        return implode("\r\n", $lines);
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
136
    {
137
        return <<<EOT
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)) {
0 ignored issues
show
Bug introduced by
It seems like $module can also be of type true; however, parameter $filename of is_file() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

234
            if (!UrlHelper::isAbsoluteUrl($module) && !is_file(/** @scrutinizer ignore-type */ $module)) {
Loading history...
Bug introduced by
It seems like $module can also be of type true; however, parameter $url of craft\helpers\UrlHelper::isAbsoluteUrl() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

234
            if (!UrlHelper::isAbsoluteUrl(/** @scrutinizer ignore-type */ $module) && !is_file($module)) {
Loading history...
235
                try {
236
                    $module = UrlHelper::siteUrl($module);
0 ignored issues
show
Bug introduced by
It seems like $module can also be of type true; however, parameter $path of craft\helpers\UrlHelper::siteUrl() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

236
                    $module = UrlHelper::siteUrl(/** @scrutinizer ignore-type */ $module);
Loading history...
237
                } catch (Exception $e) {
238
                    Craft::error($e->getMessage(), __METHOD__);
239
                }
240
            }
241
        }
242
243
        return $module;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $module also could return the type true which is incompatible with the documented return type null|string.
Loading history...
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;
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
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
            // Determine whether we should use the devServer for HMR or not
356
            $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
357
            if ($devMode) {
358
                $devServerPrefix = $config['devServer']['publicPath'];
359
                $devServerPath = self::combinePaths(
360
                    $devServerPrefix,
361
                    $path
362
                );
363
                $devServerFile = self::getFileFromUri($devServerPath, null);
364
                if ($devServerFile) {
365
                    return $devServerFile;
366
                }
367
            }
368
            // Otherwise, try not-hot files
369
            $localPrefix = $config['localFiles']['basePath'] . $config['localFiles']['criticalPrefix'];
370
            $localPath = self::combinePaths(
371
                $localPrefix,
372
                $path
373
            );
374
            $alias = Craft::getAlias($localPath, false);
375
            if ($alias && is_string($alias)) {
376
                $localPath = $alias;
377
            }
378
            if (is_file($localPath)) {
379
                return self::getFile($localPath) ?? '';
380
            }
381
        }
382
        return '';
383
    }
384
385
    /**
386
     * Invalidate all of the manifest caches
387
     */
388
    public static function invalidateCaches()
389
    {
390
        $cache = Craft::$app->getCache();
391
        TagDependency::invalidate($cache, self::CACHE_TAG);
392
        Craft::info('All manifest caches cleared', __METHOD__);
393
    }
394
395
    /**
396
     * Return the contents of a JSON file from a URI path
397
     *
398
     * @param string $path
399
     *
400
     * @return null|array
401
     */
402
    protected static function getJsonFile(string $path)
403
    {
404
        return self::getFileFromUri($path, [self::class, 'jsonFileDecode']);
405
    }
406
407
    // Protected Static Methods
408
    // =========================================================================
409
410
    /**
411
     * Return the contents of a file from a URI path
412
     *
413
     * @param string        $path
414
     * @param callable|null $callback
415
     * @param bool          $pathOnly
416
     *
417
     * @return null|mixed
418
     */
419
    protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false)
420
    {
421
        // Resolve any aliases
422
        $alias = Craft::getAlias($path, false);
423
        if ($alias && is_string($alias)) {
424
            $path = $alias;
425
        }
426
        // If we only want the file via path, make sure it exists
427
        if ($pathOnly && !is_file($path)) {
428
            Craft::warning(Craft::t(
429
                'twigpack',
430
                'File does not exist: {path}',
431
                ['path' => $path]
432
            ), __METHOD__);
433
434
            return '';
435
        }
436
        // Make sure it's a full URL
437
        if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) {
438
            try {
439
                $path = UrlHelper::siteUrl($path);
440
            } catch (Exception $e) {
441
                Craft::error($e->getMessage(), __METHOD__);
442
            }
443
        }
444
445
        return self::getFileContents($path, $callback);
446
    }
447
448
    /**
449
     * Return the contents of a file from the passed in path
450
     *
451
     * @param string   $path
452
     * @param callable $callback
453
     *
454
     * @return null|mixed
455
     */
456
    protected static function getFileContents(string $path, callable $callback = null)
457
    {
458
        // Return the memoized manifest if it exists
459
        if (!empty(self::$files[$path])) {
460
            return self::$files[$path];
461
        }
462
        // Create the dependency tags
463
        $dependency = new TagDependency([
464
            'tags' => [
465
                self::CACHE_TAG,
466
                self::CACHE_TAG.$path,
467
            ],
468
        ]);
469
        // Set the cache duration based on devMode
470
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
471
            ? self::DEVMODE_CACHE_DURATION
472
            : null;
473
        // Get the result from the cache, or parse the file
474
        $cache = Craft::$app->getCache();
475
        $settings = Twigpack::$plugin->getSettings();
476
        $cacheKeySuffix = $settings->cacheKeySuffix ?? '';
477
        $file = $cache->getOrSet(
478
            self::CACHE_KEY.$cacheKeySuffix.$path,
479
            function () use ($path, $callback) {
480
                $result = null;
481
                if (UrlHelper::isAbsoluteUrl($path)) {
482
                    /**
483
                     * Silly work-around for what appears to be a file_get_contents bug with https
484
                     * http://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser
485
                     */
486
                    $opts = [
487
                        'ssl' => [
488
                            'verify_peer' => false,
489
                            'verify_peer_name' => false,
490
                        ],
491
                        'http' => [
492
                            'ignore_errors' => true,
493
                            'header' => "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13\r\n",
494
                        ],
495
                    ];
496
                    $context = stream_context_create($opts);
497
                    $contents = @file_get_contents($path, false, $context);
498
                } else {
499
                    $contents = @file_get_contents($path);
500
                }
501
                if ($contents) {
502
                    $result = $contents;
503
                    if ($callback) {
504
                        $result = $callback($result);
505
                    }
506
                }
507
508
                return $result;
509
            },
510
            $cacheDuration,
511
            $dependency
512
        );
513
        self::$files[$path] = $file;
514
515
        return $file;
516
    }
517
518
    /**
519
     * Combined the passed in paths, whether file system or URL
520
     *
521
     * @param string ...$paths
522
     *
523
     * @return string
524
     */
525
    protected static function combinePaths(string ...$paths): string
526
    {
527
        $last_key = count($paths) - 1;
528
        array_walk($paths, function (&$val, $key) use ($last_key) {
529
            switch ($key) {
530
                case 0:
531
                    $val = rtrim($val, '/ ');
532
                    break;
533
                case $last_key:
534
                    $val = ltrim($val, '/ ');
535
                    break;
536
                default:
537
                    $val = trim($val, '/ ');
538
                    break;
539
            }
540
        });
541
542
        $first = array_shift($paths);
543
        $last = array_pop($paths);
544
        $paths = array_filter($paths);
545
        array_unshift($paths, $first);
546
        $paths[] = $last;
547
548
        return implode('/', $paths);
549
    }
550
551
    /**
552
     * @param string $error
553
     * @param bool   $soft
554
     *
555
     * @throws NotFoundHttpException
556
     */
557
    protected static function reportError(string $error, $soft = false)
558
    {
559
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
560
        if ($devMode && !$soft) {
561
            throw new NotFoundHttpException($error);
562
        }
563
        Craft::error($error, __METHOD__);
564
    }
565
566
    // Private Static Methods
567
    // =========================================================================
568
569
    /**
570
     * @param $string
571
     *
572
     * @return null|array
573
     */
574
    private static function jsonFileDecode($string)
575
    {
576
        $json = JsonHelper::decodeIfJson($string);
577
        if (is_string($json)) {
578
            Craft::error('Error decoding JSON file: '.$json, __METHOD__);
579
            $json = null;
580
        }
581
582
        return $json;
583
    }
584
}
585