Completed
Push — master ( 078c48...f64aa6 )
by Andrii
03:23
created

Plugin::getPackages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.2559

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 5
cp 0.6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
crap 2.2559
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-2017, 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\Package\CompletePackageInterface;
17
use Composer\Package\PackageInterface;
18
use Composer\Package\RootPackageInterface;
19
use Composer\Plugin\PluginInterface;
20
use Composer\Script\Event;
21
use Composer\Script\ScriptEvents;
22
use Composer\Util\Filesystem;
23
24
/**
25
 * Plugin class.
26
 *
27
 * @author Andrii Vasyliev <[email protected]>
28
 */
29
class Plugin implements PluginInterface, EventSubscriberInterface
30
{
31
    const YII2_PACKAGE_TYPE = 'yii2-extension';
32
    const EXTRA_OPTION_NAME = 'config-plugin';
33
34
    /**
35
     * @var PackageInterface[] the array of active composer packages
36
     */
37
    protected $packages;
38
39
    /**
40
     * @var string absolute path to the package base directory
41
     */
42
    protected $baseDir;
43
44
    /**
45
     * @var string absolute path to vendor directory
46
     */
47
    protected $vendorDir;
48
49
    /**
50
     * @var Filesystem utility
51
     */
52
    protected $filesystem;
53
54
    /**
55
     * @var array config name => list of files
56
     */
57
    protected $files = [
58
        'dotenv'  => [],
59
        'defines' => [],
60
        'params'  => [],
61
    ];
62
63
    /**
64
     * @var array package name => configs as listed in `composer.json`
65
     */
66
    protected $originalFiles = [];
67
68
    protected $aliases = [];
69
70
    protected $extensions = [];
71
72
    /**
73
     * @var array array of not yet merged params
74
     */
75
    protected $rawParams = [];
76
77
    /**
78
     * @var Composer instance
79
     */
80
    protected $composer;
81
82
    /**
83
     * @var IOInterface
84
     */
85
    public $io;
86
87
    /**
88
     * Initializes the plugin object with the passed $composer and $io.
89
     * @param Composer $composer
90
     * @param IOInterface $io
91
     */
92 2
    public function activate(Composer $composer, IOInterface $io)
93
    {
94 2
        $this->composer = $composer;
95 2
        $this->io = $io;
96 2
    }
97
98
    /**
99
     * Returns list of events the plugin is subscribed to.
100
     * @return array list of events
101
     */
102 1
    public static function getSubscribedEvents()
103
    {
104
        return [
105 1
            ScriptEvents::POST_AUTOLOAD_DUMP => [
106 1
                ['onPostAutoloadDump', 0],
107 1
            ],
108 1
        ];
109
    }
110
111
    /**
112
     * This is the main function.
113
     * @param Event $event
114
     */
115
    public function onPostAutoloadDump(Event $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

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

Loading history...
116
    {
117
        $this->io->writeError('<info>Assembling config files</info>');
118
        $this->initAutoload();
119
        $this->scanPackages();
120
        $this->showDepsTree();
121
122
        $builder = new Builder($this->files);
123
        $builder->setAddition(['aliases' => $this->aliases]);
124
        $builder->setIo($this->io);
125
        $builder->saveFiles();
126
        $builder->writeConfig('aliases', $this->aliases);
127
        $builder->writeConfig('extensions', $this->extensions);
128
        $builder->buildConfigs();
129
    }
130
131
    protected function initAutoload()
132
    {
133
        require_once dirname(dirname(dirname(__DIR__))) . '/autoload.php';
134
    }
135
136
    protected function scanPackages()
137
    {
138
        foreach ($this->getPackages() as $package) {
139
            if ($package instanceof CompletePackageInterface) {
140
                $this->processPackage($package);
141
            }
142
        }
143
    }
144
145
    /**
146
     * Scans the given package and collects extensions data.
147
     * @param PackageInterface $package
148
     */
149
    protected function processPackage(CompletePackageInterface $package)
150
    {
151
        $extra = $package->getExtra();
152
        $files = isset($extra[self::EXTRA_OPTION_NAME]) ? $extra[self::EXTRA_OPTION_NAME] : null;
153
        $this->originalFiles[$package->getPrettyName()] = $files;
154
155
        if (self::YII2_PACKAGE_TYPE !== $package->getType() && is_null($files)) {
156
            return;
157
        }
158
159
        if (is_array($files)) {
160
            $this->addFiles($package, $files);
161
        }
162
        if ($package instanceof RootPackageInterface) {
163
            $this->loadDotEnv($package);
164
        }
165
166
        $aliases = $this->collectAliases($package);
167
        $this->aliases = array_merge($this->aliases, $aliases);
168
169
        $this->extensions[$package->getPrettyName()] = array_filter([
170
            'name' => $package->getPrettyName(),
171
            'version' => $package->getVersion(),
172
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
173
            'aliases' => $aliases,
174
        ]);
175
    }
176
177
    protected function loadDotEnv(RootPackageInterface $package)
178
    {
179
        $path = $this->preparePath($package, '.env');
180
        if (file_exists($path) && class_exists('Dotenv\Dotenv')) {
181
            array_push($this->files['dotenv'], $path);
182
        }
183
    }
184
185
    /**
186
     * Adds given files to the list of files to be processed.
187
     * Prepares `defines` in reversed order (outer package first) because
188
     * constants cannot be redefined.
189
     * @param CompletePackageInterface $package
190
     * @param array $files
191
     */
192
    protected function addFiles(CompletePackageInterface $package, array $files)
193
    {
194
        foreach ($files as $name => $paths) {
195
            $paths = (array) $paths;
196
            if ('defines' === $name) {
197
                $paths = array_reverse($paths);
198
            }
199
            foreach ($paths as $path) {
200
                if (!isset($this->files[$name])) {
201
                    $this->files[$name] = [];
202
                }
203
                $path = $this->preparePath($package, $path);
204
                if ('defines' === $name) {
205
                    array_unshift($this->files[$name], $path);
206
                } else {
207
                    array_push($this->files[$name], $path);
208
                }
209
            }
210
        }
211
    }
212
213
    /**
214
     * Collects package aliases.
215
     * @param CompletePackageInterface $package
216
     * @return array collected aliases
217
     */
218
    protected function collectAliases(CompletePackageInterface $package)
219
    {
220
        $aliases = array_merge(
221
            $this->prepareAliases($package, 'psr-0'),
222
            $this->prepareAliases($package, 'psr-4')
223
        );
224
        if ($package instanceof RootPackageInterface) {
225
            $aliases = array_merge($aliases,
226
                $this->prepareAliases($package, 'psr-0', true),
227
                $this->prepareAliases($package, 'psr-4', true)
228
            );
229
        }
230
231
        return $aliases;
232
    }
233
234
    /**
235
     * Prepare aliases.
236
     * @param PackageInterface $package
237
     * @param string 'psr-0' or 'psr-4'
238
     * @return array
239
     */
240
    protected function prepareAliases(PackageInterface $package, $psr, $dev = false)
241
    {
242
        $autoload = $dev ? $package->getDevAutoload() : $package->getAutoload();
243
        if (empty($autoload[$psr])) {
244
            return [];
245
        }
246
247
        $aliases = [];
248
        foreach ($autoload[$psr] as $name => $path) {
249
            if (is_array($path)) {
250
                // ignore psr-4 autoload specifications with multiple search paths
251
                // we can not convert them into aliases as they are ambiguous
252
                continue;
253
            }
254
            $name = str_replace('\\', '/', trim($name, '\\'));
255
            $path = $this->preparePath($package, $path);
256
            if ('psr-0' === $psr) {
257
                $path .= '/' . $name;
258
            }
259
            $aliases["@$name"] = $path;
260
        }
261
262
        return $aliases;
263
    }
264
265
    /**
266
     * Builds path inside of a package.
267
     * @param PackageInterface $package
268
     * @param mixed $path can be absolute or relative
269
     * @return string absolute paths will stay untouched
270
     */
271
    public function preparePath(PackageInterface $package, $path)
272
    {
273
        if (0 === strncmp($path, '$', 1)) {
274
            return $path;
275
        }
276
277
        $skippable = 0 === strncmp($path, '?', 1) ? '?' : '';
278
        if ($skippable) {
279
            $path = substr($path, 1);
280
        }
281
282
        if (!$this->getFilesystem()->isAbsolutePath($path)) {
283
            $prefix = $package instanceof RootPackageInterface
284
                ? $this->getBaseDir()
285
                : $this->getVendorDir() . '/' . $package->getPrettyName();
286
            $path = $prefix . '/' . $path;
287
        }
288
289
        return $skippable . $this->getFilesystem()->normalizePath($path);
290
    }
291
292
    /**
293
     * Sets [[packages]].
294
     * @param PackageInterface[] $packages
295
     */
296 2
    public function setPackages(array $packages)
297
    {
298 2
        $this->packages = $packages;
299 2
    }
300
301
    /**
302
     * Gets [[packages]].
303
     * @return \Composer\Package\PackageInterface[]
304
     */
305 1
    public function getPackages()
306
    {
307 1
        if (null === $this->packages) {
308
            $this->packages = $this->findPackages();
309
        }
310
311 1
        return $this->packages;
312
    }
313
314
    /**
315
     * Plain list of all project dependencies (including nested) as provided by composer.
316
     * The list is unordered (chaotic, can be different after every update).
317
     */
318
    protected $plainList = [];
319
320
    /**
321
     * Ordered list of package in form: package => depth
322
     * For order description @see findPackages.
323
     */
324
    protected $orderedList = [];
325
326
    /**
327
     * Returns ordered list of packages:
328
     * - listed earlier in the composer.json will get earlier in the list
329
     * - childs before parents.
330
     * @return \Composer\Package\PackageInterface[]
331
     */
332
    public function findPackages()
333
    {
334
        $root = $this->composer->getPackage();
335
        $this->plainList[$root->getPrettyName()] = $root;
336
        foreach ($this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages() as $package) {
337
            $this->plainList[$package->getPrettyName()] = $package;
338
        }
339
        $this->orderedList = [];
340
        $this->iteratePackage($root, true);
341
342
        $res = [];
343
        foreach (array_keys($this->orderedList) as $name) {
344
            $res[] = $this->plainList[$name];
345
        }
346
347
        return $res;
348
    }
349
350
    /**
351
     * Iterates through package dependencies.
352
     * @param PackageInterface $package to iterate
353
     * @param bool $includingDev process development dependencies, defaults to not process
354
     */
355
    protected function iteratePackage(PackageInterface $package, $includingDev = false)
356
    {
357
        $name = $package->getPrettyName();
358
359
        /// prevent infinite loop in case of circular dependencies
360
        static $processed = [];
361
        if (isset($processed[$name])) {
362
            return;
363
        } else {
364
            $processed[$name] = 1;
365
        }
366
367
        /// package depth in dependency hierarchy
368
        static $depth = 0;
369
        ++$depth;
370
371
        $this->iterateDependencies($package);
372
        if ($includingDev) {
373
            $this->iterateDependencies($package, true);
374
        }
375
        if (!isset($this->orderedList[$name])) {
376
            $this->orderedList[$name] = $depth;
377
        }
378
379
        --$depth;
380
    }
381
382
    /**
383
     * Iterates dependencies of the given package.
384
     * @param PackageInterface $package
385
     * @param bool $dev which dependencies to iterate: true - dev, default - general
386
     */
387
    protected function iterateDependencies(PackageInterface $package, $dev = false)
388
    {
389
        $path = $this->preparePath($package, 'composer.json');
390
        if (file_exists($path)) {
391
            $conf = json_decode(file_get_contents($path), true);
392
            $what = $dev ? 'require-dev' : 'require';
393
            $deps = isset($conf[$what]) ? $conf[$what] : [];
394
        } else {
395
            $deps = $dev ? $package->getDevRequires() : $package->getRequires();
396
        }
397
        foreach (array_keys($deps) as $target) {
398
            if (isset($this->plainList[$target]) && empty($this->orderedList[$target])) {
399
                $this->iteratePackage($this->plainList[$target]);
400
            }
401
        }
402
    }
403
404
    protected function showDepsTree()
405
    {
406
        if (!$this->io->isVerbose()) {
407
            return;
408
        }
409
410
        foreach (array_reverse($this->orderedList) as $name => $depth) {
411
            $deps = $this->originalFiles[$name];
412
            $color = $this->colors[$depth % count($this->colors)];
413
            $indent = str_repeat('   ', $depth - 1);
414
            $package = $this->plainList[$name];
415
            $showdeps = $deps ? '<comment>[' . implode(',', array_keys($deps)) . ']</>' : '';
416
            $this->io->write(sprintf('%s - <fg=%s;options=bold>%s</> %s %s', $indent, $color, $name, $package->getFullPrettyVersion(), $showdeps));
417
        }
418
    }
419
420
    protected $colors = ['red', 'green', 'yellow', 'cyan', 'magenta', 'blue'];
421
422
    /**
423
     * Get absolute path to package base dir.
424
     * @return string
425
     */
426
    public function getBaseDir()
427
    {
428
        if (null === $this->baseDir) {
429
            $this->baseDir = dirname($this->getVendorDir());
430
        }
431
432
        return $this->baseDir;
433
    }
434
435
    /**
436
     * Get absolute path to composer vendor dir.
437
     * @return string
438
     */
439
    public function getVendorDir()
440
    {
441
        if (null === $this->vendorDir) {
442
            $dir = $this->composer->getConfig()->get('vendor-dir');
443
            $this->vendorDir = $this->getFilesystem()->normalizePath($dir);
444
        }
445
446
        return $this->vendorDir;
447
    }
448
449
    /**
450
     * Getter for filesystem utility.
451
     * @return Filesystem
452
     */
453
    public function getFilesystem()
454
    {
455
        if (null === $this->filesystem) {
456
            $this->filesystem = new Filesystem();
457
        }
458
459
        return $this->filesystem;
460
    }
461
}
462