Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
16.07% |
18 / 112 |
|
16.67% |
1 / 6 |
CRAP | |
0.00% |
0 / 1 |
| DumpAutoload | |
16.07% |
18 / 112 |
|
16.67% |
1 / 6 |
148.02 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
1 | |||
| generatedPrefixedAutoloader | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
2 | |||
| generatedMainAutoloader | |
0.00% |
0 / 50 |
|
0.00% |
0 / 1 |
56 | |||
| createInstalledVersionsFiles | |
92.86% |
13 / 14 |
|
0.00% |
0 / 1 |
2.00 | |||
| prefixNewAutoloader | |
0.00% |
0 / 37 |
|
0.00% |
0 / 1 |
6 | |||
| getSuffix | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace BrianHenryIE\Strauss\Pipeline\Autoload; |
| 4 | |
| 5 | use BrianHenryIE\Strauss\Composer\ComposerPackage; |
| 6 | use BrianHenryIE\Strauss\Files\File; |
| 7 | use BrianHenryIE\Strauss\Config\AutoloadConfigInterface; |
| 8 | use BrianHenryIE\Strauss\Helpers\FileSystem; |
| 9 | use BrianHenryIE\Strauss\Pipeline\FileEnumerator; |
| 10 | use BrianHenryIE\Strauss\Pipeline\Prefixer; |
| 11 | use BrianHenryIE\Strauss\Types\DiscoveredSymbols; |
| 12 | use BrianHenryIE\Strauss\Types\NamespaceSymbol; |
| 13 | use Composer\Autoload\AutoloadGenerator; |
| 14 | use Composer\Config; |
| 15 | use Composer\Factory; |
| 16 | use Composer\IO\NullIO; |
| 17 | use Composer\Json\JsonFile; |
| 18 | use Composer\Repository\InstalledFilesystemRepository; |
| 19 | use League\Flysystem\FilesystemException; |
| 20 | use Psr\Log\LoggerAwareTrait; |
| 21 | use Psr\Log\LoggerInterface; |
| 22 | use Seld\JsonLint\ParsingException; |
| 23 | |
| 24 | /** |
| 25 | * @phpstan-import-type ComposerJsonArray from ComposerPackage |
| 26 | */ |
| 27 | class DumpAutoload |
| 28 | { |
| 29 | use LoggerAwareTrait; |
| 30 | |
| 31 | protected AutoloadConfigInterface $config; |
| 32 | |
| 33 | protected FileSystem $filesystem; |
| 34 | |
| 35 | protected Prefixer $projectReplace; |
| 36 | |
| 37 | protected FileEnumerator $fileEnumerator; |
| 38 | |
| 39 | public function __construct( |
| 40 | AutoloadConfigInterface $config, |
| 41 | Filesystem $filesystem, |
| 42 | LoggerInterface $logger, |
| 43 | Prefixer $projectReplace, |
| 44 | FileEnumerator $fileEnumerator |
| 45 | ) { |
| 46 | $this->config = $config; |
| 47 | $this->filesystem = $filesystem; |
| 48 | $this->setLogger($logger); |
| 49 | $this->projectReplace = $projectReplace; |
| 50 | $this->fileEnumerator = $fileEnumerator; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Create `autoload.php` and the `vendor-prefixed/composer` directory. |
| 55 | * @throws ParsingException |
| 56 | * @throws FilesystemException |
| 57 | */ |
| 58 | public function generatedPrefixedAutoloader(): void |
| 59 | { |
| 60 | $this->generatedMainAutoloader(); |
| 61 | |
| 62 | $this->createInstalledVersionsFiles(); |
| 63 | |
| 64 | $this->prefixNewAutoloader(); |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * Uses `vendor/composer/installed.json` to output autoload files to `vendor-prefixed/composer`. |
| 69 | * |
| 70 | * @throws ParsingException |
| 71 | * @throws FilesystemException |
| 72 | */ |
| 73 | protected function generatedMainAutoloader(): void |
| 74 | { |
| 75 | /** |
| 76 | * Unfortunately, `::dump()` creates the target directories if they don't exist, even though it otherwise respects `::setDryRun()`. |
| 77 | * |
| 78 | * {@see https://github.com/composer/composer/pull/12396} might fix this. |
| 79 | */ |
| 80 | if ($this->config->isDryRun()) { |
| 81 | return; |
| 82 | } |
| 83 | |
| 84 | $relativeTargetDir = $this->filesystem->getRelativePath( |
| 85 | $this->config->getProjectDirectory(), |
| 86 | $this->config->getTargetDirectory() |
| 87 | ); |
| 88 | |
| 89 | $defaultVendorDirBefore = Config::$defaultConfig['vendor-dir']; |
| 90 | Config::$defaultConfig['vendor-dir'] = $relativeTargetDir; |
| 91 | |
| 92 | $projectComposerJson = new JsonFile($this->config->getProjectDirectory() . Factory::getComposerFile()); |
| 93 | |
| 94 | /** @var ComposerJsonArray $projectComposerJsonArray */ |
| 95 | $projectComposerJsonArray = $projectComposerJson->read(); |
| 96 | if (isset($projectComposerJsonArray['config'], $projectComposerJsonArray['config']['vendor-dir'])) { |
| 97 | $projectComposerJsonArray['config']['vendor-dir'] = $relativeTargetDir; |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * Loop over all packages that should be included and ensure the root package requires them. Composer only |
| 102 | * includes packages in the autoloader that are required by a parent package (including root). Without this, |
| 103 | * packages that are selectively prefixed are not included in the autoloader. |
| 104 | * |
| 105 | * @see AutoloadGenerator::filterPackageMap() |
| 106 | */ |
| 107 | foreach ($this->config->getPackagesToPrefix() as $name => $package) { |
| 108 | $projectComposerJsonArray['require'][$name] = '*'; |
| 109 | } |
| 110 | |
| 111 | // Include the project root autoload in the vendor-prefixed autoloader? |
| 112 | if (isset($projectComposerJsonArray['autoload']) && !$this->config->isIncludeRootAutoload()) { |
| 113 | $projectComposerJsonArray['autoload'] = []; |
| 114 | } |
| 115 | |
| 116 | $composer = Factory::create(new NullIO(), $projectComposerJsonArray); |
| 117 | $installationManager = $composer->getInstallationManager(); |
| 118 | $package = $composer->getPackage(); |
| 119 | |
| 120 | /** |
| 121 | * Cannot use `$composer->getConfig()`, need to create a new one so the `vendor-dir` is correct. |
| 122 | */ |
| 123 | $config = new Config(false, $this->config->getProjectDirectory()); |
| 124 | |
| 125 | /** @var array{config?: array<string, mixed>} $projectComposerConfigMergeArray */ |
| 126 | $projectComposerConfigMergeArray = ['config' => $projectComposerJsonArray['config'] ?? []]; |
| 127 | |
| 128 | $config->merge($projectComposerConfigMergeArray); |
| 129 | |
| 130 | $generator = new ComposerAutoloadGenerator( |
| 131 | $this->config->getNamespacePrefix(), |
| 132 | $composer->getEventDispatcher() |
| 133 | ); |
| 134 | |
| 135 | $generator->setDryRun($this->config->isDryRun()); |
| 136 | $generator->setClassMapAuthoritative(true); |
| 137 | $generator->setRunScripts(false); |
| 138 | // $generator->setApcu($apcu, $apcuPrefix); |
| 139 | // $generator->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)); |
| 140 | $optimize = true; // $input->getOption('optimize') || $config->get('optimize-autoloader'); |
| 141 | |
| 142 | $installedJsonFile = new JsonFile($this->config->getTargetDirectory() . 'composer/installed.json'); |
| 143 | /** @var array{dev?:bool} $installedJson */ |
| 144 | $installedJson = $installedJsonFile->read(); |
| 145 | $localRepo = new InstalledFilesystemRepository($installedJsonFile); |
| 146 | |
| 147 | /** |
| 148 | * If the target directory is different to the vendor directory, then we do not want to include dev |
| 149 | * dependencies, but if it is vendor, then unless composer install was run with --no-dev, we do want them. |
| 150 | */ |
| 151 | if ($this->config->getVendorDirectory() !== $this->config->getTargetDirectory()) { |
| 152 | $isDevMode = false; |
| 153 | } else { |
| 154 | $isDevMode = (bool) ($installedJson['dev'] ?? false); |
| 155 | } |
| 156 | $generator->setDevMode($isDevMode); |
| 157 | |
| 158 | $strictAmbiguous = false; // $input->getOption('strict-ambiguous') |
| 159 | |
| 160 | // This will output the autoload_static.php etc. files to `vendor-prefixed/composer`. |
| 161 | $generator->dump( |
| 162 | $config, |
| 163 | $localRepo, |
| 164 | $package, |
| 165 | $installationManager, |
| 166 | 'composer', |
| 167 | $optimize, |
| 168 | $this->getSuffix(), |
| 169 | $composer->getLocker(), |
| 170 | $strictAmbiguous |
| 171 | ); |
| 172 | |
| 173 | /** |
| 174 | * Tests fail if this is absent. |
| 175 | * |
| 176 | * Arguably this should be in ::setUp() and tearDown() in the test classes, but if other tools run after Strauss |
| 177 | * then they might expect it to be unmodified. |
| 178 | */ |
| 179 | Config::$defaultConfig['vendor-dir'] = $defaultVendorDirBefore; |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Create `InstalledVersions.php` and `installed.php`. |
| 184 | * |
| 185 | * This file is copied in all Composer installations. |
| 186 | * It is added always in `ComposerAutoloadGenerator::dump()`, called above. |
| 187 | * If the file does not exist, its entry in the classmap will not be prefixed and will cause autoloading issues for the real class. |
| 188 | * |
| 189 | * The accompanying `installed.php` is unique per install. Copy it and filter its packages to the packages that was copied. |
| 190 | * @throws FilesystemException |
| 191 | */ |
| 192 | protected function createInstalledVersionsFiles(): void |
| 193 | { |
| 194 | if ($this->config->getVendorDirectory() === $this->config->getTargetDirectory()) { |
| 195 | return; |
| 196 | } |
| 197 | |
| 198 | $this->filesystem->copy($this->config->getVendorDirectory() . '/composer/InstalledVersions.php', $this->config->getTargetDirectory() . 'composer/InstalledVersions.php'); |
| 199 | |
| 200 | // This is just `<?php return array(...);` |
| 201 | $installedPhpString = $this->filesystem->read($this->config->getVendorDirectory() . '/composer/installed.php'); |
| 202 | $installed = eval(str_replace('<?php', '', $installedPhpString)); |
| 203 | |
| 204 | $targetPackages = $this->config->getPackagesToCopy(); |
| 205 | $targetPackagesNames = array_keys($targetPackages); |
| 206 | |
| 207 | $installed['versions'] = array_filter($installed['versions'], function ($packageName) use ($targetPackagesNames) { |
| 208 | return in_array($packageName, $targetPackagesNames); |
| 209 | }, ARRAY_FILTER_USE_KEY); |
| 210 | |
| 211 | $installedArrayString = var_export($installed, true); |
| 212 | |
| 213 | $newInstalledPhpString = "<?php return $installedArrayString;"; |
| 214 | |
| 215 | // Update `__DIR__` which was evaluated during the `include`/`eval`. |
| 216 | $newInstalledPhpString = preg_replace('/(\'install_path\' => )(.*)(\/\.\..*)/', "$1__DIR__ . '$3", $newInstalledPhpString); |
| 217 | |
| 218 | $this->filesystem->write($this->config->getTargetDirectory() . '/composer/installed.php', $newInstalledPhpString); |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * @throws FilesystemException |
| 223 | */ |
| 224 | protected function prefixNewAutoloader(): void |
| 225 | { |
| 226 | if ($this->config->getVendorDirectory() === $this->config->getTargetDirectory()) { |
| 227 | return; |
| 228 | } |
| 229 | |
| 230 | $this->logger->debug('Prefixing the new Composer autoloader.'); |
| 231 | |
| 232 | $projectFiles = $this->fileEnumerator->compileFileListForPaths([ |
| 233 | $this->config->getTargetDirectory() . 'composer', |
| 234 | ]); |
| 235 | |
| 236 | $phpFiles = array_filter( |
| 237 | $projectFiles->getFiles(), |
| 238 | fn($file) => $file->isPhpFile() |
| 239 | ); |
| 240 | |
| 241 | $phpFilesAbsolutePaths = array_map( |
| 242 | fn($file) => $file->getSourcePath(), |
| 243 | $phpFiles |
| 244 | ); |
| 245 | |
| 246 | $sourceFile = new File(__DIR__, __DIR__); |
| 247 | $composerAutoloadNamespaceSymbol = new NamespaceSymbol( |
| 248 | 'Composer\\Autoload', |
| 249 | $sourceFile |
| 250 | ); |
| 251 | $composerAutoloadNamespaceSymbol->setReplacement( |
| 252 | $this->config->getNamespacePrefix() . '\\Composer\\Autoload' |
| 253 | ); |
| 254 | $composerNamespaceSymbol = new NamespaceSymbol( |
| 255 | 'Composer', |
| 256 | $sourceFile |
| 257 | ); |
| 258 | $composerNamespaceSymbol->setReplacement( |
| 259 | $this->config->getNamespacePrefix() . '\\Composer' |
| 260 | ); |
| 261 | |
| 262 | $discoveredSymbols = new DiscoveredSymbols(); |
| 263 | $discoveredSymbols->add( |
| 264 | $composerNamespaceSymbol |
| 265 | ); |
| 266 | $discoveredSymbols->add( |
| 267 | $composerAutoloadNamespaceSymbol |
| 268 | ); |
| 269 | |
| 270 | $this->projectReplace->replaceInProjectFiles($discoveredSymbols, $phpFilesAbsolutePaths); |
| 271 | } |
| 272 | |
| 273 | /** |
| 274 | * If there is an existing autoloader, it will use the same suffix. If there is not, it pulls the suffix from |
| 275 | * {Composer::getLocker()} and clashes with the existing autoloader. |
| 276 | * |
| 277 | * @see https://github.com/composer/composer/blob/ae208dc1e182bd45d99fcecb956501da212454a1/src/Composer/Autoload/AutoloadGenerator.php#L429 |
| 278 | * @see AutoloadGenerator::dump() 412:431 |
| 279 | * @throws \Random\RandomException in PHP 8.2+ |
| 280 | * @throws FilesystemException |
| 281 | */ |
| 282 | protected function getSuffix(): ?string |
| 283 | { |
| 284 | return !$this->filesystem->fileExists($this->config->getTargetDirectory() . 'autoload.php') |
| 285 | ? bin2hex(random_bytes(16)) |
| 286 | : null; |
| 287 | } |
| 288 | } |