Passed
Push — develop ( a9db52...9d2a29 )
by Andrew
05:41
created

Manifest::getFile()   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 yii\base\Exception;
19
use yii\caching\TagDependency;
20
use yii\web\NotFoundHttpException;
21
22
/**
23
 * @author    nystudio107
24
 * @package   Twigpack
25
 * @since     1.0.0
26
 */
27
class Manifest
28
{
29
    // Constants
30
    // =========================================================================
31
32
    const CACHE_KEY = 'twigpack';
33
    const CACHE_TAG = 'twigpack';
34
35
    const DEVMODE_CACHE_DURATION = 1;
36
37
    // Protected Static Properties
38
    // =========================================================================
39
40
    /**
41
     * @var array
42
     */
43
    protected static $files;
44
45
    // Public Static Methods
46
    // =========================================================================
47
48
    /**
49
     * @param array  $config
50
     * @param string $moduleName
51
     * @param bool   $async
52
     *
53
     * @return null|string
54
     * @throws NotFoundHttpException
55
     */
56
    public static function getCssModuleTags(array $config, string $moduleName, bool $async)
57
    {
58
        $legacyModule = self::getModule($config, $moduleName, 'legacy', true);
59
        if ($legacyModule === null) {
60
            return '';
61
        }
62
        $lines = [];
63
        if ($async) {
64
            $lines[] = "<link rel=\"preload\" href=\"{$legacyModule}\" as=\"style\" onload=\"this.onload=null;this.rel='stylesheet'\" />";
65
            $lines[] = "<noscript><link rel=\"stylesheet\" href=\"{$legacyModule}\"></noscript>";
66
        } else {
67
            $lines[] = "<link rel=\"stylesheet\" href=\"{$legacyModule}\" />";
68
        }
69
70
        return implode("\r\n", $lines);
71
    }
72
73
    /**
74
     * Returns the uglified loadCSS rel=preload Polyfill as per:
75
     * https://github.com/filamentgroup/loadCSS#how-to-use-loadcss-recommended-example
76
     *
77
     * @return string
78
     */
79
    public static function getCssRelPreloadPolyfill(): string
80
    {
81
        return <<<EOT
82
<script>
83
/*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
84
!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);
85
</script>
86
EOT;
87
    }
88
89
    /**
90
     * @param array  $config
91
     * @param string $moduleName
92
     * @param bool   $async
93
     *
94
     * @return null|string
95
     * @throws NotFoundHttpException
96
     */
97
    public static function getJsModuleTags(array $config, string $moduleName, bool $async)
98
    {
99
        $legacyModule = self::getModule($config, $moduleName, 'legacy');
100
        if ($legacyModule === null) {
101
            return '';
102
        }
103
        if ($async) {
104
            $modernModule = self::getModule($config, $moduleName, 'modern');
105
            if ($modernModule === null) {
106
                return '';
107
            }
108
        }
109
        $lines = [];
110
        if ($async) {
111
            $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...
112
            $lines[] = "<script nomodule src=\"{$legacyModule}\"></script>";
113
        } else {
114
            $lines[] = "<script src=\"{$legacyModule}\"></script>";
115
        }
116
117
        return implode("\r\n", $lines);
118
    }
119
120
    /**
121
     * Safari 10.1 supports modules, but does not support the `nomodule`
122
     * attribute - it will load <script nomodule> anyway. This snippet solve
123
     * this problem, but only for script tags that load external code, e.g.:
124
     * <script nomodule src="nomodule.js"></script>
125
     *
126
     * Again: this will **not* # prevent inline script, e.g.:
127
     * <script nomodule>alert('no modules');</script>.
128
     *
129
     * This workaround is possible because Safari supports the non-standard
130
     * 'beforeload' event. This allows us to trap the module and nomodule load.
131
     *
132
     * Note also that `nomodule` is supported in later versions of Safari -
133
     * it's just 10.1 that omits this attribute.
134
     *
135
     * c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
136
     *
137
     * @return string
138
     */
139
    public static function getSafariNomoduleFix(): string
140
    {
141
        return <<<EOT
142
<script>
143
!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()}}();
144
</script>
145
EOT;
146
    }
147
148
    /**
149
     * Return the URI to a module
150
     *
151
     * @param array  $config
152
     * @param string $moduleName
153
     * @param string $type
154
     * @param bool   $soft
155
     *
156
     * @return null|string
157
     * @throws NotFoundHttpException
158
     */
159
    public static function getModule(array $config, string $moduleName, string $type = 'modern', bool $soft = false)
160
    {
161
        $module = null;
162
        // Determine whether we should use the devServer for HMR or not
163
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
164
        $isHot = ($devMode && $config['useDevServer']);
165
        // Get the manifest file
166
        $manifest = self::getManifestFile($config, $isHot, $type);
167
        if ($manifest !== null) {
168
            // Make sure it exists in the manifest
169
            if (empty($manifest[$moduleName])) {
170
                self::reportError(Craft::t(
171
                    'twigpack',
172
                    'Module does not exist in the manifest: {moduleName}',
173
                    ['moduleName' => $moduleName]
174
                ), $soft);
175
176
                return null;
177
            }
178
            $module = $manifest[$moduleName];
179
            $prefix = $isHot
180
                ? $config['devServer']['publicPath']
181
                : $config['server']['publicPath'];
182
            // If the module isn't a full URL, prefix it
183
            if (!UrlHelper::isAbsoluteUrl($module)) {
184
                $module = self::combinePaths($prefix, $module);
185
            }
186
            // Make sure it's a full URL
187
            if (!UrlHelper::isAbsoluteUrl($module)) {
188
                try {
189
                    $module = UrlHelper::siteUrl($module);
190
                } catch (Exception $e) {
191
                    Craft::error($e->getMessage(), __METHOD__);
192
                }
193
            }
194
        }
195
196
        return $module;
197
    }
198
199
    /**
200
     * Return a JSON-decoded manifest file
201
     *
202
     * @param array  $config
203
     * @param bool   $isHot
204
     * @param string $type
205
     *
206
     * @return null|array
207
     * @throws NotFoundHttpException
208
     */
209
    public static function getManifestFile(array $config, bool &$isHot, string $type = 'modern')
210
    {
211
        $manifest = null;
212
        // Try to get the manifest
213
        while ($manifest === null) {
214
            $manifestPath = $isHot
215
                ? $config['devServer']['manifestPath']
216
                : $config['server']['manifestPath'];
217
            // Normalize the path
218
            $path = self::combinePaths($manifestPath, $config['manifest'][$type]);
219
            $manifest = self::getJsonFileFromUri($path);
220
            // If the manifest isn't found, and it was hot, fall back on non-hot
221
            if ($manifest === null) {
222
                // We couldn't find a manifest; throw an error
223
                self::reportError(Craft::t(
224
                    'twigpack',
225
                    'Manifest file not found at: {manifestPath}',
226
                    ['manifestPath' => $manifestPath]
227
                ), true);
228
                if ($isHot) {
229
                    // Try again, but not with home module replacement
230
                    $isHot = false;
231
                } else {
232
                    // Give up and return null
233
                    return null;
234
                }
235
            }
236
        }
237
238
        return $manifest;
239
    }
240
241
    /**
242
     * Returns the contents of a file from a URI path
243
     *
244
     * @param string $path
245
     *
246
     * @return mixed
247
     */
248
    public static function getFile($path)
249
    {
250
        return self::getFileFromUri($path, null);
251
    }
252
253
    /**
254
     * Invalidate all of the manifest caches
255
     */
256
    public static function invalidateCaches()
257
    {
258
        $cache = Craft::$app->getCache();
259
        TagDependency::invalidate($cache, self::CACHE_TAG);
260
        Craft::info('All manifest caches cleared', __METHOD__);
261
    }
262
263
    // Protected Static Methods
264
    // =========================================================================
265
266
    /**
267
     * Return the contents of a JSON file from a URI path
268
     *
269
     * @param string $path
270
     *
271
     * @return mixed
272
     */
273
    protected static function getJsonFileFromUri(string $path)
274
    {
275
        return self::getFileFromUri($path, [self::class, 'jsonFileDecode']);
276
    }
277
278
    /**
279
     * Return the contents of a file from a URI path
280
     *
281
     * @param string        $path
282
     * @param callable|null $callback
283
     *
284
     * @return mixed
285
     */
286
    protected static function getFileFromUri(string $path, callable $callback = null)
287
    {
288
        // Make sure it's a full URL
289
        if (!UrlHelper::isAbsoluteUrl($path) && !is_file($path)) {
290
            try {
291
                $path = UrlHelper::siteUrl($path);
292
            } catch (Exception $e) {
293
                Craft::error($e->getMessage(), __METHOD__);
294
            }
295
        }
296
297
        return self::getFileContents($path, $callback);
298
    }
299
300
    /**
301
     * Return the contents of a file from the passed in path
302
     *
303
     * @param string   $path
304
     * @param callable $callback
305
     *
306
     * @return mixed
307
     */
308
    protected static function getFileContents(string $path, callable $callback = null)
309
    {
310
        // Return the memoized manifest if it exists
311
        if (!empty(self::$files[$path])) {
312
            return self::$files[$path];
313
        }
314
        // Create the dependency tags
315
        $dependency = new TagDependency([
316
            'tags' => [
317
                self::CACHE_TAG,
318
                self::CACHE_TAG.$path,
319
            ],
320
        ]);
321
        // Set the cache duration based on devMode
322
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
323
            ? self::DEVMODE_CACHE_DURATION
324
            : null;
325
        // Get the result from the cache, or parse the file
326
        $cache = Craft::$app->getCache();
327
        $file = $cache->getOrSet(
328
            self::CACHE_KEY.$path,
329
            function () use ($path, $callback) {
330
                $result = @file_get_contents($path);
331
                if ($result && $callback) {
332
                    $result = $callback($result);
333
                }
334
335
                return $result;
336
            },
337
            $cacheDuration,
338
            $dependency
339
        );
340
        self::$files[$path] = $file;
341
342
        return $file;
343
    }
344
345
    /**
346
     * Combined the passed in paths, whether file system or URL
347
     *
348
     * @param string ...$paths
349
     *
350
     * @return string
351
     */
352
    protected static function combinePaths(string ...$paths): string
353
    {
354
        $last_key = \count($paths) - 1;
355
        array_walk($paths, function (&$val, $key) use ($last_key) {
356
            switch ($key) {
357
                case 0:
358
                    $val = rtrim($val, '/ ');
359
                    break;
360
                case $last_key:
361
                    $val = ltrim($val, '/ ');
362
                    break;
363
                default:
364
                    $val = trim($val, '/ ');
365
                    break;
366
            }
367
        });
368
369
        $first = array_shift($paths);
370
        $last = array_pop($paths);
371
        $paths = array_filter($paths);
372
        array_unshift($paths, $first);
373
        $paths[] = $last;
374
375
        return implode('/', $paths);
376
    }
377
378
    /**
379
     * @param string $error
380
     * @param bool   $soft
381
     *
382
     * @throws NotFoundHttpException
383
     */
384
    protected static function reportError(string $error, $soft = false)
385
    {
386
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
387
        if ($devMode && !$soft) {
388
            throw new NotFoundHttpException($error);
389
        }
390
        Craft::error($error, __METHOD__);
391
    }
392
393
    // Private Static Methods
394
    // =========================================================================
395
396
    /**
397
     * @param $string
398
     *
399
     * @return mixed
400
     */
401
    private function jsonFileDecode($string)
402
    {
403
        return JsonHelper::decodeIfJson($string);
404
    }
405
}
406