Passed
Pull Request — master (#8)
by Dmitriy
13:06
created

Plugin::collectPackages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 10
1
<?php
2
3
namespace Yiisoft\Composer\Config;
4
5
use Composer\Composer;
6
use Composer\IO\IOInterface;
7
use Composer\Util\Filesystem;
8
use Yiisoft\Composer\Config\Configs\ConfigFactory;
9
use Yiisoft\Composer\Config\Exceptions\BadConfigurationException;
10
use Yiisoft\Composer\Config\Exceptions\FailedReadException;
11
use Yiisoft\Composer\Config\Package\AliasesCollector;
12
use Yiisoft\Composer\Config\Package\PackageFinder;
13
use Yiisoft\Composer\Config\Readers\ReaderFactory;
14
15
final class Plugin
16
{
17
    /**
18
     * @var Package[] the array of active composer packages
19
     */
20
    private array $packages;
21
22
    private array $alternatives = [];
23
24
    private ?string $outputDir = null;
25
26
    private ?Package $rootPackage = null;
27
28
    /**
29
     * @var array config name => list of files
30
     */
31
    private array $files = [
32
        'envs' => [],
33
        'params' => [],
34
        'constants' => [],
35
    ];
36
37
    /**
38
     * @var array package name => configs as listed in `composer.json`
39
     */
40
    private array $originalFiles = [];
41
42
    private Builder $builder;
43
44
    /**
45
     * @var IOInterface
46
     */
47
    private IOInterface $io;
48
49
    private AliasesCollector $aliasesCollector;
50
51
    /**
52
     * Initializes the plugin object with the passed $composer and $io.
53
     *
54
     * @param Composer $composer
55
     * @param IOInterface $io
56
     */
57
    public function __construct(Composer $composer, IOInterface $io)
58
    {
59
        $baseDir = dirname($composer->getConfig()->get('vendor-dir')) . DIRECTORY_SEPARATOR;
60
        $this->builder = new Builder(new ConfigFactory(), realpath($baseDir));
61
        $this->aliasesCollector = new AliasesCollector(new Filesystem());
62
        $this->io = $io;
63
        $this->collectPackages($composer);
64
    }
65
66
    public function build(): void
67
    {
68
        $this->io->overwriteError('<info>Assembling config files</info>');
69
70
        $this->scanPackages();
71
        $this->reorderFiles();
72
73
        $this->builder->buildAllConfigs($this->files);
74
75
        $saveFiles = $this->files;
76
        $saveEnv = $_ENV;
77
        foreach ($this->alternatives as $name => $files) {
78
            $this->files = $saveFiles;
79
            $_ENV = $saveEnv;
80
            $builder = $this->builder->createAlternative($name);
81
            $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

81
            $this->addFiles(/** @scrutinizer ignore-type */ $this->rootPackage, $files);
Loading history...
82
            $builder->buildAllConfigs($this->files);
83
        }
84
    }
85
86
    private function scanPackages(): void
87
    {
88
        foreach ($this->packages as $package) {
89
            if ($package->isComplete()) {
90
                $this->processPackage($package);
91
            }
92
        }
93
    }
94
95
    private function reorderFiles(): void
96
    {
97
        foreach (array_keys($this->files) as $name) {
98
            $this->files[$name] = $this->getAllFiles($name);
99
        }
100
        foreach ($this->files as $name => $files) {
101
            $this->files[$name] = $this->orderFiles($files);
102
        }
103
    }
104
105
    private function getAllFiles(string $name, array $stack = []): array
106
    {
107
        if (empty($this->files[$name])) {
108
            return [];
109
        }
110
        $res = [];
111
        foreach ($this->files[$name] as $file) {
112
            if (strncmp($file, '$', 1) === 0) {
113
                if (!in_array($name, $stack, true)) {
114
                    $res = array_merge($res, $this->getAllFiles(substr($file, 1), array_merge($stack, [$name])));
115
                }
116
            } else {
117
                $res[] = $file;
118
            }
119
        }
120
121
        return $res;
122
    }
123
124
    private function orderFiles(array $files): array
125
    {
126
        if ($files === []) {
127
            return [];
128
        }
129
        $keys = array_combine($files, $files);
130
        $res = [];
131
        foreach ($this->orderedFiles as $file) {
132
            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

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