forked from tonysm/importmap-laravel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptimizeCommand.php
75 lines (58 loc) · 2.78 KB
/
OptimizeCommand.php
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
<?php
namespace Tonysm\ImportmapLaravel\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Symfony\Component\Console\Attribute\AsCommand;
use Tonysm\ImportmapLaravel\FileDigest;
use Tonysm\ImportmapLaravel\Importmap;
use Tonysm\ImportmapLaravel\Manifest;
#[AsCommand('importmap:optimize')]
class OptimizeCommand extends Command
{
public $signature = 'importmap:optimize';
public $description = 'Builds the JavaScript dependencies, generating a manifest so we dont have to recreate the importmaps JSON on the spot (good for Vapor).';
public function handle(Importmap $importmap): int
{
$this->call('importmap:clear');
$this->info('Copying over the files to a dist folder and generating a digest of them...');
if ($imports = $importmap->asArray(fn ($file) => $file)) {
$optimizedImports = collect($imports['imports'])
->reject(fn (string $url) => Str::startsWith($url, ['http://', 'https://']))
->map(function (string $file) use ($importmap) {
$sourceFile = $importmap->rootPath.(str_starts_with(trim($file, '/'), 'vendor/') ? '/public/' : '/resources/').trim($file, '/');
$sourceReplacement = $importmap->rootPath.'/public/dist/'.trim($this->digest($file, $sourceFile), '/');
File::ensureDirectoryExists(dirname($sourceReplacement));
File::copy($sourceFile, $sourceReplacement);
$replacement = Str::after($sourceReplacement, $importmap->rootPath.'/public/');
$this->output->writeln(sprintf(
' copied %s to %s',
$file,
$replacement,
));
return $replacement;
});
$this->info('Generating cached manifest...');
$preloadModulePaths = $importmap->preloadedModulePaths(fn ($file) => $file);
$optmizedJson = collect($imports['imports'])
->map(fn (string $oldFilename, string $module): array => [
'module' => $module,
'path' => $optimizedImports[$module] ?? $oldFilename,
'preload' => in_array($oldFilename, $preloadModulePaths),
])
->values()
->all();
File::put(Manifest::path(), json_encode($optmizedJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}
$this->info('Done!');
return self::SUCCESS;
}
private function digest(string $filename, string $fileSource): string
{
return preg_replace(
'#(\.jsm?)$#',
sprintf('-%s$1', (new FileDigest)($fileSource)),
$filename
);
}
}