-
-
Notifications
You must be signed in to change notification settings - Fork 621
Expand file tree
/
Copy pathInstallableModule.php
More file actions
308 lines (259 loc) · 8.91 KB
/
InstallableModule.php
File metadata and controls
308 lines (259 loc) · 8.91 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php
namespace Statamic\StarterKits;
use Exception;
use Facades\Statamic\Console\Processes\Composer;
use Illuminate\Support\Collection;
use Statamic\Console\Processes\Exceptions\ProcessException;
use Statamic\Facades\Path;
use Statamic\StarterKits\Exceptions\StarterKitException;
use Statamic\Support\Str;
final class InstallableModule extends Module
{
protected $installer;
/**
* Set installer instance.
*
* @throws Exception|StarterKitException
*/
public function installer(?Installer $installer): self
{
$this->installer = $installer;
return $this;
}
/**
* Validate starter kit module is installable.
*
* @throws Exception|StarterKitException
*/
public function validate(): void
{
$this
->requireParentInstaller()
->ensureModuleConfigNotEmpty()
->ensureInstallableFilesExist()
->ensureCompatibleDependencies();
}
/**
* Install starter kit module.
*
* @throws Exception|StarterKitException
*/
public function install(): void
{
$this
->requireParentInstaller()
->installFiles()
->installDependencies();
}
/**
* Require parent installer instance.
*
* @throws Exception
*/
protected function requireParentInstaller(): self
{
if (! $this->installer) {
throw new Exception('Parent installer required for this operation!');
}
return $this;
}
/**
* Install starter kit module files.
*/
protected function installFiles(): self
{
$this->installableFiles()->each(function ($toPath, $fromPath) {
$this->installFile($fromPath, $toPath, $this->installer->console());
});
return $this;
}
/**
* Install starter kit module dependencies.
*/
protected function installDependencies(): self
{
if ($this->installer->withoutDependencies()) {
return $this;
}
if ($packages = $this->installableDependencies('dependencies')) {
$this->requireDependencies($packages);
}
if ($packages = $this->installableDependencies('dependencies_dev')) {
$this->requireDependencies($packages, true);
}
return $this;
}
/**
* Get installable files.
*/
public function installableFiles(): Collection
{
$installableFromExportPaths = $this
->exportPaths()
->flatMap(fn ($path) => $this->expandExportDirectoriesToFiles($path));
$installableFromExportAsPaths = $this
->exportAsPaths()
->flip()
->flatMap(fn ($to, $from) => $this->expandExportDirectoriesToFiles($to, $from));
return collect()
->merge($installableFromExportPaths)
->merge($installableFromExportAsPaths);
}
/**
* Expand export path to `[$from => $to]` array format, normalizing directories to files.
*
* This is necessary when installing starter kit into existing directories, so that we don't stomp whole directories.
*/
protected function expandExportDirectoriesToFiles(string $to, ?string $from = null): Collection
{
$from = $this->relativePath($from ?? $to);
$from = Path::tidy($this->installableFilesPath($from));
$to = Path::tidy($this->installableFilesPath($to));
$paths = collect([$from => $to]);
if ($this->files->isDirectory($from)) {
$paths = collect($this->files->allFiles($from))
->map
->getPathname()
->mapWithKeys(fn ($path) => [
$path => str_replace($from, $to, $path),
]);
}
return $paths->mapWithKeys(fn ($to, $from) => [
Path::tidy($from) => Path::tidy($this->convertInstallableToDestinationPath($to)),
]);
}
/**
* Convert installable vendor file path to destination path.
*/
protected function convertInstallableToDestinationPath(string $path): string
{
$package = $this->installer->package();
$path = preg_replace("#vendor/{$package}.*/export/#", '', $path);
// Older kits may not be using new `export` folder convention, so
// we'll convert from the kit root for backwards compatibility
$path = str_replace("/vendor/{$package}", '', $path);
return $path;
}
/**
* Install dependency permanently into app.
*/
protected function requireDependencies(array $packages, bool $dev = false): void
{
$args = array_merge(['require'], $this->normalizePackagesArrayToRequireArgs($packages));
if ($dev) {
$args[] = '--dev';
}
try {
Composer::withoutQueue()->throwOnFailure()->runAndOperateOnOutput($args, function ($output) {
return $this->outputFromSymfonyProcess($output);
});
} catch (ProcessException $exception) {
$this->installer->console()->error('Error installing dependencies.');
}
}
/**
* Get installable dependencies from appropriate require key in composer.json.
*/
protected function installableDependencies(string $configKey): array
{
return collect($this->config($configKey))
->filter(fn ($version, $package) => Str::contains($package, '/'))
->all();
}
/**
* Ensure installable files exist.
*
* @throws StarterKitException
*/
protected function ensureInstallableFilesExist(): self
{
$this
->installableFiles()
->reject(fn ($to, $from) => $this->files->exists($from))
->each(function ($path) {
throw new StarterKitException("Starter kit path [{$path}] does not exist.");
});
return $this;
}
/**
* Ensure compatible dependencies by performing a dry-run.
*/
protected function ensureCompatibleDependencies(): self
{
if ($this->installer->withoutDependencies() || $this->installer->force()) {
return $this;
}
if ($packages = $this->installableDependencies('dependencies')) {
$this->ensureCanRequireDependencies($packages);
}
if ($packages = $this->installableDependencies('dependencies_dev')) {
$this->ensureCanRequireDependencies($packages, true);
}
return $this;
}
/**
* Ensure dependencies are installable by performing a dry-run.
*/
protected function ensureCanRequireDependencies(array $packages, bool $dev = false): void
{
$requireMethod = $dev ? 'requireMultipleDev' : 'requireMultiple';
try {
Composer::withoutQueue()->throwOnFailure()->{$requireMethod}($packages, '--dry-run');
} catch (ProcessException $exception) {
$this->installer->rollbackWithError('Cannot install due to dependency conflict.', $exception->getMessage());
}
}
/**
* Get starter kit installable files path.
*/
protected function installableFilesPath(?string $path = null): string
{
$package = $this->installer->package();
// Older kits may not be using new `export` folder convention at the top level,
// so for backwards compatibility we'll dynamically scope to `export` folder,
// but we don't need to worry about this with newer folder based modules.
$scope = $this->files->exists(base_path("vendor/{$package}/export")) && ! $this->isFolderBasedModule()
? 'export'
: null;
return collect([base_path("vendor/{$package}"), $scope, $path])->filter()->implode('/');
}
/**
* Get relative module path.
*/
protected function relativePath(string $path): string
{
if (! $this->relativePath) {
return $path;
}
return Str::ensureRight($this->relativePath, '/export/').$path;
}
/**
* Normalize packages array to require args, with version handling if `package => version` array structure is passed.
*/
protected function normalizePackagesArrayToRequireArgs(array $packages): array
{
return collect($packages)
->map(function ($value, $key) {
return Str::contains($key, '/')
? "{$key}:{$value}"
: "{$value}";
})
->values()
->all();
}
/**
* Clean up symfony process output and output to cli.
*/
protected function outputFromSymfonyProcess(string $output): string
{
// Remove terminal color codes.
$output = preg_replace('/\\e\[[0-9]+m/', '', $output);
// Remove new lines.
$output = preg_replace('/[\r\n]+$/', '', $output);
// If not a blank line, output to terminal.
if (! empty(trim($output))) {
$this->installer->console()->line($output);
}
return $output;
}
}