/
PrepareCommand.php
224 lines (178 loc) · 9.72 KB
/
PrepareCommand.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
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
<?php
/*
* Copyright (c) 2023 Heimrich & Hannot GmbH
*
* @license LGPL-3.0-or-later
*/
namespace HeimrichHannot\EncoreBundle\Command;
use Composer\InstalledVersions;
use const DIRECTORY_SEPARATOR;
use HeimrichHannot\EncoreBundle\Collection\ExtensionCollection;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment;
class PrepareCommand extends Command
{
public const DEPENDENCY_PREFIX = '@huh/encore-bundle--';
protected static $defaultName = 'huh:encore:prepare';
protected static $defaultDescription = 'Does the necessary preparation for contao encore bundle. Needs to be called after changes to bundle encore entries.';
private SymfonyStyle $io;
private CacheItemPoolInterface $encoreCache;
private KernelInterface $kernel;
private array $bundleConfig;
private Environment $twig;
private ExtensionCollection $extensionCollection;
public function __construct(CacheItemPoolInterface $encoreCache, KernelInterface $kernel, array $bundleConfig, Environment $twig, ExtensionCollection $extensionCollection)
{
parent::__construct();
$this->encoreCache = $encoreCache;
$this->kernel = $kernel;
$this->bundleConfig = $bundleConfig;
$this->twig = $twig;
$this->extensionCollection = $extensionCollection;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setAliases(['encore:prepare'])
->setDescription(static::$defaultDescription)
->addOption('skip-entries', null, InputOption::VALUE_OPTIONAL, 'Add a comma separated list of entries to skip their generation.', false);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->io = new SymfonyStyle($input, $output);
$this->io->title('Update project encore data');
$resultFile = $this->kernel->getProjectDir().DIRECTORY_SEPARATOR.'encore.bundles.js';
$skipEntries = $input->getOption('skip-entries') ? explode(',', $input->getOption('skip-entries')) : [];
$this->io->writeln('Using <fg=green>'.$this->kernel->getEnvironment().'</> environment. (Use --env=[ENV] to change environment. See --help for more information!)');
@unlink($resultFile);
$this->encoreCache->clear();
$this->io->text(['', ' // Collect entries', '']);
$this->io->writeln('> Collect entries from yaml config');
$encoreJsEntries = [];
// collect entries from yaml
if (isset($this->bundleConfig['js_entries']) && \is_array($this->bundleConfig['js_entries'])) {
foreach ($this->bundleConfig['js_entries'] as $entry) {
$preparedEntry = [
'name' => $entry['name'],
];
if (!str_starts_with($entry['file'], '@')) {
$preparedEntry['file'] = './'.preg_replace('@^\.?\/@i', '', $entry['file']);
} else {
$preparedEntry['file'] = rtrim((new Filesystem())->makePathRelative($this->kernel->locateResource($entry['file']), $this->kernel->getProjectDir()), DIRECTORY_SEPARATOR);
}
$encoreJsEntries[] = $preparedEntry;
}
}
$this->io->newLine();
$yamlEntryCount = \count($encoreJsEntries);
if ($yamlEntryCount < 1) {
$this->io->writeln('Found no encore entry registered through yaml config 👍');
} elseif (1 === $yamlEntryCount) {
$this->io->writeln('<bg=yellow;fg=black>Found 1 encore entry registered through yaml config. This is deprecated and support will be dropped in a future version.</>');
} else {
$this->io->writeln("<bg=yellow;fg=black>Found $yamlEntryCount encore entries registered through yaml config. This is deprecated and support will be dropped in a future version.</>");
}
if ($this->io->isVerbose()) {
$this->io->text(['', 'Following entries registered through yaml:']);
$this->io->table(['name', 'path'], $encoreJsEntries);
}
$this->io->writeln(['', '> Collect entries from encore extensions']);
$extensionDependencies = [];
$extensionList = [];
foreach ($this->extensionCollection->getExtensions() as $extension) {
$reflection = new \ReflectionClass($extension->getBundle());
$bundle = $this->kernel->getBundles()[$reflection->getShortName()];
$bundlePath = $bundle->getPath();
if (!file_exists($bundlePath.DIRECTORY_SEPARATOR.'composer.json')) {
$bundlePath = $bundlePath.DIRECTORY_SEPARATOR.'..';
}
if (!file_exists($bundlePath.DIRECTORY_SEPARATOR.'composer.json')) {
trigger_error(
'[Encore Bundle] Could not find composer.json file for '.$bundle->getName().'.'
.' Skipping EncoreExtension '.\get_class($extension).'.'
);
continue;
}
try {
$composerData = json_decode(file_get_contents($bundlePath.'/composer.json'), null, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \JsonException('composer.json of '.$reflection->getShortName().' has a syntax error.');
}
$bundlePath = InstalledVersions::getInstallPath($composerData->name);
$bundlePath = rtrim((new Filesystem())->makePathRelative($bundlePath, $this->kernel->getProjectDir()), DIRECTORY_SEPARATOR);
$preparedEntry = [];
foreach ($extension->getEntries() as $entry) {
$preparedEntry['name'] = $entry->getName();
$preparedEntry['file'] = '.'.DIRECTORY_SEPARATOR.$bundlePath.DIRECTORY_SEPARATOR.ltrim($entry->getPath(), DIRECTORY_SEPARATOR);
$encoreJsEntries[] = $preparedEntry;
}
if (file_exists($bundlePath.DIRECTORY_SEPARATOR.'package.json')) {
$packageData = json_decode(file_get_contents($bundlePath.DIRECTORY_SEPARATOR.'package.json'), true);
$extensionDependencies = array_merge($extensionDependencies, ($packageData['dependencies'] ?? []));
}
$extensionList[] = [$reflection->getShortName(), \get_class($extension), $bundlePath];
}
$this->io->newLine();
$this->io->writeln('Found <fg=green>'.\count($this->extensionCollection->getExtensions()).'</> registered encore extensions.');
if ($this->io->isVerbose()) {
$this->io->table(['Bundle', 'Extension', 'Bundle path'], $extensionList);
}
$this->io->text(['', ' // Update encore entry dependencies', '']);
if (file_exists($this->kernel->getProjectDir().DIRECTORY_SEPARATOR.'package.json')) {
$this->io->writeln('Collect encore entry dependencies ');
$encorePackageData = [
'name' => '@hundh/encore-entry-dependencies',
'version' => date('Ymd').'.'.date('Hi').'.'.time(),
'dependencies' => $extensionDependencies,
];
$encoreAssetsPath = 'vendor'.DIRECTORY_SEPARATOR.'heimrichhannot'.DIRECTORY_SEPARATOR.'encore-entry-dependencies';
(new Filesystem())->dumpFile(
$this->kernel->getProjectDir().DIRECTORY_SEPARATOR.$encoreAssetsPath.DIRECTORY_SEPARATOR.'package.json',
json_encode($encorePackageData, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)
);
$this->io->writeln('Register dependencies in project');
$packageData = json_decode(file_get_contents($this->kernel->getProjectDir().DIRECTORY_SEPARATOR.'package.json'), true);
$packageData['dependencies'] = array_merge(
['@hundh/encore-entry-dependencies' => 'file:.'.DIRECTORY_SEPARATOR.$encoreAssetsPath.DIRECTORY_SEPARATOR],
$packageData['dependencies'] ?? []
);
(new Filesystem())->dumpFile(
$this->kernel->getProjectDir().DIRECTORY_SEPARATOR.'package.json',
json_encode($packageData, \JSON_THROW_ON_ERROR | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)
);
} else {
$this->io->warning('No package.json could be found in your project. This file must be present for encore to work!');
}
if (!empty($encoreJsEntries)) {
$this->io->text(['', ' // Output encore_bundles.js', '']);
$content = $this->twig->render('@HeimrichHannotContaoEncore/encore_bundles.js.twig', [
'entries' => $encoreJsEntries,
'skipEntries' => $skipEntries,
]);
file_put_contents($resultFile, $content);
$this->io->writeln('Created encore.bundles.js in your project root. You can now require it in your webpack.config.js');
} else {
$this->io->warning('Found no registered encore entries. Skipped encore.bundles.js creation.');
}
$this->io->success('Finished updating your project encore data.');
$this->io->text([
'Next steps:',
'1. If your dependencies have changed, run <fg=black;bg=cyan> yarn upgrade </>.',
'2. Compile your asset with <fg=black;bg=cyan> yarn encore dev </>, <fg=black;bg=cyan> yarn encore dev --watch </> or <fg=black;bg=cyan> yarn encore prod </>',
'',
]);
return 0;
}
}