Passed
Push — master ( cd14ff...da2bd7 )
by Alexander
03:37 queued 25s
created

Plugin   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 241
Duplicated Lines 0 %

Test Coverage

Coverage 80.98%

Importance

Changes 10
Bugs 0 Features 0
Metric Value
wmc 41
eloc 113
c 10
b 0
f 0
dl 0
loc 241
ccs 98
cts 121
cp 0.8098
rs 9.1199

13 Methods

Rating   Name   Duplication   Size   Complexity  
A buildAllConfigs() 0 10 1
A __construct() 0 6 1
A build() 0 19 2
A collectPackages() 0 8 1
A addFiles() 0 9 4
A orderFiles() 0 14 4
A readConfig() 0 9 2
B processPackage() 0 29 8
A scanPackages() 0 5 3
A getAllFiles() 0 17 5
A loadDotEnv() 0 5 3
A addFile() 0 15 4
A reorderFiles() 0 7 3

How to fix   Complexity   

Complex Class

Complex classes like Plugin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Plugin, and based on these observations, apply Extract Interface, too.

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 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...
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\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
    /**
46
     * @var IOInterface
47
     */
48
    private IOInterface $io;
49
50
    /**
51
     * Initializes the plugin object with the passed $composer and $io.
52
     *
53
     * @param Composer $composer
54
     * @param IOInterface $io
55
     */
56 2
    public function __construct(Composer $composer, IOInterface $io)
57
    {
58 2
        $baseDir = dirname($composer->getConfig()->get('vendor-dir')) . DIRECTORY_SEPARATOR;
59 2
        $this->builder = new Builder(new ConfigFactory(), realpath($baseDir));
60 2
        $this->io = $io;
61 2
        $this->collectPackages($composer);
62 2
    }
63
64 2
    public static function buildAllConfigs(string $projectRootPath): void
65
    {
66 2
        $factory = new \Composer\Factory();
67 2
        $output = $factory::createOutput();
68 2
        $input = new \Symfony\Component\Console\Input\ArgvInput([]);
69 2
        $helperSet = new \Symfony\Component\Console\Helper\HelperSet();
70 2
        $io = new \Composer\IO\ConsoleIO($input, $output, $helperSet);
71 2
        $composer = $factory->createComposer($io, $projectRootPath . '/composer.json', true, $projectRootPath, false);
72 2
        $plugin = new self($composer, $io);
73 2
        $plugin->build();
74 2
    }
75
76 2
    public function build(): void
77
    {
78 2
        $this->io->overwriteError('<info>Assembling config files</info>');
79
80 2
        $this->scanPackages();
81 2
        $this->reorderFiles();
82
83 2
        $this->builder->buildAllConfigs($this->files);
84
85 2
        $saveFiles = $this->files;
86 2
        $saveEnv = $_ENV;
87 2
        foreach ($this->alternatives as $name => $files) {
88
            $this->files = $saveFiles;
89
            $_ENV = $saveEnv;
90
            $builder = $this->builder->createAlternative($name);
91
            /** @psalm-suppress PossiblyNullArgument */
92
            $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

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

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