Passed
Pull Request — master (#110)
by
unknown
14:42
created

Plugin::processPackage()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 33
ccs 0
cts 13
cp 0
rs 8.4444
cc 8
nc 18
nop 1
crap 72
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->reorderConfigs();
87
        $this->reorderFiles();
88
89
        $this->builder->buildAllConfigs($this->files);
90
91
        $saveFiles = $this->files;
92
        $saveEnv = $_ENV;
93
        foreach ($this->alternatives as $name => $files) {
94
            $this->files = $saveFiles;
95
            $_ENV = $saveEnv;
96
            $builder = $this->builder->createAlternative($name);
97
            $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

97
            $this->addFiles(/** @scrutinizer ignore-type */ $this->rootPackage, $files);
Loading history...
98
            $builder->buildAllConfigs($this->files);
99
        }
100
    }
101
102
    private function scanPackages(): void
103
    {
104
        foreach ($this->packages as $package) {
105
            if ($package->isComplete()) {
106
                $this->processPackage($package);
107
            }
108
        }
109
    }
110
111
    private function reorderConfigs(): void
112
    {
113
        $order = [];
114
        foreach (array_reverse($this->packages) as $package) {
115
            if (!$package->isComplete()) {
116
                continue;
117
            }
118
119
            $files = $package->getFiles();
120
            if (empty($files)) {
121
                continue;
122
            }
123
124
            foreach (array_keys($files) as $name) {
125
                if (!in_array($name, $order, true)) {
126
                    $order[] = $name;
127
                }
128
            }
129
        }
130
131
        $files = [];
132
        foreach (array_keys($this->files) as $name) {
133
            if (!in_array($name, $order)) {
134
                $files[$name] = $this->files[$name];
135
            }
136
        }
137
        foreach ($order as $name) {
138
            $files[$name] = $this->files[$name];
139
        }
140
        $this->files = $files;
141
    }
142
143
    private function reorderFiles(): void
144
    {
145
        foreach (array_keys($this->files) as $name) {
146
            $this->files[$name] = $this->getAllFiles($name);
147
        }
148
        foreach ($this->files as $name => $files) {
149
            $this->files[$name] = $this->orderFiles($files);
150
        }
151
    }
152
153
    private function getAllFiles(string $name, array $stack = []): array
154
    {
155
        if (empty($this->files[$name])) {
156
            return [];
157
        }
158
        $res = [];
159
        foreach ($this->files[$name] as $file) {
160
            if (strncmp($file, '$', 1) === 0) {
161
                if (!in_array($name, $stack, true)) {
162
                    $res = array_merge($res, $this->getAllFiles(substr($file, 1), array_merge($stack, [$name])));
163
                }
164
            } else {
165
                $res[] = $file;
166
            }
167
        }
168
169
        return $res;
170
    }
171
172
    private function orderFiles(array $files): array
173
    {
174
        if ($files === []) {
175
            return [];
176
        }
177
        $keys = array_combine($files, $files);
178
        $res = [];
179
        foreach ($this->orderedFiles as $file) {
180
            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

180
            if (array_key_exists($file, /** @scrutinizer ignore-type */ $keys)) {
Loading history...
181
                $res[$file] = $file;
182
            }
183
        }
184
185
        return array_values($res);
186
    }
187
188
    /**
189
     * Scans the given package and collects packages data.
190
     *
191
     * @param Package $package
192
     */
193
    private function processPackage(Package $package): void
194
    {
195
        $files = $package->getFiles();
196
        $this->originalFiles[$package->getPrettyName()] = $files;
197
198
        if (!empty($files)) {
199
            $this->addFiles($package, $files);
200
        }
201
        if ($package->isRoot()) {
202
            $this->rootPackage = $package;
203
            $this->loadDotEnv($package);
204
            $devFiles = $package->getDevFiles();
205
            if (!empty($devFiles)) {
206
                $this->addFiles($package, $devFiles);
207
            }
208
            $alternatives = $package->getAlternatives();
209
            if (is_string($alternatives)) {
210
                $this->alternatives = $this->readConfig($package, $alternatives);
211
            } elseif (is_array($alternatives)) {
212
                $this->alternatives = $alternatives;
213
            } elseif (!empty($alternatives)) {
214
                throw new BadConfigurationException('Alternatives must be array or path to configuration file.');
215
            }
216
        }
217
218
        $aliases = $this->aliasesCollector->collect($package);
219
220
        $this->builder->mergeAliases($aliases);
221
        $this->builder->setPackage($package->getPrettyName(), array_filter([
222
            'name' => $package->getPrettyName(),
223
            'version' => $package->getVersion(),
224
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
225
            'aliases' => $aliases,
226
        ]));
227
    }
228
229
    private function readConfig($package, $file): array
230
    {
231
        $path = $package->preparePath($file);
232
        if (!file_exists($path)) {
233
            throw new FailedReadException("failed read file: $file");
234
        }
235
        $reader = ReaderFactory::get($this->builder, $path);
236
237
        return $reader->read($path);
238
    }
239
240
    private function loadDotEnv(Package $package): void
241
    {
242
        $path = $package->preparePath('.env');
243
        if (file_exists($path) && class_exists(Dotenv::class)) {
244
            $this->addFile($package, 'envs', $path);
245
        }
246
    }
247
248
    /**
249
     * Adds given files to the list of files to be processed.
250
     * Prepares `constants` in reversed order (outer package first) because
251
     * constants cannot be redefined.
252
     *
253
     * @param Package $package
254
     * @param array $files
255
     */
256
    private function addFiles(Package $package, array $files): void
257
    {
258
        foreach ($files as $name => $paths) {
259
            $paths = (array) $paths;
260
            if ('constants' === $name) {
261
                $paths = array_reverse($paths);
262
            }
263
            foreach ($paths as $path) {
264
                $this->addFile($package, $name, $path);
265
            }
266
        }
267
    }
268
269
    private array $orderedFiles = [];
270
271
    private function addFile(Package $package, string $name, string $path): void
272
    {
273
        $path = $package->preparePath($path);
274
        if (!array_key_exists($name, $this->files)) {
275
            $this->files[$name] = [];
276
        }
277
        if (in_array($path, $this->files[$name], true)) {
278
            return;
279
        }
280
        if ('constants' === $name) {
281
            array_unshift($this->orderedFiles, $path);
282
            array_unshift($this->files[$name], $path);
283
        } else {
284
            $this->orderedFiles[] = $path;
285
            $this->files[$name][] = $path;
286
        }
287
    }
288
289
    private function collectPackages(Composer $composer): void
290
    {
291
        $vendorDir = $composer->getConfig()->get('vendor-dir');
292
        $rootPackage = $composer->getPackage();
293
        $packages = $composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
294
        $packageFinder = new PackageFinder($vendorDir, $rootPackage, $packages);
295
296
        $this->packages = $packageFinder->findPackages();
297
    }
298
}
299