Passed
Pull Request — v1 (#27)
by
unknown
07:20
created

Manifest::getFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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 the HASH value from to module
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 getModuleHash(array $config, string $moduleName, string $type = 'modern', bool $soft = false)
258
	{
259
260
		try {
261
			// Get the module entry
262
			$module = self::getModuleEntry($config, $moduleName, $type, $soft);
263
			if ($module !== null) {
264
				$prefix = self::$isHot
0 ignored issues
show
Unused Code introduced by
The assignment to $prefix is dead and can be removed.
Loading history...
265
					? $config['devServer']['publicPath']
266
					: $config['server']['publicPath'];
267
				// Extract only the Hash Value
268
				$modulePath = pathinfo($module);
269
				$moduleFilename = $modulePath['filename'];
270
				$moduleHash = substr($moduleFilename, strpos($moduleFilename, ".") + 1);
271
			}
272
		} catch (Exception $e) {
273
			// return emtpt string if no module is found
274
			return '';
275
		}
276
277
		return $moduleHash;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $moduleHash does not seem to be defined for all execution paths leading up to this point.
Loading history...
278
	}
279
280
    /**
281
     * Return a module's raw entry from the manifest
282
     *
283
     * @param array  $config
284
     * @param string $moduleName
285
     * @param string $type
286
     * @param bool   $soft
287
     *
288
     * @return null|string
289
     * @throws NotFoundHttpException
290
     */
291
    public static function getModuleEntry(
292
        array $config,
293
        string $moduleName,
294
        string $type = 'modern',
295
        bool $soft = false
296
    ) {
297
        $module = null;
298
        // Get the manifest file
299
        $manifest = self::getManifestFile($config, $type);
300
        if ($manifest !== null) {
301
            // Make sure it exists in the manifest
302
            if (empty($manifest[$moduleName])) {
303
                self::reportError(Craft::t(
304
                    'twigpack',
305
                    'Module does not exist in the manifest: {moduleName}',
306
                    ['moduleName' => $moduleName]
307
                ), $soft);
308
309
                return null;
310
            }
311
            $module = $manifest[$moduleName];
312
        }
313
314
        return $module;
315
    }
316
317
    /**
318
     * Return a JSON-decoded manifest file
319
     *
320
     * @param array  $config
321
     * @param string $type
322
     *
323
     * @return null|array
324
     * @throws NotFoundHttpException
325
     */
326
    public static function getManifestFile(array $config, string $type = 'modern')
327
    {
328
        $manifest = null;
329
        // Determine whether we should use the devServer for HMR or not
330
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
331
        self::$isHot = ($devMode && $config['useDevServer']);
332
        // Try to get the manifest
333
        while ($manifest === null) {
334
            $manifestPath = self::$isHot
335
                ? $config['devServer']['manifestPath']
336
                : $config['server']['manifestPath'];
337
            // Normalize the path
338
            $path = self::combinePaths($manifestPath, $config['manifest'][$type]);
339
            $manifest = self::getJsonFile($path);
340
            // If the manifest isn't found, and it was hot, fall back on non-hot
341
            if ($manifest === null) {
342
                // We couldn't find a manifest; throw an error
343
                self::reportError(Craft::t(
344
                    'twigpack',
345
                    'Manifest file not found at: {manifestPath}',
346
                    ['manifestPath' => $manifestPath]
347
                ), true);
348
                if (self::$isHot) {
349
                    // Try again, but not with home module replacement
350
                    self::$isHot = false;
351
                } else {
352
                    // Give up and return null
353
                    return null;
354
                }
355
            }
356
        }
357
358
        return $manifest;
359
    }
360
361
    /**
362
     * Returns the contents of a file from a URI path
363
     *
364
     * @param string $path
365
     *
366
     * @return string
367
     */
368
    public static function getFile(string $path): string
369
    {
370
        return self::getFileFromUri($path, null, true) ?? '';
371
    }
372
373
    /**
374
     * @param array  $config
375
     * @param string $fileName
376
     * @param string $type
377
     *
378
     * @return string
379
     */
380
    public static function getFileFromManifest(array $config, string $fileName, string $type = 'legacy'): string
381
    {
382
        $path = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
383
        try {
384
            $path = self::getModuleEntry($config, $fileName, $type, true);
385
        } catch (NotFoundHttpException $e) {
386
            Craft::error($e->getMessage(), __METHOD__);
387
        }
388
        if ($path !== null) {
389
            $path = self::combinePaths(
390
                $config['localFiles']['basePath'],
391
                $path
392
            );
393
394
            return self::getFileFromUri($path, null) ?? '';
395
        }
396
397
        return '';
398
    }
399
400
    /**
401
     * Invalidate all of the manifest caches
402
     */
403
    public static function invalidateCaches()
404
    {
405
        $cache = Craft::$app->getCache();
406
        TagDependency::invalidate($cache, self::CACHE_TAG);
407
        Craft::info('All manifest caches cleared', __METHOD__);
408
    }
409
410
    /**
411
     * Return the contents of a JSON file from a URI path
412
     *
413
     * @param string $path
414
     *
415
     * @return null|array
416
     */
417
    protected static function getJsonFile(string $path)
418
    {
419
        return self::getFileFromUri($path, [self::class, 'jsonFileDecode']);
420
    }
421
422
    // Protected Static Methods
423
    // =========================================================================
424
425
    /**
426
     * Return the contents of a file from a URI path
427
     *
428
     * @param string        $path
429
     * @param callable|null $callback
430
     * @param bool          $pathOnly
431
     *
432
     * @return null|mixed
433
     */
434
    protected static function getFileFromUri(string $path, callable $callback = null, bool $pathOnly = false)
435
    {
436
        // Resolve any aliases
437
        $alias = Craft::getAlias($path, false);
438
        if ($alias && is_string($alias)) {
439
            $path = $alias;
440
        }
441
        // If we only want the file via path, make sure it exists
442
        if ($pathOnly && !is_file($path)) {
443
            Craft::warning(Craft::t(
444
                'twigpack',
445
                'File does not exist: {path}',
446
                ['path' => $path]
447
            ), __METHOD__);
448
449
            return '';
450
        }
451
        // Make sure it's a full URL
452
        if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) {
453
            try {
454
                $path = UrlHelper::siteUrl($path);
455
            } catch (Exception $e) {
456
                Craft::error($e->getMessage(), __METHOD__);
457
            }
458
        }
459
460
        return self::getFileContents($path, $callback);
461
    }
462
463
    /**
464
     * Return the contents of a file from the passed in path
465
     *
466
     * @param string   $path
467
     * @param callable $callback
468
     *
469
     * @return null|mixed
470
     */
471
    protected static function getFileContents(string $path, callable $callback = null)
472
    {
473
        // Return the memoized manifest if it exists
474
        if (!empty(self::$files[$path])) {
475
            return self::$files[$path];
476
        }
477
        // Create the dependency tags
478
        $dependency = new TagDependency([
479
            'tags' => [
480
                self::CACHE_TAG,
481
                self::CACHE_TAG.$path,
482
            ],
483
        ]);
484
        // Set the cache duration based on devMode
485
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
486
            ? self::DEVMODE_CACHE_DURATION
487
            : null;
488
        // Get the result from the cache, or parse the file
489
        $cache = Craft::$app->getCache();
490
        $settings = Twigpack::$plugin->getSettings();
491
        $cacheKeySuffix = $settings->cacheKeySuffix ?? '';
492
        $file = $cache->getOrSet(
493
            self::CACHE_KEY.$cacheKeySuffix.$path,
494
            function () use ($path, $callback) {
495
                $result = null;
496
                if (UrlHelper::isAbsoluteUrl($path)) {
497
                    /**
498
                     * Silly work-around for what appears to be a file_get_contents bug with https
499
                     * http://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser
500
                     */
501
                    $opts = [
502
                        'ssl' => [
503
                            'verify_peer' => false,
504
                            'verify_peer_name' => false,
505
                        ],
506
                        'http' => [
507
                            'ignore_errors' => true,
508
                            '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",
509
                        ],
510
                    ];
511
                    $context = stream_context_create($opts);
512
                    $contents = @file_get_contents($path, false, $context);
513
                } else {
514
                    $contents = @file_get_contents($path);
515
                }
516
                if ($contents) {
517
                    $result = $contents;
518
                    if ($callback) {
519
                        $result = $callback($result);
520
                    }
521
                }
522
523
                return $result;
524
            },
525
            $cacheDuration,
526
            $dependency
527
        );
528
        self::$files[$path] = $file;
529
530
        return $file;
531
    }
532
533
    /**
534
     * Combined the passed in paths, whether file system or URL
535
     *
536
     * @param string ...$paths
537
     *
538
     * @return string
539
     */
540
    protected static function combinePaths(string ...$paths): string
541
    {
542
        $last_key = count($paths) - 1;
543
        array_walk($paths, function (&$val, $key) use ($last_key) {
544
            switch ($key) {
545
                case 0:
546
                    $val = rtrim($val, '/ ');
547
                    break;
548
                case $last_key:
549
                    $val = ltrim($val, '/ ');
550
                    break;
551
                default:
552
                    $val = trim($val, '/ ');
553
                    break;
554
            }
555
        });
556
557
        $first = array_shift($paths);
558
        $last = array_pop($paths);
559
        $paths = array_filter($paths);
560
        array_unshift($paths, $first);
561
        $paths[] = $last;
562
563
        return implode('/', $paths);
564
    }
565
566
    /**
567
     * @param string $error
568
     * @param bool   $soft
569
     *
570
     * @throws NotFoundHttpException
571
     */
572
    protected static function reportError(string $error, $soft = false)
573
    {
574
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
575
        if ($devMode && !$soft) {
576
            throw new NotFoundHttpException($error);
577
        }
578
        Craft::error($error, __METHOD__);
579
    }
580
581
    // Private Static Methods
582
    // =========================================================================
583
584
    /**
585
     * @param $string
586
     *
587
     * @return null|array
588
     */
589
    private static function jsonFileDecode($string)
590
    {
591
        $json = JsonHelper::decodeIfJson($string);
592
        if (is_string($json)) {
593
            Craft::error('Error decoding JSON file: '.$json, __METHOD__);
594
            $json = null;
595
        }
596
597
        return $json;
598
    }
599
}
600