|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the humbug/php-scoper package. |
| 7 | + * |
| 8 | + * Copyright (c) 2017 Théo FIDRY <[email protected]>, |
| 9 | + * Pádraic Brady <[email protected]> |
| 10 | + * |
| 11 | + * For the full copyright and license information, please view the LICENSE |
| 12 | + * file that was distributed with this source code. |
| 13 | + */ |
| 14 | + |
| 15 | +namespace Humbug\PhpScoper\Scoper\Composer; |
| 16 | + |
| 17 | +use Humbug\PhpScoper\Scoper; |
| 18 | +use LogicException; |
| 19 | + |
| 20 | +final class InstalledPackagesScoper implements Scoper |
| 21 | +{ |
| 22 | + /** |
| 23 | + * @var string |
| 24 | + */ |
| 25 | + private static $filePattern; |
| 26 | + |
| 27 | + private $decoratedScoper; |
| 28 | + |
| 29 | + public function __construct(Scoper $decoratedScoper) |
| 30 | + { |
| 31 | + if (null === self::$filePattern) { |
| 32 | + self::$filePattern = str_replace( |
| 33 | + '/', |
| 34 | + DIRECTORY_SEPARATOR, |
| 35 | + '~composer/installed\.json~' |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + $this->decoratedScoper = $decoratedScoper; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Scopes PHP and JSON files related to Composer. |
| 44 | + * |
| 45 | + * {@inheritdoc} |
| 46 | + */ |
| 47 | + public function scope(string $filePath, string $prefix): string |
| 48 | + { |
| 49 | + if (null === self::$filePattern) { |
| 50 | + throw new LogicException('Cannot be used without being initialised first.'); |
| 51 | + } |
| 52 | + |
| 53 | + if (1 !== preg_match(self::$filePattern, $filePath)) { |
| 54 | + return $this->decoratedScoper->scope($filePath, $prefix); |
| 55 | + } |
| 56 | + |
| 57 | + $decodedJson = json_decode( |
| 58 | + file_get_contents($filePath), |
| 59 | + true |
| 60 | + ); |
| 61 | + |
| 62 | + $decodedJson = $this->prefixLockPackages($decodedJson, $prefix); |
| 63 | + |
| 64 | + return json_encode( |
| 65 | + $decodedJson, |
| 66 | + JSON_PRETTY_PRINT |
| 67 | + ); |
| 68 | + } |
| 69 | + |
| 70 | + private function prefixLockPackages(array $packages, string $prefix): array |
| 71 | + { |
| 72 | + foreach ($packages as $index => $package) { |
| 73 | + $packages[$index] = AutoloadPrefixer::prefixPackageAutoloads($package, $prefix); |
| 74 | + } |
| 75 | + |
| 76 | + return $packages; |
| 77 | + } |
| 78 | +} |
0 commit comments