-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathConfigurationFactory.php
385 lines (318 loc) · 11.2 KB
/
ConfigurationFactory.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
declare(strict_types=1);
/*
* This file is part of the humbug/php-scoper package.
*
* Copyright (c) 2017 Théo FIDRY <[email protected]>,
* Pádraic Brady <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Humbug\PhpScoper\Configuration;
use Exception;
use Humbug\PhpScoper\Configuration\Throwable\InvalidConfiguration;
use Humbug\PhpScoper\Configuration\Throwable\InvalidConfigurationFile;
use Humbug\PhpScoper\Configuration\Throwable\InvalidConfigurationValue;
use Humbug\PhpScoper\Patcher\ComposerPatcher;
use Humbug\PhpScoper\Patcher\Patcher;
use Humbug\PhpScoper\Patcher\PatcherChain;
use Humbug\PhpScoper\Patcher\SymfonyParentTraitPatcher;
use Humbug\PhpScoper\Patcher\SymfonyPatcher;
use PhpParser\PhpVersion;
use SplFileInfo;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_unique;
use function array_unshift;
use function bin2hex;
use function dirname;
use function file_exists;
use function Humbug\PhpScoper\chain;
use function is_array;
use function is_callable;
use function is_dir;
use function is_file;
use function is_link;
use function is_readable;
use function is_string;
use function random_bytes;
use function readlink as native_readlink;
use function realpath;
use function Safe\file_get_contents;
use function trim;
use const DIRECTORY_SEPARATOR;
final readonly class ConfigurationFactory
{
public const DEFAULT_FILE_NAME = 'scoper.inc.php';
public function __construct(
private Filesystem $fileSystem,
private SymbolsConfigurationFactory $symbolsConfigurationFactory,
) {
}
/**
* @param non-empty-string|null $path Absolute canonical path to the configuration file.
* @param list<non-empty-string> $paths List of absolute canonical paths to append besides the one configured
*
* @throws InvalidConfiguration
*/
public function create(?string $path = null, array $paths = []): Configuration
{
$config = null === $path ? [] : $this->loadConfigFile($path);
self::validateConfigKeys($config);
$prefix = self::retrievePrefix($config);
$outputDir = self::retrieveOutputDir($config);
$excludedFiles = null === $path
? []
: $this->retrieveExcludedFiles(
dirname($path),
$config,
);
$patchers = self::retrievePatchers($config);
array_unshift($patchers, new SymfonyPatcher());
array_unshift($patchers, new SymfonyParentTraitPatcher());
array_unshift($patchers, new ComposerPatcher());
$symbolsConfiguration = $this->symbolsConfigurationFactory->createSymbolsConfiguration($config);
$finders = self::retrieveFinders($config);
$filesFromPaths = self::retrieveFilesFromPaths($paths);
$filesWithContents = self::retrieveFilesWithContents(chain($filesFromPaths, ...$finders));
return new Configuration(
$path,
$outputDir,
$prefix,
self::retrievePhpVersion($config),
$filesWithContents,
self::retrieveFilesWithContents($excludedFiles),
new PatcherChain($patchers),
$symbolsConfiguration,
);
}
/**
* @param string[] $paths
*/
public function createWithPaths(Configuration $config, array $paths): Configuration
{
$filesWithContents = self::retrieveFilesWithContents(
chain(
self::retrieveFilesFromPaths(
array_unique($paths),
),
),
);
return $config->withFilesWithContents([
...$config->getFilesWithContents(),
...$filesWithContents,
]);
}
public function createWithPrefix(Configuration $config, string $prefix): Configuration
{
$prefix = self::retrievePrefix([ConfigurationKeys::PREFIX_KEYWORD => $prefix]);
return $config->withPrefix($prefix);
}
/**
* @throws InvalidConfigurationValue
*/
private function loadConfigFile(string $path): array
{
if (!$this->fileSystem->isAbsolutePath($path)) {
throw InvalidConfigurationFile::forNonAbsolutePath($path);
}
if (!file_exists($path)) {
throw InvalidConfigurationFile::forFileNotFound($path);
}
$isADirectoryLink = is_link($path)
&& false !== native_readlink($path)
&& is_file(native_readlink($path));
if (!$isADirectoryLink && !is_file($path)) {
throw InvalidConfigurationFile::forNotAFile($path);
}
$config = include $path;
if (!is_array($config)) {
throw InvalidConfigurationFile::forInvalidValue($path);
}
return $config;
}
private static function validateConfigKeys(array $config): void
{
array_map(
ConfigurationKeys::assertIsValidKey(...),
array_keys($config),
);
}
/**
* @return non-empty-string
*/
private static function retrievePrefix(array $config): string
{
$prefix = trim((string) ($config[ConfigurationKeys::PREFIX_KEYWORD] ?? ''));
return '' === $prefix ? self::generateRandomPrefix() : $prefix;
}
/**
* @throws InvalidConfigurationValue
*/
private static function retrievePhpVersion(array $config): ?PhpVersion
{
$stringVersion = $config[ConfigurationKeys::PHP_VERSION_KEYWORD] ?? null;
if (null === $stringVersion || '' === $stringVersion) {
return null;
}
if (!is_string($stringVersion)) {
throw InvalidConfigurationValue::forInvalidPhpVersionType($stringVersion);
}
try {
return PhpVersion::fromString($stringVersion);
} catch (Exception $exception) {
throw InvalidConfigurationValue::forInvalidPhpVersion($stringVersion, $exception);
}
}
/**
* @return non-empty-string|null
*/
private static function retrieveOutputDir(array $config): ?string
{
$outputDir = trim((string) ($config[ConfigurationKeys::OUTPUT_DIR_KEYWORD] ?? ''));
return '' === $outputDir ? null : $outputDir;
}
/**
* @throws InvalidConfigurationValue
*
* @return array<(callable(string,string,string): string)|Patcher>
*/
private static function retrievePatchers(array $config): array
{
if (!array_key_exists(ConfigurationKeys::PATCHERS_KEYWORD, $config)) {
return [];
}
$patchers = $config[ConfigurationKeys::PATCHERS_KEYWORD];
if (!is_array($patchers)) {
throw InvalidConfigurationValue::forInvalidPatchersType($patchers);
}
foreach ($patchers as $index => $patcher) {
if (!is_callable($patcher)) {
throw InvalidConfigurationValue::forInvalidPatcherType($index, $patcher);
}
}
return $patchers;
}
/**
* @throws InvalidConfigurationValue
*
* @return string[] Absolute paths
*/
private function retrieveExcludedFiles(string $dirPath, array $config): array
{
if (!array_key_exists(ConfigurationKeys::EXCLUDED_FILES_KEYWORD, $config)) {
return [];
}
$excludedFiles = $config[ConfigurationKeys::EXCLUDED_FILES_KEYWORD];
if (!is_array($excludedFiles)) {
throw InvalidConfigurationValue::forInvalidExcludedFilesTypes($excludedFiles);
}
foreach ($excludedFiles as $index => $file) {
if (!is_string($file)) {
throw InvalidConfigurationValue::forInvalidExcludedFilePath($index, $excludedFiles);
}
if (!$this->fileSystem->isAbsolutePath($file)) {
$file = $dirPath.DIRECTORY_SEPARATOR.$file;
}
unset( $excludedFiles[$index] );
$fileKey = str_replace( $dirPath.DIRECTORY_SEPARATOR, '', $file );
$file = realpath($file);
$excludedFiles[$fileKey] = $file;
}
// We ignore files not found excluded file as we do not want to bail out just because a file we do not want to
// include does not exist.
return array_filter($excludedFiles);
}
/**
* @throws InvalidConfigurationValue
*
* @return Finder[]
*/
private static function retrieveFinders(array $config): array
{
if (!array_key_exists(ConfigurationKeys::FINDER_KEYWORD, $config)) {
return [];
}
$finders = $config[ConfigurationKeys::FINDER_KEYWORD];
if (!is_array($finders)) {
throw InvalidConfigurationValue::forInvalidFinderTypes($finders);
}
foreach ($finders as $index => $finder) {
if ($finder instanceof Finder) {
continue;
}
throw InvalidConfigurationValue::forInvalidFinderType($index, $finder);
}
return $finders;
}
/**
* @param string[] $paths
*
* @throws InvalidConfigurationValue
*
* @return iterable<SplFileInfo>
*/
private static function retrieveFilesFromPaths(array $paths): iterable
{
if ([] === $paths) {
return [];
}
$pathsToSearch = [];
$filesToAppend = [];
foreach ($paths as $path) {
if (!file_exists($path)) {
throw InvalidConfigurationValue::forFileNotFound($path);
}
if (is_dir($path)) {
$pathsToSearch[] = $path;
} else {
$filesToAppend[] = $path;
}
}
$finder = new Finder();
$finder->files()
->in($pathsToSearch)
->append($filesToAppend)
->filter(
static fn (SplFileInfo $fileInfo) => !$fileInfo->isLink(),
)
->sortByName();
return $finder;
}
/**
* @param iterable<SplFileInfo|string> $files
*
* @throws InvalidConfigurationValue
*
* @return array<string, array{string, string}> Array of tuple with the first argument being the file path and the second its contents
*/
private static function retrieveFilesWithContents(iterable $files): array
{
$filesWithContents = [];
foreach ($files as $fileKey => $filePathOrFileInfo) {
$filePath = $filePathOrFileInfo instanceof SplFileInfo
? $filePathOrFileInfo->getRealPath()
: realpath($filePathOrFileInfo);
if (!$filePath) {
throw InvalidConfigurationValue::forFileNotFound((string) $filePathOrFileInfo);
}
if (!is_readable($filePath)) {
throw InvalidConfigurationValue::forUnreadableFile($filePath);
}
$filesWithContents[$fileKey] = [$filePath, file_get_contents($filePath)];
}
return $filesWithContents;
}
/**
* @return non-empty-string
*/
private static function generateRandomPrefix(): string
{
return '_PhpScoper'.bin2hex(random_bytes(6));
}
}