Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.41% covered (warning)
59.41%
142 / 239
41.67% covered (danger)
41.67%
5 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
InstalledJson
59.41% covered (warning)
59.41%
142 / 239
41.67% covered (danger)
41.67%
5 / 12
357.21
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 copyInstalledJson
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
1
 getJsonFile
62.50% covered (warning)
62.50%
10 / 16
0.00% covered (danger)
0.00%
0 / 1
3.47
 updatePackagePaths
34.78% covered (danger)
34.78%
8 / 23
0.00% covered (danger)
0.00%
0 / 1
15.99
 pathExistsInPackage
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 removeMissingAutoloadKeyPaths
31.58% covered (danger)
31.58%
18 / 57
0.00% covered (danger)
0.00%
0 / 1
148.12
 removeMovedPackagesAutoloadKeyFromVendorDirInstalledJson
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 removeMovedPackagesAutoloadKeyFromTargetDirInstalledJson
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
9.75
 updateNamespaces
70.00% covered (warning)
70.00%
28 / 40
0.00% covered (danger)
0.00%
0 / 1
21.08
 cleanTargetDirInstalledJson
84.85% covered (warning)
84.85%
28 / 33
0.00% covered (danger)
0.00%
0 / 1
6.13
 cleanupVendorInstalledJson
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
2
 reindexPackagesList
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Changes "install-path" to point to vendor-prefixed target directory.
4 *
5 * * create new vendor-prefixed/composer/installed.json file with copied packages
6 * * when delete is enabled, update package paths in the original vendor/composer/installed.json
7 * * when delete is enabled, remove dead entries in the original vendor/composer/installed.json
8 * * update psr-0 autoload keys to have matching classmap entries
9 *
10 * @see vendor/composer/installed.json
11 *
12 * TODO: when delete_vendor_files is used, the original directory still exists so the paths are not updated.
13 *
14 * @package brianhenryie/strauss
15 */
16
17namespace BrianHenryIE\Strauss\Pipeline\Cleanup;
18
19use BrianHenryIE\Strauss\Composer\DependenciesCollection;
20use BrianHenryIE\Strauss\Config\CleanupConfigInterface;
21use BrianHenryIE\Strauss\Helpers\Flysystem\FileSystem;
22use BrianHenryIE\Strauss\Types\DiscoveredSymbols;
23use Composer\Json\JsonFile;
24use Composer\Json\JsonValidationException;
25use Exception;
26use League\Flysystem\FilesystemException;
27use Psr\Log\LoggerAwareTrait;
28use Psr\Log\LoggerInterface;
29use Seld\JsonLint\ParsingException;
30
31/**
32 * @phpstan-type InstalledJsonPackageSourceArray array{type:string, url:string, reference:string}
33 * @phpstan-type InstalledJsonPackageDistArray array{type:string, url:string, reference:string, shasum:string}
34 * @phpstan-type InstalledJsonPackageAutoloadPsr0Array array<string,string|array<string>>
35 * @phpstan-type InstalledJsonPackageAutoloadPsr4Array array<string,string|array<string>>
36 * @phpstan-type InstalledJsonPackageAutoloadClassmapArray string[]
37 * @phpstan-type InstalledJsonPackageAutoloadFilesArray string[]
38 * @phpstan-type InstalledJsonPackageAutoloadArray array{"psr-4"?:InstalledJsonPackageAutoloadPsr4Array, classmap?:InstalledJsonPackageAutoloadClassmapArray, files?:InstalledJsonPackageAutoloadFilesArray, "psr-0"?:InstalledJsonPackageAutoloadPsr0Array}
39 * @phpstan-type InstalledJsonPackageAuthorArray array{name:string,email:string}
40 * @phpstan-type InstalledJsonPackageSupportArray array{issues:string, source:string}
41 *
42 * @phpstan-type InstalledJsonPackageArray array{name:string, version:string, version_normalized:string, source:InstalledJsonPackageSourceArray, dist:InstalledJsonPackageDistArray, require:array<string,string>, require-dev:array<string,string>, time:string, type:string, installation-source:string, autoload?:InstalledJsonPackageAutoloadArray, notification-url:string, license:array<string>, authors:array<InstalledJsonPackageAuthorArray>, description:string, homepage:string, keywords:array<string>, support:InstalledJsonPackageSupportArray, install-path:string}
43 *
44 * @phpstan-type InstalledJsonArray array{packages:array<InstalledJsonPackageArray>, dev?:bool, dev-package-names:array<string>}
45 */
46class InstalledJson
47{
48    use LoggerAwareTrait;
49
50    protected CleanupConfigInterface $config;
51
52    protected FileSystem $filesystem;
53
54    public function __construct(
55        CleanupConfigInterface $config,
56        FileSystem $filesystem,
57        LoggerInterface $logger
58    ) {
59        $this->config = $config;
60        $this->filesystem = $filesystem;
61
62        $this->setLogger($logger);
63    }
64
65    /**
66     * @throws FilesystemException
67     */
68    public function copyInstalledJson(): void
69    {
70        $this->logger->debug('InstalledJson::copyInstalledJson()');
71
72        $source = $this->config->getAbsoluteVendorDirectory() . '/composer/installed.json';
73        $target = $this->config->getAbsoluteTargetDirectory() . '/composer/installed.json';
74
75        $this->logger->info('Copying {sourcePath} to {targetPath}', [
76            'sourcePath' => $source,
77            'targetPath' => $target
78        ]);
79
80        $this->filesystem->copy(
81            $source,
82            $target
83        );
84
85        $this->logger->info('Copied {sourcePath} to {targetPath}', [
86            'sourcePath' => $source,
87            'targetPath' => $target
88        ]);
89    }
90
91    /**
92     * @throws JsonValidationException
93     * @throws ParsingException
94     * @throws Exception
95     */
96    protected function getJsonFile(string $vendorDir): JsonFile
97    {
98        $installedJsonFile = new JsonFile(
99            sprintf(
100                '%s/composer/installed.json',
101                $this->filesystem->makeAbsolute($vendorDir)
102            )
103        );
104        if (!$installedJsonFile->exists()) {
105            if (!$this->config->isDryRun()) {
106                $this->logger->error(
107                    'Expected {installedJsonFilePath} does not exist.',
108                    [ 'installedJsonFilePath' => $installedJsonFile->getPath() ]
109                );
110            }
111            throw new Exception('Expected installed.json does not exist: ' . $installedJsonFile->getPath());
112        }
113
114        $installedJsonFile->validateSchema(JsonFile::LAX_SCHEMA);
115
116        $this->logger->info('Loaded file: {installedJsonFilePath}', ['installedJsonFilePath' => $installedJsonFile->getPath()]);
117
118        return $installedJsonFile;
119    }
120
121    /**
122     * @param InstalledJsonArray $installedJsonArray
123     * @param DependenciesCollection $flatDependencyTree
124     * @param string[] $excludedPackageNames
125     * @return InstalledJsonArray
126     */
127    protected function updatePackagePaths(
128        array $installedJsonArray,
129        DependenciesCollection $flatDependencyTree,
130        string $path,
131        DiscoveredSymbols $discoveredSymbols,
132        array $excludedPackageNames = []
133    ): array {
134
135        foreach ($installedJsonArray['packages'] as $key => $package) {
136            if (in_array($package['name'], $excludedPackageNames, true)) {
137                unset($installedJsonArray['packages'][$key]);
138                continue;
139            }
140
141            // Skip packages that were never copied in the first place.
142            if (!in_array($package['name'], array_keys($flatDependencyTree->toArray()))) {
143                $this->logger->debug('Skipping package: ' . $package['name']);
144                continue;
145            }
146            $this->logger->info('Checking package: ' . $package['name']);
147
148            // `composer/` is here because the install-path is relative to the `vendor/composer` directory.
149            $packageDir = $path . '/composer/' . $package['install-path'];
150            if (!$this->filesystem->directoryExists($packageDir)) {
151                $this->logger->debug('Package directory does not exist at : ' . $packageDir);
152
153                $newInstallPath = $this->filesystem->normalizePath($path . '/composer/' . $package['install-path']);
154
155                if (!$this->filesystem->directoryExists($newInstallPath)) {
156                    unset($installedJsonArray['packages'][$key]);
157                    $this->logger->info('Package directory does not exist: ' . $newInstallPath);
158                    continue;
159                }
160
161                $newRelativePath = $this->filesystem->getRelativePath(
162                    $path . '/composer/',
163                    $newInstallPath
164                );
165
166                $installedJsonArray['packages'][$key]['install-path'] = $newRelativePath;
167            } else {
168                $this->logger->debug('Original package directory exists at : ' . $packageDir);
169            }
170        }
171        return $installedJsonArray;
172    }
173
174    /**
175     * @param InstalledJsonPackageArray $packageArray
176     * @throws FilesystemException
177     */
178    protected function pathExistsInPackage(string $vendorDir, array $packageArray, string $relativePath): bool
179    {
180        return $this->filesystem->exists(
181            $vendorDir . '/composer/' . $packageArray['install-path'] . '/' . $relativePath
182        );
183    }
184
185    /**
186     * Remove autoload key entries from `installed.json` whose file or directory does not exist after deleting.
187     *
188     * @param InstalledJsonArray $installedJsonArray
189     * @return InstalledJsonArray
190     * @throws FilesystemException
191     */
192    protected function removeMissingAutoloadKeyPaths(array $installedJsonArray, string $vendorDir, string $installedJsonPath, DiscoveredSymbols $discoveredSymbols): array
193    {
194        foreach ($installedJsonArray['packages'] as $packageIndex => $packageArray) {
195            if (!isset($packageArray['autoload'])) {
196                $this->logger->info(
197                    'Package {packageName} has no autoload key in {installedJsonPath}',
198                    ['packageName' => $packageArray['name'],'installedJsonPath'=>$installedJsonPath]
199                );
200                continue;
201            }
202            // delete_vendor_files
203            $path = $vendorDir . '/composer/' . $packageArray['install-path'];
204            $pathExists = $this->filesystem->directoryExists($path);
205            // delete_vendor_packages
206            if (!$pathExists) {
207                $this->logger->info(
208                    'Removing package autoload key from {installedJsonPath}: {packageName}',
209                    ['packageName' => $packageArray['name'],'installedJsonPath'=>$installedJsonPath]
210                );
211                $installedJsonArray['packages'][$packageIndex]['autoload'] = [];
212            }
213            foreach ($installedJsonArray['packages'][$packageIndex]['autoload'] ?? [] as $type => $autoload) {
214                switch ($type) {
215                    case 'files':
216                    case 'classmap':
217                        // Ensure we filter the current autoload bucket and keep only existing paths
218                        $filtered = array_filter(
219                            (array) $autoload,
220                            function ($relativePath) use ($vendorDir, $packageArray): bool {
221                                return is_string($relativePath) && $this->pathExistsInPackage($vendorDir, $packageArray, $relativePath);
222                            }
223                        );
224                        // Reindex to produce a clean list of strings
225                        $installedJsonArray['packages'][$packageIndex]['autoload'][$type] = array_values($filtered);
226                        break;
227                    case 'psr-0':
228                        // Intentionally fall through.
229                    case 'psr-4':
230                        foreach ($autoload as $namespace => $paths) {
231                            switch (true) {
232                                case is_array($paths):
233                                    // e.g. [ 'psr-4' => [ 'BrianHenryIE\Project' => ['src','lib] ] ]
234                                    $validPaths = [];
235                                    foreach ($paths as $path) {
236                                        if ($this->pathExistsInPackage($vendorDir, $packageArray, $path)) {
237                                            $validPaths[] = $path;
238                                        } else {
239                                            $this->logger->debug('Removing non-existent path from autoload: ' . $path);
240                                        }
241                                    }
242                                    if (!empty($validPaths)) {
243                                        $installedJsonArray['packages'][$packageIndex]['autoload'][$type][$namespace] = $validPaths;
244                                    } else {
245                                        $this->logger->debug('Removing autoload key: ' . $type);
246                                        unset($installedJsonArray['packages'][$packageIndex]['autoload'][$type][$namespace]);
247                                    }
248                                    break;
249                                case is_string($paths):
250                                    // e.g. [ 'psr-4' => [ 'BrianHenryIE\Project' => 'src' ] ]
251                                    if (!$this->pathExistsInPackage($vendorDir, $packageArray, $paths)) {
252                                        $this->logger->debug('Removing autoload key: ' . $type . ' for ' . $paths);
253                                        unset($installedJsonArray['packages'][$packageIndex]['autoload'][$type][$namespace]);
254                                    }
255                                    break;
256                                default:
257                                    $this->logger->warning('Unexpectedly got neither a string nor array for autoload key in installed.json: ' . $type . ' ' . json_encode($paths));
258                                    break;
259                            }
260                        }
261                        break;
262                    case 'exclude-from-classmap':
263                        break;
264                    default:
265                        $this->logger->warning(
266                            'Unexpected autoload type in {installedJsonPath}: {type}',
267                            ['installedJsonPath'=>$installedJsonPath,'type'=>$type]
268                        );
269                        break;
270                }
271            }
272        }
273        /** @var InstalledJsonArray $installedJsonArray */
274        $installedJsonArray = $installedJsonArray;
275        return $installedJsonArray;
276    }
277
278    /**
279     * Remove the autoload key for packages from `installed.json` whose target directory does not exist after deleting.
280     *
281     * E.g. after the file is copied to the target directory, this will remove dev dependencies and unmodified dependencies from the second installed.json
282     *
283     * @param InstalledJsonArray $installedJsonArray
284     * @param DependenciesCollection $flatDependencyTree
285     * @return InstalledJsonArray
286     */
287    protected function removeMovedPackagesAutoloadKeyFromVendorDirInstalledJson(array $installedJsonArray, DependenciesCollection $flatDependencyTree, string $installedJsonPath): array
288    {
289        /**
290         * @var int $key
291         * @var InstalledJsonPackageArray $packageArray
292         */
293        foreach ($installedJsonArray['packages'] as $key => $packageArray) {
294            $packageName = $packageArray['name'];
295            $package = $flatDependencyTree[$packageName] ?? null;
296            if (!$package) {
297                // Probably a dev dependency that we aren't tracking.
298                continue;
299            }
300
301            if ($package->didDelete()) {
302                $this->logger->info(
303                    'Removing deleted package autoload key from {installedJsonPath}: {packageName}',
304                    ['installedJsonPath' => $installedJsonPath, 'packageName' => $packageName]
305                );
306                $installedJsonArray['packages'][$key]['autoload'] = [];
307            }
308        }
309        return $installedJsonArray;
310    }
311
312    /**
313     * Remove the autoload key for packages from `vendor-prefixed/composer/installed.json` whose target directory does not exist in `vendor-prefixed`.
314     *
315     * E.g. after the file is copied to the target directory, this will remove dev dependencies and unmodified dependencies from the second installed.json
316     *
317     * @param InstalledJsonArray $installedJsonArray
318     * @param DependenciesCollection $flatDependencyTree
319     * @return InstalledJsonArray
320     */
321    protected function removeMovedPackagesAutoloadKeyFromTargetDirInstalledJson(array $installedJsonArray, DependenciesCollection $flatDependencyTree, string $installedJsonPath): array
322    {
323        /**
324         * @var int $key
325         * @var InstalledJsonPackageArray $packageArray
326         */
327        foreach ($installedJsonArray['packages'] as $key => $packageArray) {
328            $packageName = $packageArray['name'];
329
330            $remove = false;
331
332            if (!in_array($packageName, array_keys($flatDependencyTree->toArray()))) {
333                // If it's not a package we were ever considering copying, then we can remove it.
334                $remove = true;
335            } else {
336                $package = $flatDependencyTree[$packageName] ?? null;
337                if (!$package) {
338                    // Probably a dev dependency.
339                    continue;
340                }
341                if (!$package->didCopy()) {
342                    // If it was marked not to copy, then we know it's not in the vendor-prefixed directory, and we can remove it.
343                    $remove = true;
344                }
345            }
346
347            if ($remove) {
348                $this->logger->info(
349                    'Removing deleted package autoload key from {installedJsonPath}: {packageName}',
350                    ['installedJsonPath' => $installedJsonPath, 'packageName' => $packageName]
351                );
352                $installedJsonArray['packages'][$key]['autoload'] = [];
353            }
354        }
355        return $installedJsonArray;
356    }
357
358    /**
359     * @param InstalledJsonArray $installedJsonArray
360     * @return InstalledJsonArray
361     */
362    protected function updateNamespaces(array $installedJsonArray, DiscoveredSymbols $discoveredSymbols): array
363    {
364        $this->logger->debug('InstalledJson::updateNamespaces()');
365
366        $discoveredNamespaces = $discoveredSymbols->getNamespaces()->toArray();
367
368        foreach ($installedJsonArray['packages'] as $key => $package) {
369            if (!isset($package['autoload'])) {
370                // woocommerce/action-scheduler
371                $this->logger->info('Package has no autoload key: ' . $package['name'] . ' ' . $package['type']);
372                continue;
373            }
374
375            $autoload_key = $package['autoload'];
376            // TODO: This was added before good PSR-0 support, we just added PSR-0 to the classmap and it worked ok.
377            if (!isset($autoload_key['classmap'])) {
378                $autoload_key['classmap'] = [];
379            }
380            foreach ($autoload_key as $type => $autoload) {
381                switch ($type) {
382                    case 'psr-0':
383                        // Intentionally fall through
384                    case 'psr-4':
385                        /**
386                         * e.g.
387                         * * {"psr-4":{"Psr\\Log\\":"Psr\/Log\/"}}
388                         * * {"psr-4":{"":"src\/"}}
389                         * * {"psr-4":{"Symfony\\Polyfill\\Mbstring\\":""}}
390                         * * {"psr-4":{"Another\\Package\\":["src","includes"]}}
391                         * * {"psr-0":{"PayPal":"lib\/"}}
392                         */
393                        foreach ($autoload_key[$type] as $originalNamespace => $packageRelativeDirectory) {
394                            // Replace $originalNamespace with updated namespace
395
396                            // Just for dev â€“ find a package like this and write a test for it.
397                            // pear/pear-core-minimal
398                            if (empty($originalNamespace)) {
399                                // In the case of `nesbot/carbon`, it uses an empty namespace but the classes are in the `Carbon`
400                                // namespace, so using `override_autoload` should be a good solution if this proves to be an issue.
401                                // The package directory will be updated, so for whatever reason the original empty namespace
402                                // works, maybe the updated namespace will work too.
403                                $this->logger->warning('Empty namespace found in autoload. Behaviour is not fully documented: ' . $package['name']);
404                                continue;
405                            }
406
407                            $trimmedOriginalNamespace = trim($originalNamespace, '\\');
408
409                            $this->logger->info('Checking '.$type.' namespace: ' . $trimmedOriginalNamespace);
410
411                            if (isset($discoveredNamespaces[$trimmedOriginalNamespace])) {
412                                $namespaceSymbol = $discoveredNamespaces[$trimmedOriginalNamespace];
413                            } else {
414                                $this->logger->debug('Namespace not found in list of changes: ' . $trimmedOriginalNamespace);
415                                continue;
416                            }
417
418                            if ($trimmedOriginalNamespace === trim($namespaceSymbol->getLocalReplacement(), '\\')) {
419                                $this->logger->debug('Namespace is unchanged: ' . $trimmedOriginalNamespace);
420                                continue;
421                            }
422
423                            // Update the namespace if it has changed.
424                            $this->logger->info('Updating namespace: ' . $trimmedOriginalNamespace . ' => ' . $namespaceSymbol->getLocalReplacement());
425                            $newKey = str_replace($trimmedOriginalNamespace, $namespaceSymbol->getLocalReplacement(), $originalNamespace);
426                            // PSR-0 underscore convention (PEAR-style): packages where class names use underscores
427                            // as directory separators with no PHP namespace declarations have no source files on
428                            // the namespace symbol. Their installed.json key must use underscores to match.
429                            // TODO: if this fails, filter the source files' namespaces to ensure they are all global.
430                            if ($type === 'psr-0' && empty($namespaceSymbol->getSourceFiles())) {
431                                $newKey = str_replace('\\', '_', $newKey);
432                            }
433                            /** @phpstan-ignore offsetAccess.notFound */
434                            $autoload_key[$type][$newKey] = $autoload_key[$type][$originalNamespace];
435                            unset($autoload_key[$type][$originalNamespace]);
436                        }
437                        break;
438                    default:
439                        /**
440                         * `files`, `classmap`, `exclude-from-classmap`
441                         * These don't contain namespaces in the autoload key.
442                         * * {"classmap":["src\/"]}
443                         * * {"files":["src\/functions.php"]}
444                         * * {"exclude-from-classmap":["\/Tests\/"]}
445                         *
446                         * Custom autoloader types might.
447                         */
448                        if (!in_array($type, ['files', 'classmap', 'exclude-from-classmap'])) {
449                            $this->logger->warning('Unexpected autoloader type: {type} in {packageName}.', [
450                                'type' => $type, 'packageName' => $package['name']
451                            ]);
452                        }
453                        break;
454                }
455            }
456            $installedJsonArray['packages'][$key]['autoload'] = array_filter($autoload_key);
457        }
458
459        $this->logger->debug('Finished InstalledJson::updateNamespaces()');
460
461        return $installedJsonArray;
462    }
463
464    /**
465     * TODO: This runs twice but should only run once.
466     *
467     * @throws Exception
468     * @throws FilesystemException
469     */
470    public function cleanTargetDirInstalledJson(DependenciesCollection $flatDependencyTree, DiscoveredSymbols $discoveredSymbols): void
471    {
472        $this->logger->debug('InstalledJson::cleanTargetDirInstalledJson()');
473
474        $targetDir = $this->config->getAbsoluteTargetDirectory();
475        try {
476            $installedJsonFile = $this->getJsonFile($targetDir);
477        } catch (Exception $e) {
478            if ($this->config->isDryRun()) {
479                $installedJsonFile = $this->getJsonFile($this->config->getAbsoluteVendorDirectory());
480            } else {
481                throw $e;
482            }
483        }
484
485        /**
486         * @var InstalledJsonArray $installedJsonArray
487         */
488        $installedJsonArray = $installedJsonFile->read();
489
490        $installedJsonArray = $this->updatePackagePaths(
491            $installedJsonArray,
492            $flatDependencyTree,
493            $this->config->getAbsoluteTargetDirectory(),
494            $discoveredSymbols,
495            $this->config->getExcludePackagesFromCopy()
496        );
497
498        $installedJsonArray = $this->removeMissingAutoloadKeyPaths($installedJsonArray, $this->config->getAbsoluteTargetDirectory(), $installedJsonFile->getPath(), $discoveredSymbols);
499
500        $installedJsonArray = $this->removeMovedPackagesAutoloadKeyFromTargetDirInstalledJson(
501            $installedJsonArray,
502            $flatDependencyTree,
503            $installedJsonFile->getPath()
504        );
505
506        $installedJsonArray = $this->updateNamespaces($installedJsonArray, $discoveredSymbols);
507
508        foreach ($installedJsonArray['packages'] as $index => $package) {
509            if (!in_array($package['name'], array_keys($flatDependencyTree->toArray()))) {
510                unset($installedJsonArray['packages'][$index]);
511            }
512        }
513
514        $installedJsonArray = $this->reindexPackagesList($installedJsonArray);
515        $installedJsonArray['dev'] = false;
516        $installedJsonArray['dev-package-names'] = [];
517
518        $this->logger->info('Writing installed.json to ' . $targetDir);
519
520        if (!$this->config->isDryRun()) {
521            $installedJsonFile->write($installedJsonArray);
522        }
523
524        $this->logger->info('Installed.json written to ' . $targetDir);
525
526        $this->logger->debug('Finished InstalledJson::cleanTargetDirInstalledJson()');
527    }
528
529    /**
530     * Composer creates a file `vendor/composer/installed.json` which is used when running `composer dump-autoload`.
531     * When `delete-vendor-packages` or `delete-vendor-files` is true, files and directories which have been deleted
532     * must also be removed from `installed.json` or Composer will throw an error.
533     *
534     * @throws Exception
535     * @throws FilesystemException
536     */
537    public function cleanupVendorInstalledJson(DependenciesCollection $flatDependencyTree, DiscoveredSymbols $discoveredSymbols): void
538    {
539        $this->logger->debug('InstalledJson::cleanupVendorInstalledJson()');
540
541        $vendorDir = $this->config->getAbsoluteVendorDirectory();
542
543        $vendorInstalledJsonFile = $this->getJsonFile($vendorDir);
544
545        $this->logger->info('Cleaning up {installedJsonPath}', ['installedJsonPath' => $vendorInstalledJsonFile->getPath()]);
546
547        /**
548         * @var InstalledJsonArray $installedJsonArray
549         */
550        $installedJsonArray = $vendorInstalledJsonFile->read();
551
552        $installedJsonArray = $this->removeMissingAutoloadKeyPaths($installedJsonArray, $this->config->getAbsoluteVendorDirectory(), $vendorInstalledJsonFile->getPath(), $discoveredSymbols);
553
554        $installedJsonArray = $this->removeMovedPackagesAutoloadKeyFromVendorDirInstalledJson($installedJsonArray, $flatDependencyTree, $vendorInstalledJsonFile->getPath());
555
556        $installedJsonArray = $this->updatePackagePaths(
557            $installedJsonArray,
558            $flatDependencyTree,
559            $this->config->getAbsoluteVendorDirectory(),
560            $discoveredSymbols
561        );
562
563        // Only relevant when source = target.
564        $installedJsonArray = $this->updateNamespaces($installedJsonArray, $discoveredSymbols);
565
566        $installedJsonArray = $this->reindexPackagesList($installedJsonArray);
567
568        if (!$this->config->isDryRun()) {
569            $vendorInstalledJsonFile->write($installedJsonArray);
570        }
571
572        $this->logger->debug('Finished InstalledJson::cleanupVendorInstalledJson()');
573    }
574
575    /**
576     * @param InstalledJsonArray $installedJsonArray
577     * @return InstalledJsonArray
578     */
579    private function reindexPackagesList(array $installedJsonArray): array
580    {
581        $installedJsonArray['packages'] = array_values($installedJsonArray['packages']);
582
583        return $installedJsonArray;
584    }
585}