Passed
Push — master ( e85357...d9046f )
by Alexander
21:03 queued 14:54
created

Plugin::buildAllConfigs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 9
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config;
6
7
use Composer\Composer;
8
use Composer\IO\IOInterface;
9
use Composer\Util\Filesystem;
10
use Yiisoft\Composer\Config\Config\ConfigFactory;
11
use Yiisoft\Composer\Config\Exception\BadConfigurationException;
12
use Yiisoft\Composer\Config\Exception\FailedReadException;
13
use Yiisoft\Composer\Config\Package\AliasesCollector;
14
use Yiisoft\Composer\Config\Package\PackageFinder;
15
use Yiisoft\Composer\Config\Reader\ReaderFactory;
16
use Dotenv\Dotenv;
0 ignored issues
show
Bug introduced by
The type Dotenv\Dotenv was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
18
final class Plugin
19
{
20
    /**
21
     * @var Package[] the array of active composer packages
22
     */
23
    private array $packages;
24
25
    private array $alternatives = [];
26
27
    private ?Package $rootPackage = null;
28
29
    /**
30
     * @var array config name => list of files
31
     * Important: defines config files processing order:
32
     * envs then constants then params then other configs
33
     */
34
    private array $files = [
35
        'envs' => [],
36
        'constants' => [],
37
        'params' => [],
38
    ];
39
40
    /**
41
     * @var array package name => configs as listed in `composer.json`
42
     */
43
    private array $originalFiles = [];
44
45
    private Builder $builder;
46
47
    /**
48
     * @var IOInterface
49
     */
50
    private IOInterface $io;
51
52
    private AliasesCollector $aliasesCollector;
53
54
    /**
55
     * Initializes the plugin object with the passed $composer and $io.
56
     *
57
     * @param Composer $composer
58
     * @param IOInterface $io
59
     */
60
    public function __construct(Composer $composer, IOInterface $io)
61
    {
62
        $baseDir = dirname($composer->getConfig()->get('vendor-dir')) . DIRECTORY_SEPARATOR;
63
        $this->builder = new Builder(new ConfigFactory(), realpath($baseDir));
64
        $this->aliasesCollector = new AliasesCollector(new Filesystem());
65
        $this->io = $io;
66
        $this->collectPackages($composer);
67
    }
68
69
    public static function buildAllConfigs(string $projectRootPath): void
70
    {
71
        $factory = new \Composer\Factory();
72
        $output = $factory::createOutput();
73
        $input = new \Symfony\Component\Console\Input\ArgvInput([]);
74
        $helperSet = new \Symfony\Component\Console\Helper\HelperSet();
75
        $io = new \Composer\IO\ConsoleIO($input, $output, $helperSet);
76
        $composer = $factory->createComposer($io, $projectRootPath . '/composer.json', true, $projectRootPath, false);
77
        $plugin = new self($composer, $io);
78
        $plugin->build();
79
    }
80
81
    public function build(): void
82
    {
83
        $this->io->overwriteError('<info>Assembling config files</info>');
84
85
        $this->scanPackages();
86
        $this->reorderFiles();
87
88
        $this->builder->buildAllConfigs($this->files);
89
90
        $saveFiles = $this->files;
91
        $saveEnv = $_ENV;
92
        foreach ($this->alternatives as $name => $files) {
93
            $this->files = $saveFiles;
94
            $_ENV = $saveEnv;
95
            $builder = $this->builder->createAlternative($name);
96
            $this->addFiles($this->rootPackage, $files);
0 ignored issues
show
Bug introduced by
It seems like $this->rootPackage can also be of type null; however, parameter $package of Yiisoft\Composer\Config\Plugin::addFiles() does only seem to accept Yiisoft\Composer\Config\Package, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

96
            $this->addFiles(/** @scrutinizer ignore-type */ $this->rootPackage, $files);
Loading history...
97
            $builder->buildAllConfigs($this->files);
98
        }
99
    }
100
101
    private function scanPackages(): void
102
    {
103
        foreach ($this->packages as $package) {
104
            if ($package->isComplete()) {
105
                $this->processPackage($package);
106
            }
107
        }
108
    }
109
110
    private function reorderFiles(): void
111
    {
112
        foreach (array_keys($this->files) as $name) {
113
            $this->files[$name] = $this->getAllFiles($name);
114
        }
115
        foreach ($this->files as $name => $files) {
116
            $this->files[$name] = $this->orderFiles($files);
117
        }
118
    }
119
120
    private function getAllFiles(string $name, array $stack = []): array
121
    {
122
        if (empty($this->files[$name])) {
123
            return [];
124
        }
125
        $res = [];
126
        foreach ($this->files[$name] as $file) {
127
            if (strncmp($file, '$', 1) === 0) {
128
                if (!in_array($name, $stack, true)) {
129
                    $res = array_merge($res, $this->getAllFiles(substr($file, 1), array_merge($stack, [$name])));
130
                }
131
            } else {
132
                $res[] = $file;
133
            }
134
        }
135
136
        return $res;
137
    }
138
139
    private function orderFiles(array $files): array
140
    {
141
        if ($files === []) {
142
            return [];
143
        }
144
        $keys = array_combine($files, $files);
145
        $res = [];
146
        foreach ($this->orderedFiles as $file) {
147
            if (array_key_exists($file, $keys)) {
0 ignored issues
show
Bug introduced by
It seems like $keys can also be of type false; however, parameter $search of array_key_exists() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

147
            if (array_key_exists($file, /** @scrutinizer ignore-type */ $keys)) {
Loading history...
148
                $res[$file] = $file;
149
            }
150
        }
151
152
        return array_values($res);
153
    }
154
155
    /**
156
     * Scans the given package and collects packages data.
157
     *
158
     * @param Package $package
159
     */
160
    private function processPackage(Package $package): void
161
    {
162
        $files = $package->getFiles();
163
        $this->originalFiles[$package->getPrettyName()] = $files;
164
165
        if (!empty($files)) {
166
            $this->addFiles($package, $files);
167
        }
168
        if ($package->isRoot()) {
169
            $this->rootPackage = $package;
170
            $this->loadDotEnv($package);
171
            $devFiles = $package->getDevFiles();
172
            if (!empty($devFiles)) {
173
                $this->addFiles($package, $devFiles);
174
            }
175
            $alternatives = $package->getAlternatives();
176
            if (is_string($alternatives)) {
177
                $this->alternatives = $this->readConfig($package, $alternatives);
178
            } elseif (is_array($alternatives)) {
179
                $this->alternatives = $alternatives;
180
            } elseif (!empty($alternatives)) {
181
                throw new BadConfigurationException('Alternatives must be array or path to configuration file.');
182
            }
183
        }
184
185
        $aliases = $this->aliasesCollector->collect($package);
186
187
        $this->builder->mergeAliases($aliases);
188
        $this->builder->setPackage($package->getPrettyName(), array_filter([
189
            'name' => $package->getPrettyName(),
190
            'version' => $package->getVersion(),
191
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
192
            'aliases' => $aliases,
193
        ]));
194
    }
195
196
    private function readConfig($package, $file): array
197
    {
198
        $path = $package->preparePath($file);
199
        if (!file_exists($path)) {
200
            throw new FailedReadException("failed read file: $file");
201
        }
202
        $reader = ReaderFactory::get($this->builder, $path);
203
204
        return $reader->read($path);
205
    }
206
207
    private function loadDotEnv(Package $package): void
208
    {
209
        $path = $package->preparePath('.env');
210
        if (file_exists($path) && class_exists(Dotenv::class)) {
211
            $this->addFile($package, 'envs', $path);
212
        }
213
    }
214
215
    /**
216
     * Adds given files to the list of files to be processed.
217
     * Prepares `constants` in reversed order (outer package first) because
218
     * constants cannot be redefined.
219
     *
220
     * @param Package $package
221
     * @param array $files
222
     */
223
    private function addFiles(Package $package, array $files): void
224
    {
225
        foreach ($files as $name => $paths) {
226
            $paths = (array) $paths;
227
            if ('constants' === $name) {
228
                $paths = array_reverse($paths);
229
            }
230
            foreach ($paths as $path) {
231
                $this->addFile($package, $name, $path);
232
            }
233
        }
234
    }
235
236
    private array $orderedFiles = [];
237
238
    private function addFile(Package $package, string $name, string $path): void
239
    {
240
        $path = $package->preparePath($path);
241
        if (!array_key_exists($name, $this->files)) {
242
            $this->files[$name] = [];
243
        }
244
        if (in_array($path, $this->files[$name], true)) {
245
            return;
246
        }
247
        if ('constants' === $name) {
248
            array_unshift($this->orderedFiles, $path);
249
            array_unshift($this->files[$name], $path);
250
        } else {
251
            $this->orderedFiles[] = $path;
252
            $this->files[$name][] = $path;
253
        }
254
    }
255
256
    private function collectPackages(Composer $composer): void
257
    {
258
        $vendorDir = $composer->getConfig()->get('vendor-dir');
259
        $rootPackage = $composer->getPackage();
260
        $packages = $composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
261
        $packageFinder = new PackageFinder($vendorDir, $rootPackage, $packages);
262
263
        $this->packages = $packageFinder->findPackages();
264
    }
265
}
266