Completed
Pull Request — master (#3)
by Lukyanov
03:33
created

Plugin::collectAliases()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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