Passed
Push — develop ( 41c9fa...602f70 )
by Andrew
03:08
created

Manifest::getJsonFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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', true);
156
        if ($legacyModule === null) {
157
            return '';
158
        }
159
        if ($async) {
160
            $modernModule = self::getModule($config, $moduleName, 'modern', true);
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 $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...
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...
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, true) ?? '';
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
     * @param bool          $pathOnly
391
     *
392
     * @return null|mixed
393
     */
394
    protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false)
395
    {
396
        // Resolve any aliases
397
        $alias = Craft::getAlias($path, false);
398
        if ($alias) {
399
            $path = $alias;
400
        }
401
        // If we only want the file via path, make sure it exists
402
        if ($pathOnly && !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

402
        if ($pathOnly && !is_file(/** @scrutinizer ignore-type */ $path)) {
Loading history...
403
            Craft::warning(Craft::t(
404
                'twigpack',
405
                'File does not exist: {path}',
406
                ['path' => $path]
407
            ), __METHOD__);
408
409
            return '';
410
        }
411
        // Make sure it's a full URL
412
        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 $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

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

414
                $path = UrlHelper::siteUrl(/** @scrutinizer ignore-type */ $path);
Loading history...
415
            } catch (Exception $e) {
416
                Craft::error($e->getMessage(), __METHOD__);
417
            }
418
        }
419
420
        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

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