-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAbstractWebpackLoader.php
More file actions
258 lines (221 loc) · 7.45 KB
/
AbstractWebpackLoader.php
File metadata and controls
258 lines (221 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
<?php
declare(strict_types=1);
namespace Inpsyde\Assets\Loader;
use Inpsyde\Assets\Asset;
use Inpsyde\Assets\BaseAsset;
use Inpsyde\Assets\ConfigureAutodiscoverVersionTrait;
use Inpsyde\Assets\Exception\FileNotFoundException;
use Inpsyde\Assets\Exception\InvalidResourceException;
use Inpsyde\Assets\Script;
use Inpsyde\Assets\ScriptModule;
use Inpsyde\Assets\Style;
abstract class AbstractWebpackLoader implements LoaderInterface
{
use ConfigureAutodiscoverVersionTrait;
protected string $directoryUrl = '';
/**
* @param string $directoryUrl optional directory URL which will be used for the Asset
*
* @return static
*/
public function withDirectoryUrl(string $directoryUrl): AbstractWebpackLoader
{
$this->directoryUrl = $directoryUrl;
return $this;
}
/**
* @param array<string, string> $data
* @param string $resource
*
* @return Asset[]
*/
abstract protected function parseData(array $data, string $resource): array;
/**
* @param mixed $resource
*
* @return Asset[]
*
* phpcs:disable Syde.Functions.ArgumentTypeDeclaration.NoArgumentType
* @psalm-suppress MixedArgument
*/
public function load($resource): array
{
if (!is_string($resource) || !is_readable($resource)) {
throw new FileNotFoundException(
sprintf(
'The given file "%s" does not exists or is not readable.',
esc_html($resource)
)
);
}
$data = @file_get_contents($resource)
?: ''; // phpcs:ignore
$data = json_decode($data, true);
$errorCode = json_last_error();
if (0 < $errorCode) {
throw new InvalidResourceException(
sprintf(
'Error parsing JSON - %s',
esc_html($this->getJSONErrorMessage($errorCode))
)
);
}
return $this->parseData($data, $resource);
}
/**
* Translates JSON_ERROR_* constant into meaningful message.
*
* @param int $errorCode
*
* @return string Message string
*/
private function getJSONErrorMessage(int $errorCode): string
{
switch ($errorCode) {
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded';
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch';
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON';
case JSON_ERROR_UTF8:
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
default:
return 'Unknown error';
}
}
/**
* @param string $handle
* @param string $fileUrl
* @param string $filePath
*
* @return Asset|null
*/
protected function buildAsset(string $handle, string $fileUrl, string $filePath): ?Asset
{
/** @var array{filename?:string, extension?:string} $pathInfo */
$pathInfo = pathinfo($filePath);
$filename = $pathInfo['filename'] ?? '';
$class = self::resolveClassByExtension($filePath);
if (!$class) {
return null;
}
/** @var Style|Script|ScriptModule $asset */
$asset = new $class($handle, $fileUrl, $this->resolveLocation($filename));
$asset->withFilePath($filePath);
$asset->canEnqueue(true);
if ($asset instanceof BaseAsset) {
$this->autodiscoverVersion
? $asset->enableAutodiscoverVersion()
: $asset->disableAutodiscoverVersion();
}
return $asset;
}
protected function resolveClassByExtension(string $filePath): ?string
{
$extensionsToClass = [
'css' => Style::class,
'js' => Script::class,
'mjs' => ScriptModule::class,
'module.js' => ScriptModule::class,
];
// TODO Maybe make use of \SplFileInfo since it's typed and we can share it
// we have to just make a factory method and that's it.
/** @var array{filename?:string, extension?:string} $pathInfo */
$pathInfo = pathinfo($filePath);
$baseName = $pathInfo['basename'] ?? '';
$extension = $pathInfo['extension'] ?? '';
if (self::isModule($baseName)) {
$extension = 'module.js';
}
if (!in_array($extension, array_keys($extensionsToClass), true)) {
return null;
}
return $extensionsToClass[$extension];
}
protected static function isModule(string $fileName): bool
{
// TODO replace it with `str_ends_with` once dropping support for php 7.4
$strEndsWith = static function (string $haystack, string $needle): bool {
return substr_compare($haystack, $needle, -strlen($needle)) === 0;
};
return $strEndsWith($fileName, '.module.js') || $strEndsWith($fileName, '.mjs');
}
/**
* The "file"-value can contain:
* - URL
* - Path to current folder
* - Absolute path
*
* We try to build a clean path which will be appended to the directoryPath or urlPath.
*
* @param string $file
*
* @return string
*/
protected function sanitizeFileName(string $file): string
{
// Check if the given "file"-value is a URL
$parsedUrl = parse_url($file);
// the "file"-value can contain "./file.css" or "/file.css".
return ltrim($parsedUrl['path'] ?? $file, './');
}
/**
* Internal function to sanitize the handle based on the file
* by taking into consideration that @vendor can be present.
*
* @param string $file
*
* @return string
* @example /path/to/@vendor/script.module.js -> @vendor/script.module
*
* @example /path/to/script.js -> script
* @example @vendor/script.module.js -> @vendor/script.module
*/
protected function sanitizeHandle(string $file): string
{
$pathInfo = pathinfo($file);
$dirName = $pathInfo['dirname'] ?? '';
$parts = explode('@', $dirName);
$vendor = $parts[1] ?? null;
$handle = $pathInfo['filename'];
if ($vendor !== null) {
$handle = "@{$vendor}/{$handle}";
}
return $handle;
}
/**
* Internal function to resolve a location for a given file name.
*
* @param string $fileName
*
* @return int
*
* @example foo-customizer.css -> Asset::CUSTOMIZER
* @example foo-block.css -> Asset::BLOCK_EDITOR_ASSETS
* @example foo-login.css -> Asset::LOGIN
* @example foo.css -> Asset::FRONTEND
* @example foo-backend.css -> Asset::BACKEND
*/
protected function resolveLocation(string $fileName): int
{
if (stristr($fileName, '-backend')) {
return Asset::BACKEND;
}
if (stristr($fileName, '-block')) {
return Asset::BLOCK_EDITOR_ASSETS;
}
if (stristr($fileName, '-login')) {
return Asset::LOGIN;
}
if (stristr($fileName, '-customizer-preview')) {
return Asset::CUSTOMIZER_PREVIEW;
}
if (stristr($fileName, '-customizer')) {
return Asset::CUSTOMIZER;
}
return Asset::FRONTEND;
}
}