Passed
Push — develop ( 6d5f6c...4cd50a )
by Andrew
03:37
created

Manifest::getFileFromManifest()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 4
nop 3
dl 0
loc 18
rs 9.9
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 = (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
            $path = self::combinePaths(
356
                $config['localFiles']['basePath'],
357
                $path
358
            );
359
360
            return self::getFileFromUri($path, null) ?? '';
361
        }
362
363
        return '';
364
    }
365
366
    /**
367
     * Invalidate all of the manifest caches
368
     */
369
    public static function invalidateCaches()
370
    {
371
        $cache = Craft::$app->getCache();
372
        TagDependency::invalidate($cache, self::CACHE_TAG);
373
        Craft::info('All manifest caches cleared', __METHOD__);
374
    }
375
376
    /**
377
     * Return the contents of a JSON file from a URI path
378
     *
379
     * @param string $path
380
     *
381
     * @return null|array
382
     */
383
    protected static function getJsonFile(string $path)
384
    {
385
        return self::getFileFromUri($path, [self::class, 'jsonFileDecode']);
386
    }
387
388
    // Protected Static Methods
389
    // =========================================================================
390
391
    /**
392
     * Return the contents of a file from a URI path
393
     *
394
     * @param string        $path
395
     * @param callable|null $callback
396
     * @param bool          $pathOnly
397
     *
398
     * @return null|mixed
399
     */
400
    protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false)
401
    {
402
        // Resolve any aliases
403
        $alias = Craft::getAlias($path, false);
404
        if ($alias && is_string($alias)) {
405
            $path = $alias;
406
        }
407
        // If we only want the file via path, make sure it exists
408
        if ($pathOnly && !is_file($path)) {
409
            Craft::warning(Craft::t(
410
                'twigpack',
411
                'File does not exist: {path}',
412
                ['path' => $path]
413
            ), __METHOD__);
414
415
            return '';
416
        }
417
        // Make sure it's a full URL
418
        if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) {
419
            try {
420
                $path = UrlHelper::siteUrl($path);
421
            } catch (Exception $e) {
422
                Craft::error($e->getMessage(), __METHOD__);
423
            }
424
        }
425
426
        return self::getFileContents($path, $callback);
427
    }
428
429
    /**
430
     * Return the contents of a file from the passed in path
431
     *
432
     * @param string   $path
433
     * @param callable $callback
434
     *
435
     * @return null|mixed
436
     */
437
    protected static function getFileContents(string $path, callable $callback = null)
438
    {
439
        // Return the memoized manifest if it exists
440
        if (!empty(self::$files[$path])) {
441
            return self::$files[$path];
442
        }
443
        // Create the dependency tags
444
        $dependency = new TagDependency([
445
            'tags' => [
446
                self::CACHE_TAG,
447
                self::CACHE_TAG.$path,
448
            ],
449
        ]);
450
        // Set the cache duration based on devMode
451
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
452
            ? self::DEVMODE_CACHE_DURATION
453
            : null;
454
        // Get the result from the cache, or parse the file
455
        $cache = Craft::$app->getCache();
456
        $file = $cache->getOrSet(
457
            self::CACHE_KEY.$path,
458
            function () use ($path, $callback) {
459
                $result = null;
460
                if (UrlHelper::isAbsoluteUrl($path)) {
461
                    /**
462
                     * Silly work-around for what appears to be a file_get_contents bug with https
463
                     * http://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser
464
                     */
465
                    $opts = [
466
                        'ssl' => [
467
                            'verify_peer' => false,
468
                            'verify_peer_name' => false,
469
                        ],
470
                        'http' => [
471
                            'ignore_errors' => true,
472
                            '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",
473
                        ],
474
                    ];
475
                    $context = stream_context_create($opts);
476
                    $contents = @file_get_contents($path, false, $context);
477
                } else {
478
                    $contents = @file_get_contents($path);
479
                }
480
                if ($contents) {
481
                    $result = $contents;
482
                    if ($callback) {
483
                        $result = $callback($result);
484
                    }
485
                }
486
487
                return $result;
488
            },
489
            $cacheDuration,
490
            $dependency
491
        );
492
        self::$files[$path] = $file;
493
494
        return $file;
495
    }
496
497
    /**
498
     * Combined the passed in paths, whether file system or URL
499
     *
500
     * @param string ...$paths
501
     *
502
     * @return string
503
     */
504
    protected static function combinePaths(string ...$paths): string
505
    {
506
        $last_key = count($paths) - 1;
507
        array_walk($paths, function (&$val, $key) use ($last_key) {
508
            switch ($key) {
509
                case 0:
510
                    $val = rtrim($val, '/ ');
511
                    break;
512
                case $last_key:
513
                    $val = ltrim($val, '/ ');
514
                    break;
515
                default:
516
                    $val = trim($val, '/ ');
517
                    break;
518
            }
519
        });
520
521
        $first = array_shift($paths);
522
        $last = array_pop($paths);
523
        $paths = array_filter($paths);
524
        array_unshift($paths, $first);
525
        $paths[] = $last;
526
527
        return implode('/', $paths);
528
    }
529
530
    /**
531
     * @param string $error
532
     * @param bool   $soft
533
     *
534
     * @throws NotFoundHttpException
535
     */
536
    protected static function reportError(string $error, $soft = false)
537
    {
538
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
539
        if ($devMode && !$soft) {
540
            throw new NotFoundHttpException($error);
541
        }
542
        Craft::error($error, __METHOD__);
543
    }
544
545
    // Private Static Methods
546
    // =========================================================================
547
548
    /**
549
     * @param $string
550
     *
551
     * @return null|array
552
     */
553
    private static function jsonFileDecode($string)
554
    {
555
        $json = JsonHelper::decodeIfJson($string);
556
        if (is_string($json)) {
557
            Craft::error('Error decoding JSON file: '.$json, __METHOD__);
558
            $json = null;
559
        }
560
561
        return $json;
562
    }
563
}
564