Passed
Pull Request — master (#3)
by Dmitriy
10:28
created

Plugin   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 264
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 116
c 2
b 0
f 0
dl 0
loc 264
rs 9.0399
wmc 42

13 Methods

Rating   Name   Duplication   Size   Complexity  
A orderFiles() 0 14 4
A readConfig() 0 9 2
B processPackage() 0 34 8
A getAllFiles() 0 17 5
A reorderFiles() 0 7 3
A addFiles() 0 9 4
A loadDotEnv() 0 5 3
A addFile() 0 15 4
A scanPackages() 0 5 3
A getSubscribedEvents() 0 5 1
A activate() 0 7 1
A getPackages() 0 7 2
A onPostAutoloadDump() 0 19 2

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
namespace Yiisoft\Composer\Config;
4
5
use Composer\Composer;
6
use Composer\EventDispatcher\EventSubscriberInterface;
7
use Composer\IO\IOInterface;
8
use Composer\Plugin\PluginInterface;
9
use Composer\Script\Event;
10
use Composer\Script\ScriptEvents;
11
use Composer\Util\Filesystem;
12
use Yiisoft\Composer\Config\exceptions\BadConfigurationException;
13
use Yiisoft\Composer\Config\exceptions\FailedReadException;
14
use Yiisoft\Composer\Config\Package\AliasesCollector;
15
use Yiisoft\Composer\Config\Package\PackageFinder;
16
use Yiisoft\Composer\Config\readers\ReaderFactory;
17
18
/**
19
 * Plugin class.
20
 */
21
class Plugin implements PluginInterface, EventSubscriberInterface
22
{
23
    /**
24
     * @var Package[] the array of active composer packages
25
     */
26
    private array $packages = [];
27
28
    private array $alternatives = [];
29
30
    private ?string $outputDir = null;
31
32
    private ?Package $rootPackage = null;
33
34
    /**
35
     * @var array config name => list of files
36
     */
37
    private array $files = [
38
        'dotenv' => [],
39
        'defines' => [],
40
        'params' => [],
41
    ];
42
43
    /**
44
     * @var array package name => configs as listed in `composer.json`
45
     */
46
    private array $originalFiles = [];
47
48
    /**
49
     * @var Builder
50
     */
51
    private Builder $builder;
52
53
    /**
54
     * @var Composer instance
55
     */
56
    private Composer $composer;
57
58
    /**
59
     * @var IOInterface
60
     */
61
    private IOInterface $io;
62
63
    private PackageFinder $packageFinder;
64
65
    private AliasesCollector $aliasesCollector;
66
67
    /**
68
     * Initializes the plugin object with the passed $composer and $io.
69
     *
70
     * @param Composer $composer
71
     * @param IOInterface $io
72
     */
73
    public function activate(Composer $composer, IOInterface $io): void
74
    {
75
        $this->builder = new Builder();
76
        $this->packageFinder = new PackageFinder($composer);
77
        $this->aliasesCollector = new AliasesCollector(new Filesystem());
78
        $this->composer = $composer;
79
        $this->io = $io;
80
    }
81
82
    /**
83
     * Returns list of events the plugin is subscribed to.
84
     * @return array list of events
85
     */
86
    public static function getSubscribedEvents(): array
87
    {
88
        return [
89
            ScriptEvents::POST_AUTOLOAD_DUMP => [
90
                ['onPostAutoloadDump', 0],
91
            ],
92
        ];
93
    }
94
95
    /**
96
     * This is the main function.
97
     */
98
    public function onPostAutoloadDump(Event $event): void
99
    {
100
        $this->io->overwriteError('<info>Assembling config files</info>');
101
102
        require_once $event->getComposer()->getConfig()->get('vendor-dir') . '/autoload.php';
103
        $this->scanPackages();
104
        $this->reorderFiles();
105
106
        $this->builder->setOutputDir($this->outputDir);
107
        $this->builder->buildAllConfigs($this->files);
108
109
        $saveFiles = $this->files;
110
        $saveEnv = $_ENV;
111
        foreach ($this->alternatives as $name => $files) {
112
            $this->files = $saveFiles;
113
            $_ENV = $saveEnv;
114
            $builder = $this->builder->createAlternative($name);
115
            $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

115
            $this->addFiles(/** @scrutinizer ignore-type */ $this->rootPackage, $files);
Loading history...
116
            $builder->buildAllConfigs($this->files);
117
        }
118
    }
119
120
    private function scanPackages(): void
121
    {
122
        foreach ($this->getPackages() as $package) {
123
            if ($package->isComplete()) {
124
                $this->processPackage($package);
125
            }
126
        }
127
    }
128
129
    private function reorderFiles(): void
130
    {
131
        foreach (array_keys($this->files) as $name) {
132
            $this->files[$name] = $this->getAllFiles($name);
133
        }
134
        foreach ($this->files as $name => $files) {
135
            $this->files[$name] = $this->orderFiles($files);
136
        }
137
    }
138
139
    private function getAllFiles(string $name, array $stack = []): array
140
    {
141
        if (empty($this->files[$name])) {
142
            return[];
143
        }
144
        $res = [];
145
        foreach ($this->files[$name] as $file) {
146
            if (strncmp($file, '$', 1) === 0) {
147
                if (!in_array($name, $stack, true)) {
148
                    $res = array_merge($res, $this->getAllFiles(substr($file, 1), array_merge($stack, [$name])));
149
                }
150
            } else {
151
                $res[] = $file;
152
            }
153
        }
154
155
        return $res;
156
    }
157
158
    private function orderFiles(array $files): array
159
    {
160
        if (empty($files)) {
161
            return [];
162
        }
163
        $keys = array_combine($files, $files);
164
        $res = [];
165
        foreach ($this->orderedFiles as $file) {
166
            if (isset($keys[$file])) {
167
                $res[$file] = $file;
168
            }
169
        }
170
171
        return array_values($res);
172
    }
173
174
    /**
175
     * Scans the given package and collects packages data.
176
     * @param Package $package
177
     */
178
    private function processPackage(Package $package)
179
    {
180
        $files = $package->getFiles();
181
        $this->originalFiles[$package->getPrettyName()] = $files;
182
183
        if (!empty($files)) {
184
            $this->addFiles($package, $files);
185
        }
186
        if ($package->isRoot()) {
187
            $this->rootPackage = $package;
188
            $this->loadDotEnv($package);
189
            $devFiles = $package->getDevFiles();
190
            if (!empty($devFiles)) {
191
                $this->addFiles($package, $devFiles);
192
            }
193
            $this->outputDir = $package->getOutputDir();
194
            $alternatives = $package->getAlternatives();
195
            if (is_string($alternatives)) {
0 ignored issues
show
introduced by
The condition is_string($alternatives) is always false.
Loading history...
196
                $this->alternatives = $this->readConfig($package, $alternatives);
197
            } elseif (is_array($alternatives)) {
0 ignored issues
show
introduced by
The condition is_array($alternatives) is always true.
Loading history...
198
                $this->alternatives = $alternatives;
199
            } elseif (!empty($alternatives)) {
200
                throw new BadConfigurationException('Alternatives must be array or path to configuration file.');
201
            }
202
        }
203
204
        $aliases = $this->aliasesCollector->collect($package);
205
206
        $this->builder->mergeAliases($aliases);
207
        $this->builder->setPackage($package->getPrettyName(), array_filter([
208
            'name' => $package->getPrettyName(),
209
            'version' => $package->getVersion(),
210
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
211
            'aliases' => $aliases,
212
        ]));
213
    }
214
215
    private function readConfig($package, $file): array
216
    {
217
        $path = $package->preparePath($file);
218
        if (!file_exists($path)) {
219
            throw new FailedReadException("failed read file: $file");
220
        }
221
        $reader = ReaderFactory::get($this->builder, $path);
222
223
        return $reader->read($path);
224
    }
225
226
    private function loadDotEnv(Package $package): void
227
    {
228
        $path = $package->preparePath('.env');
229
        if (file_exists($path) && class_exists('Dotenv\Dotenv')) {
230
            $this->addFile($package, 'dotenv', $path);
231
        }
232
    }
233
234
    /**
235
     * Adds given files to the list of files to be processed.
236
     * Prepares `defines` in reversed order (outer package first) because
237
     * constants cannot be redefined.
238
     * @param Package $package
239
     * @param array $files
240
     */
241
    private function addFiles(Package $package, array $files): void
242
    {
243
        foreach ($files as $name => $paths) {
244
            $paths = (array) $paths;
245
            if ('defines' === $name) {
246
                $paths = array_reverse($paths);
247
            }
248
            foreach ($paths as $path) {
249
                $this->addFile($package, $name, $path);
250
            }
251
        }
252
    }
253
254
    private array $orderedFiles = [];
255
256
    private function addFile(Package $package, string $name, string $path): void
257
    {
258
        $path = $package->preparePath($path);
259
        if (!isset($this->files[$name])) {
260
            $this->files[$name] = [];
261
        }
262
        if (in_array($path, $this->files[$name], true)) {
263
            return;
264
        }
265
        if ('defines' === $name) {
266
            array_unshift($this->orderedFiles, $path);
267
            array_unshift($this->files[$name], $path);
268
        } else {
269
            $this->orderedFiles[] = $path;
270
            $this->files[$name][] = $path;
271
        }
272
    }
273
274
    /**
275
     * Gets [[packages]].
276
     * @return Package[]
277
     */
278
    private function getPackages(): array
279
    {
280
        if ([] === $this->packages) {
281
            $this->packages = $this->packageFinder->findPackages();
282
        }
283
284
        return $this->packages;
285
    }
286
287
}
288