Completed
Push — master ( 753470...8ba86d )
by Andrii
11:15
created

Plugin::processPackage()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 21
ccs 0
cts 10
cp 0
rs 9.4888
c 0
b 0
f 0
cc 5
nc 8
nop 1
crap 30
1
<?php
2
/**
3
 * Composer plugin for config assembling
4
 *
5
 * @link      https://github.com/hiqdev/composer-config-plugin
6
 * @package   composer-config-plugin
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\composer\config;
12
13
use Composer\Composer;
14
use Composer\EventDispatcher\EventSubscriberInterface;
15
use Composer\IO\IOInterface;
16
use Composer\Plugin\PluginInterface;
17
use Composer\Script\Event;
18
use Composer\Script\ScriptEvents;
19
20
/**
21
 * Plugin class.
22
 *
23
 * @author Andrii Vasyliev <[email protected]>
24
 */
25
class Plugin implements PluginInterface, EventSubscriberInterface
26
{
27
    const EXTRA_OPTION_NAME = 'config-plugin';
28
29
    /**
30
     * @var Package[] the array of active composer packages
31
     */
32
    protected $packages;
33
34
    /**
35
     * @var array config name => list of files
36
     */
37
    protected $files = [
38
        'dotenv'  => [],
39
        'aliases' => [],
40
        'defines' => [],
41
        'params'  => [],
42
    ];
43
44
    /**
45
     * @var array package name => configs as listed in `composer.json`
46
     */
47
    protected $originalFiles = [];
48
49
    /**
50
     * @var Builder
51
     */
52
    protected $builder;
53
54
    /**
55
     * @var Composer instance
56
     */
57
    protected $composer;
58
59
    /**
60
     * @var IOInterface
61
     */
62
    public $io;
63
64
    /**
65
     * Initializes the plugin object with the passed $composer and $io.
66
     * @param Composer $composer
67
     * @param IOInterface $io
68
     */
69
    public function activate(Composer $composer, IOInterface $io)
70
    {
71
        $this->composer = $composer;
72
        $this->io = $io;
73
    }
74
75
    /**
76
     * Returns list of events the plugin is subscribed to.
77
     * @return array list of events
78
     */
79
    public static function getSubscribedEvents()
80
    {
81
        return [
82
            ScriptEvents::POST_AUTOLOAD_DUMP => [
83
                ['onPostAutoloadDump', 0],
84
            ],
85
        ];
86
    }
87
88 2
    /**
89
     * This is the main function.
90 2
     * @param Event $event
91 2
     */
92 2
    public function onPostAutoloadDump(Event $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed. ( Ignorable by Annotation )

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

92
    public function onPostAutoloadDump(/** @scrutinizer ignore-unused */ Event $event)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
93
    {
94
        $this->io->writeError('<info>Assembling config files</info>');
95
96
        $this->builder = new Builder();
97
98 1
        $this->initAutoload();
99
        $this->scanPackages();
100
        $this->showDepsTree();
101 1
102
        $this->builder->buildAllConfigs($this->files);
103
    }
104
105
    protected function initAutoload()
106
    {
107
        $dir = dirname(dirname(dirname(__DIR__)));
108
        require_once "$dir/autoload.php";
109
    }
110
111
    protected function scanPackages()
112
    {
113
        foreach ($this->getPackages() as $package) {
114
            if ($package->isComplete()) {
115
                $this->processPackage($package);
116
            }
117
        }
118
    }
119
120
    /**
121
     * Scans the given package and collects packages data.
122
     * @param Package $package
123
     */
124
    protected function processPackage(Package $package)
125
    {
126
        $extra = $package->getExtra();
127
        $files = isset($extra[self::EXTRA_OPTION_NAME]) ? $extra[self::EXTRA_OPTION_NAME] : null;
128
        $this->originalFiles[$package->getPrettyName()] = $files;
129
130
        if (is_array($files)) {
131
            $this->addFiles($package, $files);
132
        }
133
        if ($package->isRoot()) {
134
            $this->loadDotEnv($package);
135
        }
136
137
        $aliases = $package->collectAliases();
138
139
        $this->builder->mergeAliases($aliases);
140
        $this->builder->setPackage($package->getPrettyName(), array_filter([
141
            'name' => $package->getPrettyName(),
142
            'version' => $package->getVersion(),
143
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
144
            'aliases' => $aliases,
145
        ]));
146
    }
147
148
    protected function loadDotEnv(Package $package)
149
    {
150
        $path = $package->preparePath('.env');
151
        if (file_exists($path) && class_exists('Dotenv\Dotenv')) {
152
            array_push($this->files['dotenv'], $path);
153
        }
154
    }
155
156
    /**
157
     * Adds given files to the list of files to be processed.
158
     * Prepares `defines` in reversed order (outer package first) because
159
     * constants cannot be redefined.
160
     * @param Package $package
161
     * @param array $files
162
     */
163
    protected function addFiles(Package $package, array $files)
164
    {
165
        foreach ($files as $name => $paths) {
166
            $paths = (array) $paths;
167
            if ('defines' === $name) {
168
                $paths = array_reverse($paths);
169
            }
170
            foreach ($paths as $path) {
171
                if (!isset($this->files[$name])) {
172
                    $this->files[$name] = [];
173
                }
174
                $path = $package->preparePath($path);
175
                if (in_array($path, $this->files[$name], true)) {
176
                    continue;
177
                }
178
                if ('defines' === $name) {
179
                    array_unshift($this->files[$name], $path);
180
                } else {
181
                    array_push($this->files[$name], $path);
182
                }
183
            }
184
        }
185
    }
186
187
    /**
188
     * Sets [[packages]].
189
     * @param Package[] $packages
190
     */
191
    public function setPackages(array $packages)
192
    {
193
        $this->packages = $packages;
194
    }
195
196
    /**
197
     * Gets [[packages]].
198
     * @return Package[]
199
     */
200
    public function getPackages()
201
    {
202
        if (null === $this->packages) {
203
            $this->packages = $this->findPackages();
204
        }
205
206
        return $this->packages;
207
    }
208
209
    /**
210
     * Plain list of all project dependencies (including nested) as provided by composer.
211
     * The list is unordered (chaotic, can be different after every update).
212
     */
213
    protected $plainList = [];
214
215
    /**
216
     * Ordered list of package in form: package => depth
217
     * For order description @see findPackages.
218
     */
219
    protected $orderedList = [];
220
221
    /**
222
     * Returns ordered list of packages:
223
     * - listed earlier in the composer.json will get earlier in the list
224
     * - childs before parents.
225
     * @return Package[]
226
     */
227
    public function findPackages()
228
    {
229
        $root = new Package($this->composer->getPackage(), $this->composer);
230
        $this->plainList[$root->getPrettyName()] = $root;
231
        foreach ($this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages() as $package) {
232
            $this->plainList[$package->getPrettyName()] = new Package($package, $this->composer);
233
        }
234
        $this->orderedList = [];
235
        $this->iteratePackage($root, true);
236
237
        $res = [];
238
        foreach (array_keys($this->orderedList) as $name) {
239
            $res[] = $this->plainList[$name];
240
        }
241
242
        return $res;
243
    }
244
245
    /**
246
     * Iterates through package dependencies.
247
     * @param Package $package to iterate
248
     * @param bool $includingDev process development dependencies, defaults to not process
249
     */
250
    protected function iteratePackage(Package $package, $includingDev = false)
251
    {
252
        $name = $package->getPrettyName();
253
254
        /// prevent infinite loop in case of circular dependencies
255
        static $processed = [];
256
        if (isset($processed[$name])) {
257
            return;
258
        } else {
259
            $processed[$name] = 1;
260
        }
261
262
        /// package depth in dependency hierarchy
263
        static $depth = 0;
264
        ++$depth;
265
266
        $this->iterateDependencies($package);
267
        if ($includingDev) {
268
            $this->iterateDependencies($package, true);
269
        }
270
        if (!isset($this->orderedList[$name])) {
271
            $this->orderedList[$name] = $depth;
272
        }
273
274
        --$depth;
275
    }
276
277
    /**
278
     * Iterates dependencies of the given package.
279
     * @param Package $package
280
     * @param bool $dev which dependencies to iterate: true - dev, default - general
281
     */
282
    protected function iterateDependencies(Package $package, $dev = false)
283
    {
284
        $deps = $dev ? $package->getDevRequires() : $package->getRequires();
285
        foreach (array_keys($deps) as $target) {
286
            if (isset($this->plainList[$target]) && empty($this->orderedList[$target])) {
287
                $this->iteratePackage($this->plainList[$target]);
288
            }
289
        }
290
    }
291
292
    protected function showDepsTree()
293 2
    {
294
        if (!$this->io->isVerbose()) {
295 2
            return;
296 2
        }
297
298
        foreach (array_reverse($this->orderedList) as $name => $depth) {
299
            $deps = $this->originalFiles[$name];
300
            $color = $this->colors[$depth % count($this->colors)];
301
            $indent = str_repeat('   ', $depth - 1);
302 1
            $package = $this->plainList[$name];
303
            $showdeps = $deps ? '<comment>[' . implode(',', array_keys($deps)) . ']</>' : '';
304 1
            $this->io->write(sprintf('%s - <fg=%s;options=bold>%s</> %s %s', $indent, $color, $name, $package->getFullPrettyVersion(), $showdeps));
305
        }
306
    }
307
308 1
    protected $colors = ['red', 'green', 'yellow', 'cyan', 'magenta', 'blue'];
309
}
310