Passed
Pull Request — master (#67)
by Dmitriy
13:57
created

Plugin::addFile()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 15
ccs 0
cts 13
cp 0
rs 9.9
cc 4
nc 6
nop 3
crap 20
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 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...
9
use Yiisoft\Composer\Config\Config\ConfigFactory;
10
use Yiisoft\Composer\Config\Exception\BadConfigurationException;
11
use Yiisoft\Composer\Config\Exception\FailedReadException;
12
use Yiisoft\Composer\Config\Package\AliasesCollector;
13
use Yiisoft\Composer\Config\Package\PackageFinder;
14
use Yiisoft\Composer\Config\Reader\ReaderFactory;
15
16
final class Plugin
17
{
18
    /**
19
     * @var Package[] the array of active composer packages
20
     */
21
    private array $packages;
22
23
    private array $alternatives = [];
24
25
    private ?Package $rootPackage = null;
26
27
    /**
28
     * @var array config name => list of files
29
     * Important: defines config files processing order:
30
     * envs then constants then params then other configs
31
     */
32
    private array $files = [
33
        'envs' => [],
34
        'constants' => [],
35
        'params' => [],
36
    ];
37
38
    /**
39
     * @var array package name => configs as listed in `composer.json`
40
     */
41
    private array $originalFiles = [];
42
43
    private Builder $builder;
44
45
    private IOInterface $io;
46
47
    private AliasesCollector $aliasesCollector;
48
49
    /**
50
     * Initializes the plugin object with the passed $composer and $io.
51
     *
52
     * @param Composer $composer
53
     * @param IOInterface $io
54
     */
55
    public function __construct(Composer $composer, IOInterface $io)
56
    {
57
        $baseDir = dirname($composer->getConfig()->get('vendor-dir')) . DIRECTORY_SEPARATOR;
58
        $this->builder = new Builder(new ConfigFactory(), realpath($baseDir));
59
        $this->aliasesCollector = new AliasesCollector(new Filesystem());
60
        $this->io = $io;
61
        $this->collectPackages($composer);
62
    }
63
64
    public function build(): void
65
    {
66
        $this->io->overwriteError('<info>Assembling config files</info>');
67
68
        $this->scanPackages();
69
        $this->reorderFiles();
70
71
        $this->builder->buildAllConfigs($this->files);
72
73
        $saveFiles = $this->files;
74
        $saveEnv = getenv();
75
        foreach ($this->alternatives as $name => $files) {
76
            $this->files = $saveFiles;
77
            $this->overloadEnvs($saveEnv);
0 ignored issues
show
Bug introduced by
$saveEnv of type string is incompatible with the type array expected by parameter $envs of Yiisoft\Composer\Config\Plugin::overloadEnvs(). ( Ignorable by Annotation )

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

77
            $this->overloadEnvs(/** @scrutinizer ignore-type */ $saveEnv);
Loading history...
78
            $builder = $this->builder->createAlternative($name);
79
            $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

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

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