Passed
Push — v1 ( 2a4f93...bf6c9c )
by Andrew
07:11 queued 04:13
created

Manifest::getJsonFileContents()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 22
nc 3
nop 1
dl 0
loc 36
rs 9.568
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');
59
        if ($legacyModule === null) {
60
            return null;
61
        }
62
        $lines = [];
63
        if ($async) {
64
            $lines[] = "<link rel=\"preload\" href=\"{$legacyModule}\" as=\"style\" onload=\"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
     * @param array  $config
75
     * @param string $moduleName
76
     * @param bool   $async
77
     *
78
     * @return null|string
79
     * @throws NotFoundHttpException
80
     */
81
    public static function getJsModuleTags(array $config, string $moduleName, bool $async)
82
    {
83
        $legacyModule = self::getModule($config, $moduleName, 'legacy');
84
        if ($legacyModule === null) {
85
            return null;
86
        }
87
        if ($async) {
88
            $modernModule = self::getModule($config, $moduleName, 'modern');
89
            if ($modernModule === null) {
90
                return null;
91
            }
92
        }
93
        $lines = [];
94
        if ($async) {
95
            $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...
96
            $lines[] = "<script nomodule src=\"{$legacyModule}\"></script>";
97
        } else {
98
            $lines[] = "<script src=\"{$legacyModule}\"></script>";
99
        }
100
101
        return implode("\r\n", $lines);
102
    }
103
104
    /**
105
     * Safari 10.1 supports modules, but does not support the `nomodule`
106
     * attribute - it will load <script nomodule> anyway. This snippet solve
107
     * this problem, but only for script tags that load external code, e.g.:
108
     * <script nomodule src="nomodule.js"></script>
109
     *
110
     * Again: this will **not* # prevent inline script, e.g.:
111
     * <script nomodule>alert('no modules');</script>.
112
     *
113
     * This workaround is possible because Safari supports the non-standard
114
     * 'beforeload' event. This allows us to trap the module and nomodule load.
115
     *
116
     * Note also that `nomodule` is supported in later versions of Safari -
117
     * it's just 10.1 that omits this attribute.
118
     *
119
     * c.f.: https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
120
     *
121
     * @return string
122
     */
123
    public static function getSafariNomoduleFix(): string
124
    {
125
        return <<<EOT
126
<script>
127
!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()}}();
128
</script>
129
EOT;
130
    }
131
132
    /**
133
     * Return the URI to a module
134
     *
135
     * @param array  $config
136
     * @param string $moduleName
137
     * @param string $type
138
     *
139
     * @return null|string
140
     * @throws NotFoundHttpException
141
     */
142
    public static function getModule(array $config, string $moduleName, string $type = 'modern')
143
    {
144
        $module = null;
145
        // Determine whether we should use the devServer for HMR or not
146
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
147
        $isHot = ($devMode && $config['useDevServer']);
148
        // Get the manifest file
149
        $manifest = self::getManifestFile($config, $isHot, $type);
150
        if ($manifest !== null) {
151
            $module = $manifest[$moduleName];
152
            $prefix = $isHot
153
                ? $config['devServer']['publicPath']
154
                : $config['server']['publicPath'];
155
            // If the module isn't a full URL, prefix it
156
            if (!UrlHelper::isAbsoluteUrl($module)) {
157
                $module = self::combinePaths($prefix, $module);
158
            }
159
            // Make sure it's a full URL
160
            if (!UrlHelper::isAbsoluteUrl($module)) {
161
                try {
162
                    $module = UrlHelper::siteUrl($module);
163
                } catch (Exception $e) {
164
                    Craft::error($e->getMessage(), __METHOD__);
165
                }
166
            }
167
        }
168
169
        return $module;
170
    }
171
172
    /**
173
     * Return a JSON-decoded manifest file
174
     *
175
     * @param array  $config
176
     * @param bool   $isHot
177
     * @param string $type
178
     *
179
     * @return null|array
180
     * @throws NotFoundHttpException
181
     */
182
    public static function getManifestFile(array $config, bool &$isHot, string $type = 'modern')
183
    {
184
        $manifest = null;
185
        // Try to get the manifest
186
        while ($manifest === null) {
187
            $manifestPath = $isHot
188
                ? $config['devServer']['manifestPath']
189
                : $config['server']['manifestPath'];
190
            // Normalize the path
191
            $path = self::combinePaths($manifestPath, $config['manifest'][$type]);
192
            $manifest = self::getJsonFileFromUri($path);
193
            // If the manifest isn't found, and it was hot, fall back on non-hot
194
            if ($manifest === null) {
195
                Craft::error(
196
                    Craft::t(
197
                        'twigpack',
198
                        'Manifest file not found at: {manifestPath}',
199
                        ['manifestPath' => $manifestPath]
200
                    ),
201
                    __METHOD__
202
                );
203
                if ($isHot) {
204
                    // Try again, but not with home module replacement
205
                    $isHot = false;
206
                } else {
207
                    if ($devMode) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $devMode seems to be never defined.
Loading history...
208
                        // We couldn't find a manifest; throw an error
209
                        throw new NotFoundHttpException(
210
                            Craft::t(
211
                                'twigpack',
212
                                'Manifest file not found at: {manifestPath}',
213
                                ['manifestPath' => $manifestPath]
214
                            )
215
                        );
216
                    }
217
218
                    return null;
219
                }
220
            }
221
        }
222
223
        return $manifest;
224
    }
225
226
    /**
227
     * Invalidate all of the manifest caches
228
     */
229
    public static function invalidateCaches()
230
    {
231
        $cache = Craft::$app->getCache();
232
        TagDependency::invalidate($cache, self::CACHE_TAG);
233
        Craft::info('All manifest caches cleared', __METHOD__);
234
    }
235
236
    // Protected Static Methods
237
    // =========================================================================
238
239
    /**
240
     * Return the contents of a file from a URI path
241
     *
242
     * @param string $path
243
     *
244
     * @return mixed
245
     */
246
    protected static function getJsonFileFromUri(string $path)
247
    {
248
        // Make sure it's a full URL
249
        if (!UrlHelper::isAbsoluteUrl($path)) {
250
            try {
251
                $path = UrlHelper::siteUrl($path);
252
            } catch (Exception $e) {
253
                Craft::error($e->getMessage(), __METHOD__);
254
            }
255
        }
256
257
        return self::getJsonFileContents($path);
258
    }
259
260
    /**
261
     * Return the contents of a file from the passed in path
262
     *
263
     * @param string $path
264
     *
265
     * @return mixed
266
     */
267
    protected static function getJsonFileContents(string $path)
268
    {
269
        // Return the memoized manifest if it exists
270
        if (!empty(self::$files[$path])) {
271
            return self::$files[$path];
272
        }
273
        // Create the dependency tags
274
        $dependency = new TagDependency([
275
            'tags' => [
276
                self::CACHE_TAG,
277
                self::CACHE_TAG.$path,
278
            ],
279
        ]);
280
        // Set the cache duration based on devMode
281
        $cacheDuration = Craft::$app->getConfig()->getGeneral()->devMode
282
            ? self::DEVMODE_CACHE_DURATION
283
            : null;
284
        // Get the result from the cache, or parse the file
285
        $cache = Craft::$app->getCache();
286
        $file = $cache->getOrSet(
287
            self::CACHE_KEY.$path,
288
            function () use ($path) {
289
                $result = null;
290
                $string = @file_get_contents($path);
291
                if ($string) {
292
                    $result = JsonHelper::decodeIfJson($string);
293
                }
294
295
                return $result;
296
            },
297
            $cacheDuration,
298
            $dependency
299
        );
300
        self::$files[$path] = $file;
301
302
        return $file;
303
    }
304
305
    /**
306
     * Combined the passed in paths, whether file system or URL
307
     *
308
     * @param string ...$paths
309
     *
310
     * @return string
311
     */
312
    protected static function combinePaths(string ...$paths): string
313
    {
314
        $last_key = \count($paths) - 1;
315
        array_walk($paths, function (&$val, $key) use ($last_key) {
316
            switch ($key) {
317
                case 0:
318
                    $val = rtrim($val, '/ ');
319
                    break;
320
                case $last_key:
321
                    $val = ltrim($val, '/ ');
322
                    break;
323
                default:
324
                    $val = trim($val, '/ ');
325
                    break;
326
            }
327
        });
328
329
        $first = array_shift($paths);
330
        $last = array_pop($paths);
331
        $paths = array_filter($paths);
332
        array_unshift($paths, $first);
333
        $paths[] = $last;
334
335
        return implode('/', $paths);
336
    }
337
}
338