-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathComposerPackageManager.php
More file actions
717 lines (647 loc) · 25.1 KB
/
ComposerPackageManager.php
File metadata and controls
717 lines (647 loc) · 25.1 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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
<?php
declare(strict_types=1);
namespace TYPO3\TestingFramework\Composer;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use Composer\InstalledVersions;
use TYPO3\TestingFramework\Core\Functional\FunctionalTestCase;
/**
* `typo3/testing-framework` internal composer package manager, used to gather source
* information of extensions already loaded by the root composer installation with
* the additional ability to register test fixture packages and extensions during
* runtime to create {@see FunctionalTestCase} test instances and provide symlinks
* of extensions into the classic mode test instance or retrieve files from a composer
* package or extension unrelated where they are placed on the filesystem.
*
* - {@see Testbase::setUpInstanceCoreLinks()}
* - {@see Testbase::linkTestExtensionsToInstance()}
* - {@see Testbase::linkFrameworkExtensionsToInstance()}
* - {@see Testbase::setUpLocalConfiguration()}
* - {@see Testbase::setUpPackageStates()}
*
* @internal This class is for testing-framework internal processing and not part of public testing API.
*/
final class ComposerPackageManager
{
/**
* The number of buffer entries that triggers a cleanup operation.
*/
private const CLEANUP_THRESHOLD = 1250;
/**
* The buffer size after the cleanup operation.
*/
private const CLEANUP_SIZE = 1000;
/**
* Buffers input/output of {@link canonicalize()}.
*
* @var array<string, string>
*/
private static array $buffer = [];
private static int $bufferSize = 0;
private static string $vendorPath = '';
private static string $publicPath = '';
private static ?PackageInfo $rootPackage = null;
/**
* @var array<string, PackageInfo>
*/
private static array $packages = [];
/**
* @var array<non-empty-string, non-empty-string>
*/
private static array $extensionKeyToPackageNameMap = [];
public function __construct()
{
// @todo Remove this from the constructor.
$this->build();
}
/**
* Get composer package information {@see PackageInfo} for `$nameOrExtensionKeyOrPath`.
*/
public function getPackageInfoWithFallback(string $nameOrExtensionKeyOrPath): ?PackageInfo
{
if ($packageInfo = $this->getPackageInfo($nameOrExtensionKeyOrPath)) {
return $packageInfo;
}
if ($packageInfo = $this->getPackageFromPath($nameOrExtensionKeyOrPath)) {
return $packageInfo;
}
if ($packageInfo = $this->getPackageFromPathFallback($nameOrExtensionKeyOrPath)) {
return $packageInfo;
}
return null;
}
/**
* Get {@see PackageInfo} for package name or extension key `$name`.
*/
public function getPackageInfo(string $name): ?PackageInfo
{
return self::$packages[$name] ?? self::$packages[$this->resolvePackageName($name)] ?? null;
}
/**
* Get list of system extensions keys. We need this as fallback if no core extensions are selected to be symlinked.
*
* @return string[]
*/
public function getSystemExtensionExtensionKeys(): array
{
$extensionKeys = [];
foreach (self::$packages as $packageInfo) {
if ($packageInfo->isSystemExtension()
&& $packageInfo->getExtensionKey() !== ''
) {
$extensionKeys[] = $packageInfo->getExtensionKey();
}
}
return $extensionKeys;
}
public function getRootPath(): string
{
return $this->rootPackage()->getRealPath();
}
/**
* Get full vendor path
*/
public function getVendorPath(): string
{
return self::$vendorPath;
}
public function getPublicPath(): string
{
return self::$publicPath;
}
/**
* Build package caches if not already done.
*/
private function build(): void
{
if (self::$rootPackage instanceof PackageInfo) {
return;
}
$this->processRootPackage();
$this->processMonoRepository();
$this->processPackages();
}
/**
* Extract root package information. This must be done first, to have related information at hand for subsequent
* package information retrieval.
*/
private function processRootPackage(): void
{
$package = InstalledVersions::getRootPackage();
$packageName = $package['name'];
$packagePath = $this->getPackageInstallPath($packageName);
$packageRealPath = $this->realPath($packagePath);
$info = $this->getPackageComposerJson($packagePath);
$packageType = $info['type'] ?? '';
$extEmConf = $this->getExtEmConf($packagePath);
$extensionKey = $this->determineExtensionKey($packagePath, $info, $extEmConf);
$packageInfo = new PackageInfo(
$packageName,
$packageType,
$packagePath,
$packageRealPath,
$package['pretty_version'],
$extensionKey,
$info,
$extEmConf
);
self::$rootPackage = $packageInfo;
$this->addPackageInfo($packageInfo);
// If root-package is the testing-framework itself, we add it as fake extension_key for unit-tests related
// to composer package manager to test properly for extension testing level.
if ($packageInfo->getName() === 'typo3/testing-framework') {
self::$extensionKeyToPackageNameMap['testing_framework'] = 'typo3/testing-framework';
}
self::$vendorPath = $this->realPath(
rtrim(
$packageInfo->getRealPath() . '/' . ($packageInfo->getVendorDir() ?: 'vendor'),
'/'
)
);
self::$publicPath = $this->realPath(
rtrim(
$packageInfo->getRealPath() . '/' . ($packageInfo->getWebDir() ?: ''),
'/'
)
);
}
private function getPackageFromPathFallback(string $path): ?PackageInfo
{
$path = $this->sanitizePath($path);
if (str_contains($path, '..')
&& !str_starts_with($path, '/')
) {
$path = rtrim($this->rootPackage()->getRealPath() . '/' . $this->rootPackage()->getWebDir(), '/') . '/' . $path;
$path = $this->canonicalize(rtrim(strtr($path, '\\', '/'), '/'));
}
$containsLegacySystemExtensionPath = str_contains($path, 'typo3/sysext/ext/');
$containsLegacyExtensionPath = str_contains($path, 'typo3conf/ext/');
if ($containsLegacyExtensionPath || $containsLegacySystemExtensionPath) {
$path = $this->removePrefixPaths($path);
}
$matches = [];
if (preg_match('/typo3\/sysext\/[\w]+/', $path, $matches) === 1) {
$extensionKey = $this->getFirstPathElement(substr($path, mb_strlen('typo3/sysext/')));
if ($extensionPackageInfo = $this->getPackageInfo($extensionKey)) {
if (rtrim($path, '/') === 'typo3/sysext/' . $extensionKey) {
return $extensionPackageInfo;
}
$path = $extensionPackageInfo->getRealPath() . '/' . substr($path, mb_strlen('typo3/sysext/' . $extensionKey . '/'));
}
}
if (preg_match('/typo3conf\/ext\/[\w]+/', $path, $matches) === 1) {
$extensionKey = $this->getFirstPathElement(substr($path, mb_strlen('typo3conf/ext/')));
if ($extensionPackageInfo = $this->getPackageInfo($extensionKey)) {
if (rtrim($path, '/') === 'typo3conf/ext/' . $extensionKey) {
return $extensionPackageInfo;
}
$path = $extensionPackageInfo->getRealPath() . '/' . substr($path, mb_strlen('typo3conf/ext/' . $extensionKey . '/'));
}
}
if ($packageInfo = $this->getPackageFromPath($path)) {
return $packageInfo;
}
// @todo Validate if there are additional cases which should be handled as fallback.
return null;
}
private function getPackageFromPath(string $path): ?PackageInfo
{
$path = $this->sanitizePath($path);
$path = rtrim($path);
if (!is_dir($path)) {
return null;
}
$info = $this->getPackageComposerJson($path);
$extEmConf = $this->getExtEmConf($path);
$extensionKey = $this->determineExtensionKey($path, $info, $extEmConf);
$packageName = $info['name'] ?? $this->normalizePackageName($extensionKey);
$packageType = $info['type'] ?? ($extEmConf !== null ? 'typo3-cms-extension' : '');
if ($packageInfo = $this->getPackageInfo($packageName)) {
return $packageInfo;
}
if ($packageInfo = $this->getPackageInfo($extensionKey)) {
return $packageInfo;
}
$packageInfo = new PackageInfo(
$packageName,
$packageType,
$path,
$this->realPath($path),
// System extensions in mono-repository are exactly the same version as the root package. Use it.
$this->rootPackage()->getVersion(),
$extensionKey,
$info,
$extEmConf,
);
$this->addPackageInfo($packageInfo);
return $packageInfo;
}
/**
* TYPO3 Core Development Mono Repository has a special setup, where the system extension are not required by the
* root composer.json. Therefore, we need to look them up manually to add corresponding package information. This
* allows us to handle system extensions in mono repository they same way as outside and make e.g. symlink system
* extensions to test instance simpler by eliminating the need for dedicated mono-repository handling there.
*/
private function processMonoRepository(): void
{
if (!($this->rootPackage()?->isMonoRepository() ?? false)) {
return;
}
$systemExtensionComposerJsonFiles = glob($this->rootPackage()->getRealPath() . '/typo3/sysext/*/composer.json');
foreach ($systemExtensionComposerJsonFiles as $systemExtensionComposerJsonFile) {
$packagePath = dirname($systemExtensionComposerJsonFile);
$packageRealPath = $this->realPath($packagePath);
$info = $this->getPackageComposerJson($packageRealPath);
$packageName = $info['name'] ?? '';
$packageType = $info['type'] ?? '';
$extEmConf = $this->getExtEmConf($packageRealPath);
$extensionKey = $this->determineExtensionKey($packageRealPath, $info, $extEmConf);
$packageInfo = new PackageInfo(
$packageName,
$packageType,
$packagePath,
$packageRealPath,
// System extensions in mono-repository are exactly the same version as the root package. Use it.
$this->rootPackage()->getVersion(),
$extensionKey,
$info,
$extEmConf,
);
if (!$packageInfo->isSystemExtension()) {
continue;
}
$this->addPackageInfo($packageInfo);
}
}
/**
* Process all composer installed packages.
*/
private function processPackages(): void
{
foreach (InstalledVersions::getAllRawData() as $loader) {
foreach ($loader['versions'] as $packageName => $version) {
// We ignore replaced packages. The replacing package adds them with the final package info directly.
if (($version['replaced'] ?? false)
&& $version['replaced'] !== []
) {
continue;
}
$packagePath = $this->getPackageInstallPath($packageName);
$packageRealPath = $this->realPath($packagePath);
$info = $this->getPackageComposerJson($packagePath);
$extEmConf = $this->getExtEmConf($packagePath);
$packageType = $info['type'] ?? '';
$extensionKey = $this->determineExtensionKey($packagePath, $info, $extEmConf);
$this->addPackageInfo(new PackageInfo(
$packageName,
$packageType,
$packagePath,
$packageRealPath,
(string)($version['pretty_version'] ?? $this->prettifyVersion($extEmConf['version'] ?? '')),
$extensionKey,
$info,
$extEmConf
));
}
}
}
/**
* Adds the package information to the internal cache. Additionally, it sets the extensionKey to packageName
* map information, if a TYPO3 extension or system-extensions package information is handed over. This map
* is used to allow extensionKey or packageName for retrieving package information, which comes in handy to
* provide backward compatibility for test core- and test extension symlink configuration per test instance.
*/
private function addPackageInfo(PackageInfo $packageInfo): void
{
if (self::$packages[$packageInfo->getName()] ?? null) {
return;
}
self::$packages[$packageInfo->getName()] = $packageInfo;
if ($packageInfo->getExtensionKey() !== '') {
self::$extensionKeyToPackageNameMap[$packageInfo->getExtensionKey()] = $packageInfo->getName();
}
foreach ($packageInfo->getReplacesPackageNames() as $replacedPackageName) {
self::$packages[$replacedPackageName] = $packageInfo;
if ($packageInfo->isExtension() || $packageInfo->isSystemExtension()) {
$extensionKey = basename($replacedPackageName);
if (str_starts_with($extensionKey, 'cms-')) {
$extensionKey = substr($extensionKey, 4);
}
$extensionKey = $this->normalizeExtensionKey($extensionKey);
self::$extensionKeyToPackageNameMap[$extensionKey] = $replacedPackageName;
}
}
}
private function rootPackage(): ?PackageInfo
{
return self::$rootPackage;
}
private function getPackageComposerJson(string $path): ?array
{
if ($path === '') {
return null;
}
$composerFile = rtrim($path, '/') . '/composer.json';
if (!file_exists($composerFile) || !is_readable($composerFile)) {
return null;
}
try {
return json_decode((string)file_get_contents($composerFile), true, JSON_THROW_ON_ERROR);
} catch (\Throwable) {
// skipped
}
return null;
}
private function getExtEmConf(string $path): ?array
{
if ($path === '') {
return null;
}
$extEmConfFile = rtrim($path, '/') . '/ext_emconf.php';
if (!file_exists($extEmConfFile) || !is_readable($extEmConfFile)) {
return null;
}
try {
/** @var array<non-empty-string, array> $EM_CONF */
$EM_CONF = [];
$_EXTKEY = '__EXTKEY__';
@include $extEmConfFile;
return $EM_CONF[$_EXTKEY] ?? null;
} catch (\Throwable) {
}
return null;
}
/**
* Returns resolved composer package name when $name is a known extension key
* for a known package, otherwise return $name unchanged.
*
* Used to determine the package name to look up as composer package within {@see self::$packages}
*
* Supports also relative classic mode notation:
*
* - typo3/sysext/backend
* - typo3conf/ext/my_ext_key
*
* {@see self::prepareResolvePackageName()} for details for normalisation.
*/
private function resolvePackageName(string $name): string
{
$name = $this->prepareResolvePackageName($name);
return self::$extensionKeyToPackageNameMap[$name] ?? $name;
}
/**
* Get the sanitized package installation path.
*
* Note: Not using realpath() is done by intention. That gives us the ability, to eventually avoid duplicates and
* act on both paths if needed.
*/
private function getPackageInstallPath(string $name): string
{
return $this->sanitizePath((string)InstalledVersions::getInstallPath($name));
}
/**
* This method resolves relative path tokens directly ( e.g. '/../' ) and sanitizes the path from back-slash to
* slash for a cross os compatibility.
*/
public function sanitizePath(string $path): string
{
$path = $this->canonicalize(rtrim(strtr($path, '\\', '/'), '/'));
return $path;
}
/**
* Guarded realpath() wrapper, to ensure we do not lose an path information if realpath() would fail.
*/
private function realPath(string $path): string
{
$path = $this->sanitizePath($path);
return realpath($path) ?: $path;
}
private function canonicalize(string $path): string
{
if ($path === '') {
return '';
}
// This method is called by many other methods in this class. Buffer
// the canonicalized paths to make up for the severe performance
// decrease.
if (isset(self::$buffer[$path])) {
return self::$buffer[$path];
}
$path = str_replace('\\', '/', $path);
[$root, $pathWithoutRoot] = $this->split($path);
$canonicalParts = $this->findCanonicalParts($root, $pathWithoutRoot);
// Add the root directory again
self::$buffer[$path] = $canonicalPath = $root . implode('/', $canonicalParts);
++self::$bufferSize;
// Clean up regularly to prevent memory leaks
if (self::$bufferSize > self::CLEANUP_THRESHOLD) {
self::$buffer = \array_slice(self::$buffer, -self::CLEANUP_SIZE, null, true);
self::$bufferSize = self::CLEANUP_SIZE;
}
return $canonicalPath;
}
private function split(string $path): array
{
if ($path === '') {
return ['', ''];
}
// Remember scheme as part of the root, if any
$schemeSeparatorPosition = strpos($path, '://');
if ($schemeSeparatorPosition !== false) {
$root = substr($path, 0, $schemeSeparatorPosition + 3);
$path = substr($path, $schemeSeparatorPosition + 3);
} else {
$root = '';
}
$length = \strlen($path);
// Remove and remember root directory
if (str_starts_with($path, '/')) {
$root .= '/';
$path = $length > 1 ? substr($path, 1) : '';
} elseif ($length > 1 && ctype_alpha($path[0]) && $path[1] === ':') {
if ($length === 2) {
// Windows special case: "C:"
$root .= $path . '/';
$path = '';
} elseif ($path[2] === '/') {
// Windows normal case: "C:/"..
$root .= substr($path, 0, 3);
$path = $length > 3 ? substr($path, 3) : '';
}
}
return [$root, $path];
}
private function findCanonicalParts(string $root, string $pathWithoutRoot): array
{
$parts = explode('/', $pathWithoutRoot);
$canonicalParts = [];
// Collapse "." and "..", if possible
foreach ($parts as $part) {
if ($part === '.'
|| $part === ''
) {
continue;
}
// Collapse ".." with the previous part, if one exists
// Don't collapse ".." if the previous part is also ".."
if ($part === '..'
&& \count($canonicalParts) > 0
&& $canonicalParts[\count($canonicalParts) - 1] !== '..'
) {
array_pop($canonicalParts);
continue;
}
// Only add ".." prefixes for relative paths
if ($part !== '..'
|| $root === ''
) {
$canonicalParts[] = $part;
}
}
return $canonicalParts;
}
private function determineExtensionKey(
string $packagePath,
?array $info = null,
?array $extEmConf = null
): string {
$isComposerExtensionType = ($info !== null && array_key_exists('type', $info) && is_string($info['type']) && in_array($info['type'], ['typo3-cms-framework', 'typo3-cms-extension'], true));
$hasExtEmConf = $extEmConf !== null;
if (!($isComposerExtensionType || $hasExtEmConf)) {
return '';
}
$hasComposerExtensionKey = (
is_array($info)
&& isset($info['extra']['typo3/cms']['extension-key'])
&& is_string($info['extra']['typo3/cms']['extension-key'])
&& $info['extra']['typo3/cms']['extension-key'] !== ''
);
if ($hasComposerExtensionKey) {
return $info['extra']['typo3/cms']['extension-key'];
}
$baseName = basename($packagePath);
if (($info['type'] ?? '') === 'typo3-csm-framework'
&& str_starts_with($baseName, 'cms-')
) {
// remove `cms-` prefix
$baseName = substr($baseName, 4);
}
$baseName = $this->normalizeExtensionKey($baseName);
return $info['extra']['typo3/cms']['extension-key'] ?? $baseName;
}
private function normalizeExtensionKey(string $extensionKey): string
{
$replaces = [
'-' => '_',
];
return str_replace(
array_keys($replaces),
array_values($replaces),
$extensionKey
);
}
private function normalizePackageName(string $packageName): string
{
if (!str_contains($packageName, '/')) {
$packageName = 'unknown-vendor/' . $packageName;
}
$replaces = [
'_' => '-',
];
return str_replace(
array_keys($replaces),
array_values($replaces),
$packageName
);
}
private function prettifyVersion(string $version): string
{
if ($version === '') {
return '';
}
$parts = array_pad(explode('.', $version), 3, '0');
return implode(
'.',
[
$parts[0] ?? '0',
$parts[1] ?? '0',
$parts[2] ?? '0',
],
);
}
private function removePrefixPaths(string $path): string
{
$removePaths = [
rtrim($this->getPublicPath(), '/') . '/',
rtrim($this->getVendorPath(), '/') . '/',
rtrim($this->rootPackage()->getVendorDir(), '/') . '/',
rtrim($this->rootPackage()->getWebDir(), '/') . '/',
rtrim($this->getRootPath(), '/') . '/',
];
foreach ($removePaths as $removePath) {
if (str_starts_with($path, $removePath)) {
$path = substr($path, mb_strlen($removePath));
}
}
return ltrim($path, '/');
}
private function getFirstPathElement(string $path): string
{
if ($path === '') {
return '';
}
return explode('/', $path)[0] ?? '';
}
/**
* Extension can be specified with their composer name, extension key or with classic mode relative path
* prefixes (`typo3/sysext/<extensionkey>` or `typo3conf/ext/<extensionkey>`) for functional tests to
* configure which extension should be provided in the test instance.
*
* This method normalizes a handed over name by removing the specified extra information, so it can be
* used to resolve it either as direct package name or as extension name.
*
* Handed over value also removes known environment prefix paths, like the full path to the root (project rook),
* vendor folder or web folder using {@see self::removePrefixPaths()} which is safe, as this method is and most
* only be used for {@see self::resolvePackageName()} to find a composer package in {@see self::$packages}, after
* mapping extension-key to composer package name.
*
* Example for processed changes:
* -----------------------------_
*
* - typo3/sysext/backend => backend
* - typo3conf/ext/my_ext_key => my_ext_key
*
* Example not processed values:
* -----------------------------
*
* valid names
* - typo3/cms-core => typo3/cms-core
* - my-vendor/my-package-name => my-vendor/my-package-name
* - my-package-name-without-vendor => my-package-name-without-vendor
*/
private function prepareResolvePackageName($name): string
{
$name = trim($this->removePrefixPaths($name), '/');
$relativePrefixPaths = [
'typo3/sysext/',
'typo3conf/ext/',
];
foreach ($relativePrefixPaths as $relativePrefixPath) {
if (!str_starts_with($name, $relativePrefixPath)) {
continue;
}
$name = substr($name, mb_strlen($relativePrefixPath));
}
return $name;
}
}