Passed
Push — develop ( f35ed6...39cf26 )
by Andrew
04:34
created

Manifest::getFileContents()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 58
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
nc 3
nop 2
dl 0
loc 58
rs 8.7377
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 = 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');
156
        if ($legacyModule === null) {
157
            return '';
158
        }
159
        if ($async) {
160
            $modernModule = self::getModule($config, $moduleName, 'modern');
161
            if ($modernModule === null) {
162
                return '';
163
            }
164
        }
165
        $lines = [];
166
        if ($async) {
167
            $lines[] = "<script type=\"module\" src=\"{$modernModule}\"></script>";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $modernModule does not seem to be defined for all execution paths leading up to this point.
Loading history...
168
            $lines[] = "<script nomodule src=\"{$legacyModule}\"></script>";
169
        } else {
170
            $lines[] = "<script src=\"{$legacyModule}\"></script>";
171
        }
172
173
        return implode("\r\n", $lines);
174
    }
175
176
    /**
177
     * Safari 10.1 supports modules, but does not support the `nomodule`
178
     * attribute - it will load <script nomodule> anyway. This snippet solve
179
     * this problem, but only for script tags that load external code, e.g.:
180
     * <script nomodule src="nomodule.js"></script>
181
     *
182
     * Again: this will **not* # prevent inline script, e.g.:
183
     * <script nomodule>alert('no modules');</script>.
184
     *
185
     * This workaround is possible because Safari supports the non-standard
186
     * 'beforeload' event. This allows us to trap the module and nomodule load.
187
     *
188
     * Note also that `nomodule` is supported in later versions of Safari -
189
     * it's just 10.1 that omits this attribute.
190
     *
191
     * c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
192
     *
193
     * @return string
194
     */
195
    public static function getSafariNomoduleFix(): string
196
    {
197
        return <<<EOT
198
<script>
199
!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()}}();
200
</script>
201
EOT;
202
    }
203
204
    /**
205
     * Return the URI to a module
206
     *
207
     * @param array  $config
208
     * @param string $moduleName
209
     * @param string $type
210
     * @param bool   $soft
211
     *
212
     * @return null|string
213
     * @throws NotFoundHttpException
214
     */
215
    public static function getModule(array $config, string $moduleName, string $type = 'modern', bool $soft = false)
216
    {
217
        // Get the module entry
218
        $module = self::getModuleEntry($config, $moduleName, $type, $soft);
219
        if ($module !== null) {
220
            $prefix = self::$isHot
221
                ? $config['devServer']['publicPath']
222
                : $config['server']['publicPath'];
223
            // If the module isn't a full URL, prefix it
224
            if (!UrlHelper::isAbsoluteUrl($module)) {
225
                $module = self::combinePaths($prefix, $module);
226
            }
227
            // Resolve any aliases
228
            $alias = Craft::getAlias($module, false);
229
            if ($alias) {
230
                $module = $alias;
231
            }
232
            // Make sure it's a full URL
233
            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 $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

233
            if (!UrlHelper::isAbsoluteUrl(/** @scrutinizer ignore-type */ $module) && !is_file($module)) {
Loading history...
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

233
            if (!UrlHelper::isAbsoluteUrl($module) && !is_file(/** @scrutinizer ignore-type */ $module)) {
Loading history...
234
                try {
235
                    $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

235
                    $module = UrlHelper::siteUrl(/** @scrutinizer ignore-type */ $module);
Loading history...
236
                } catch (Exception $e) {
237
                    Craft::error($e->getMessage(), __METHOD__);
238
                }
239
            }
240
        }
241
242
        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...
243
    }
244
245
    /**
246
     * Return a module's raw entry from the manifest
247
     *
248
     * @param array  $config
249
     * @param string $moduleName
250
     * @param string $type
251
     * @param bool   $soft
252
     *
253
     * @return null|string
254
     * @throws NotFoundHttpException
255
     */
256
    public static function getModuleEntry(array $config, string $moduleName, string $type = 'modern', bool $soft = false)
257
    {
258
        $module = null;
259
        // Get the manifest file
260
        $manifest = self::getManifestFile($config, $type);
261
        if ($manifest !== null) {
262
            // Make sure it exists in the manifest
263
            if (empty($manifest[$moduleName])) {
264
                self::reportError(Craft::t(
265
                    'twigpack',
266
                    'Module does not exist in the manifest: {moduleName}',
267
                    ['moduleName' => $moduleName]
268
                ), $soft);
269
270
                return null;
271
            }
272
            $module = $manifest[$moduleName];
273
        }
274
275
        return $module;
276
    }
277
278
    /**
279
     * Return a JSON-decoded manifest file
280
     *
281
     * @param array  $config
282
     * @param string $type
283
     *
284
     * @return null|array
285
     * @throws NotFoundHttpException
286
     */
287
    public static function getManifestFile(array $config, string $type = 'modern')
288
    {
289
        $manifest = null;
290
        // Determine whether we should use the devServer for HMR or not
291
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
292
        self::$isHot = ($devMode && $config['useDevServer']);
293
        // Try to get the manifest
294
        while ($manifest === null) {
295
            $manifestPath = self::$isHot
296
                ? $config['devServer']['manifestPath']
297
                : $config['server']['manifestPath'];
298
            // Normalize the path
299
            $path = self::combinePaths($manifestPath, $config['manifest'][$type]);
300
            $manifest = self::getJsonFile($path);
301
            // If the manifest isn't found, and it was hot, fall back on non-hot
302
            if ($manifest === null) {
303
                // We couldn't find a manifest; throw an error
304
                self::reportError(Craft::t(
305
                    'twigpack',
306
                    'Manifest file not found at: {manifestPath}',
307
                    ['manifestPath' => $manifestPath]
308
                ), true);
309
                if (self::$isHot) {
310
                    // Try again, but not with home module replacement
311
                    self::$isHot = false;
312
                } else {
313
                    // Give up and return null
314
                    return null;
315
                }
316
            }
317
        }
318
319
        return $manifest;
320
    }
321
322
    /**
323
     * Returns the contents of a file from a URI path
324
     *
325
     * @param string $path
326
     *
327
     * @return string
328
     */
329
    public static function getFile(string $path): string
330
    {
331
        return self::getFileFromUri($path, null) ?? '';
332
    }
333
334
    /**
335
     * @param array  $config
336
     * @param string $fileName
337
     * @param string $type
338
     *
339
     * @return string
340
     */
341
    public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string
342
    {
343
        try {
344
            $path = self::getModuleEntry($config, $fileName, $type, true);
345
        } catch (NotFoundHttpException $e) {
346
            Craft::error($e->getMessage(), __METHOD__);
347
        }
348
        if ($path !== null) {
349
            $path = self::combinePaths(
350
                $config['localFiles']['basePath'],
351
                $path
352
            );
353
354
            return self::getFileFromUri($path, null) ?? '';
355
        }
356
357
        return '';
358
    }
359
360
    /**
361
     * Invalidate all of the manifest caches
362
     */
363
    public static function invalidateCaches()
364
    {
365
        $cache = Craft::$app->getCache();
366
        TagDependency::invalidate($cache, self::CACHE_TAG);
367
        Craft::info('All manifest caches cleared', __METHOD__);
368
    }
369
370
    /**
371
     * Return the contents of a JSON file from a URI path
372
     *
373
     * @param string $path
374
     *
375
     * @return null|array
376
     */
377
    protected static function getJsonFile(string $path)
378
    {
379
        return self::getFileFromUri($path, [self::class, 'jsonFileDecode']);
380
    }
381
382
    // Protected Static Methods
383
    // =========================================================================
384
385
    /**
386
     * Return the contents of a file from a URI path
387
     *
388
     * @param string        $path
389
     * @param callable|null $callback
390
     *
391
     * @return null|mixed
392
     */
393
    protected static function getFileFromUri(string $path, callable $callback = null)
394
    {
395
        // Resolve any aliases
396
        $alias = Craft::getAlias($path, false);
397
        if ($alias) {
398
            $path = $alias;
399
        }
400
        // Make sure it's a full URL
401
        if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) {
0 ignored issues
show
Bug introduced by
It seems like $path 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

401
        if (!UrlHelper::isAbsoluteUrl($path) && !is_file(/** @scrutinizer ignore-type */ $path)) {
Loading history...
Bug introduced by
It seems like $path 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

401
        if (!UrlHelper::isAbsoluteUrl(/** @scrutinizer ignore-type */ $path) && !is_file($path)) {
Loading history...
402
            try {
403
                $path = UrlHelper::siteUrl($path);
0 ignored issues
show
Bug introduced by
It seems like $path 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

403
                $path = UrlHelper::siteUrl(/** @scrutinizer ignore-type */ $path);
Loading history...
404
            } catch (Exception $e) {
405
                Craft::error($e->getMessage(), __METHOD__);
406
            }
407
        }
408
409
        return self::getFileContents($path, $callback);
0 ignored issues
show
Bug introduced by
It seems like $path can also be of type true; however, parameter $path of nystudio107\twigpack\hel...fest::getFileContents() 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

409
        return self::getFileContents(/** @scrutinizer ignore-type */ $path, $callback);
Loading history...
410
    }
411
412
    /**
413
     * Return the contents of a file from the passed in path
414
     *
415
     * @param string   $path
416
     * @param callable $callback
417
     *
418
     * @return null|mixed
419
     */
420
    protected static function getFileContents(string $path, callable $callback = null)
421
    {
422
        // Return the memoized manifest if it exists
423
        if (!empty(self::$files[$path])) {
424
            return self::$files[$path];
425
        }
426
        // Create the dependency tags
427
        $dependency = new TagDependency([
428
            'tags' => [
429
                self::CACHE_TAG,
430
                self::CACHE_TAG.$path,
431
            ],
432
        ]);
433
        // Set the cache duration based on devMode
434
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
435
            ? self::DEVMODE_CACHE_DURATION
436
            : null;
437
        // Get the result from the cache, or parse the file
438
        $cache = Craft::$app->getCache();
439
        $file = $cache->getOrSet(
440
            self::CACHE_KEY.$path,
441
            function () use ($path, $callback) {
442
                $result = null;
443
                if (UrlHelper::isAbsoluteUrl($path)) {
444
                    /**
445
                     * Silly work-around for what appears to be a file_get_contents bug with https
446
                     * http://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser
447
                     */
448
                    $opts = [
449
                        'ssl' => [
450
                            'verify_peer' => false,
451
                            'verify_peer_name' => false,
452
                        ],
453
                        'http' => [
454
                            'ignore_errors' => true,
455
                            '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",
456
                        ],
457
                    ];
458
                    $context = stream_context_create($opts);
459
                    $contents = @file_get_contents($path, false, $context);
460
                } else {
461
                    $contents = @file_get_contents($path);
462
                }
463
                if ($contents) {
464
                    $result = $contents;
465
                    if ($callback) {
466
                        $result = $callback($result);
467
                    }
468
                }
469
470
                return $result;
471
            },
472
            $cacheDuration,
473
            $dependency
474
        );
475
        self::$files[$path] = $file;
476
477
        return $file;
478
    }
479
480
    /**
481
     * Combined the passed in paths, whether file system or URL
482
     *
483
     * @param string ...$paths
484
     *
485
     * @return string
486
     */
487
    protected static function combinePaths(string ...$paths): string
488
    {
489
        $last_key = \count($paths) - 1;
490
        array_walk($paths, function (&$val, $key) use ($last_key) {
491
            switch ($key) {
492
                case 0:
493
                    $val = rtrim($val, '/ ');
494
                    break;
495
                case $last_key:
496
                    $val = ltrim($val, '/ ');
497
                    break;
498
                default:
499
                    $val = trim($val, '/ ');
500
                    break;
501
            }
502
        });
503
504
        $first = array_shift($paths);
505
        $last = array_pop($paths);
506
        $paths = array_filter($paths);
507
        array_unshift($paths, $first);
508
        $paths[] = $last;
509
510
        return implode('/', $paths);
511
    }
512
513
    /**
514
     * @param string $error
515
     * @param bool   $soft
516
     *
517
     * @throws NotFoundHttpException
518
     */
519
    protected static function reportError(string $error, $soft = false)
520
    {
521
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
522
        if ($devMode && !$soft) {
523
            throw new NotFoundHttpException($error);
524
        }
525
        Craft::error($error, __METHOD__);
526
    }
527
528
    // Private Static Methods
529
    // =========================================================================
530
531
    /**
532
     * @param $string
533
     *
534
     * @return mixed
535
     */
536
    private static function jsonFileDecode($string)
537
    {
538
        return JsonHelper::decodeIfJson($string);
539
    }
540
}
541