| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Assets package. |
| 5 |
* |
| 6 |
* (c) Inpsyde GmbH |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
declare(strict_types=1); |
| 13 |
|
| 14 |
namespace Inpsyde\Assets\Loader; |
| 15 |
|
| 16 |
use Inpsyde\Assets\Asset; |
| 17 |
|
| 18 |
/** |
| 19 |
* Implementation of Symfony's Encore implementation of entrypoints.json which |
| 20 |
* supports splitEntryChunks and hashing. |
| 21 |
* |
| 22 |
* @package Inpsyde\Assets\Loader |
| 23 |
*/ |
| 24 |
class EncoreEntrypointsLoader extends AbstractWebpackLoader implements LoaderInterface |
| 25 |
{ |
| 26 |
/** |
| 27 |
* {@inheritDoc} |
| 28 |
*/ |
| 29 |
protected function parseData(array $data, string $resource): array |
| 30 |
{ |
| 31 |
$directory = trailingslashit(dirname($resource)); |
| 32 |
/** @var array{entrypoints:array{css?:string[], js?:string[]}} $data */ |
| 33 |
$data = $data['entrypoints'] ?? []; |
| 34 |
|
| 35 |
$assets = []; |
| 36 |
foreach ($data as $handle => $filesByExtension) { |
| 37 |
$files = $filesByExtension['css'] ?? []; |
| 38 |
$assets = array_merge($assets, $this->extractAssets($handle, $files, $directory)); |
| 39 |
|
| 40 |
$files = $filesByExtension['js'] ?? []; |
| 41 |
$assets = array_merge($assets, $this->extractAssets($handle, $files, $directory)); |
| 42 |
} |
| 43 |
|
| 44 |
return $assets; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* @param string $handle |
| 49 |
* @param string[] $files |
| 50 |
* @param string $directory |
| 51 |
* |
| 52 |
* @return array |
| 53 |
*/ |
| 54 |
protected function extractAssets(string $handle, array $files, string $directory): array |
| 55 |
{ |
| 56 |
$assets = []; |
| 57 |
|
| 58 |
foreach ($files as $i => $file) { |
| 59 |
$handle = $i > 0 |
| 60 |
? "{$handle}-{$i}" |
| 61 |
: $handle; |
| 62 |
|
| 63 |
$sanitizedFile = $this->sanitizeFileName($file); |
| 64 |
|
| 65 |
$fileUrl = (!$this->directoryUrl) |
| 66 |
? $file |
| 67 |
: $this->directoryUrl . $sanitizedFile; |
| 68 |
|
| 69 |
$filePath = $directory . $sanitizedFile; |
| 70 |
|
| 71 |
$asset = $this->buildAsset($handle, $fileUrl, $filePath); |
| 72 |
|
| 73 |
if ($asset !== null) { |
| 74 |
$assets[] = $asset; |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
foreach ($assets as $i => $asset) { |
| 79 |
$dependencies = array_map( |
| 80 |
static function (Asset $asset): string { |
| 81 |
return $asset->handle(); |
| 82 |
}, |
| 83 |
array_slice($assets, 0, $i) |
| 84 |
); |
| 85 |
$asset->withDependencies(...$dependencies); |
| 86 |
} |
| 87 |
|
| 88 |
return $assets; |
| 89 |
} |
| 90 |
} |
| 91 |
|