Completed
Push — master ( 224338...49f229 )
by Andrii
01:39
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 7
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, 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
        'defines' => [],
59
        'params'  => [],
60
    ];
61
62
    protected $aliases = [];
63
64
    protected $extensions = [];
65
66
    /**
67
     * @var array array of not yet merged params
68
     */
69
    protected $rawParams = [];
70
71
    /**
72
     * @var Composer instance
73
     */
74
    protected $composer;
75
76
    /**
77
     * @var IOInterface
78
     */
79
    public $io;
80
81
    /**
82
     * Initializes the plugin object with the passed $composer and $io.
83
     * @param Composer $composer
84
     * @param IOInterface $io
85
     */
86 2
    public function activate(Composer $composer, IOInterface $io)
87
    {
88 2
        $this->composer = $composer;
89 2
        $this->io = $io;
90 2
    }
91
92
    /**
93
     * Returns list of events the plugin is subscribed to.
94
     * @return array list of events
95
     */
96 1
    public static function getSubscribedEvents()
97
    {
98
        return [
99 1
            ScriptEvents::POST_AUTOLOAD_DUMP => [
100 1
                ['onPostAutoloadDump', 0],
101 1
            ],
102 1
        ];
103
    }
104
105
    /**
106
     * This is the main function.
107
     * @param Event $event
108
     */
109
    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...
110
    {
111
        $this->io->writeError('<info>Assembling config files</info>');
112
        $this->scanPackages();
113
114
        $builder = new Builder($this->files);
115
        $builder->setAddition(['aliases' => $this->aliases]);
116
        $builder->setIo($this->io);
117
        $builder->saveFiles();
118
        $builder->writeConfig('aliases', $this->aliases);
119
        $builder->writeConfig('extensions', $this->extensions);
120
        $builder->buildConfigs();
121
    }
122
123
    protected function scanPackages()
124
    {
125
        foreach ($this->getPackages() as $package) {
126
            if ($package instanceof CompletePackageInterface) {
127
                $this->processPackage($package);
128
            }
129
        }
130
    }
131
132
    /**
133
     * Scans the given package and collects extensions data.
134
     * @param PackageInterface $package
135
     */
136
    protected function processPackage(CompletePackageInterface $package)
137
    {
138
        $extra = $package->getExtra();
139
        $files = isset($extra[self::EXTRA_OPTION_NAME]) ? $extra[self::EXTRA_OPTION_NAME] : null;
140
141
        if ($package->getType() !== self::YII2_PACKAGE_TYPE && is_null($files)) {
142
            return;
143
        }
144
145
        if (is_array($files)) {
146
            $this->processFiles($package, $files);
147
        }
148
149
        $aliases = $this->collectAliases($package);
150
        $this->aliases = array_merge($this->aliases, $aliases);
151
152
        $this->extensions[$package->getPrettyName()] = array_filter([
153
            'name' => $package->getPrettyName(),
154
            'version' => $package->getVersion(),
155
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
156
            'aliases' => $aliases,
157
        ]);
158
    }
159
160
    protected function processFiles(CompletePackageInterface $package, array $files)
161
    {
162
        foreach ($files as $name => $pathes) {
163
            foreach ((array) $pathes as $path) {
164
                if (!isset($this->files[$name])) {
165
                    $this->files[$name] = [];
166
                }
167
                array_push($this->files[$name], $this->preparePath($package, $path));
168
            }
169
        }
170
    }
171
172
    /**
173
     * Collects package aliases.
174
     * @param CompletePackageInterface $package
175
     * @return array collected aliases
176
     */
177
    protected function collectAliases(CompletePackageInterface $package)
178
    {
179
        $aliases = array_merge(
180
            $this->prepareAliases($package, 'psr-0'),
181
            $this->prepareAliases($package, 'psr-4')
182
        );
183
        if ($package instanceof RootPackageInterface) {
184
            $aliases = array_merge($aliases,
185
                $this->prepareAliases($package, 'psr-0', true),
186
                $this->prepareAliases($package, 'psr-4', true)
187
            );
188
        }
189
190
        return $aliases;
191
    }
192
193
    /**
194
     * Prepare aliases.
195
     * @param PackageInterface $package
196
     * @param string 'psr-0' or 'psr-4'
197
     * @return array
198
     */
199
    protected function prepareAliases(PackageInterface $package, $psr, $dev = false)
200
    {
201
        $autoload = $dev ? $package->getDevAutoload() : $package->getAutoload();
202
        if (empty($autoload[$psr])) {
203
            return [];
204
        }
205
206
        $aliases = [];
207
        foreach ($autoload[$psr] as $name => $path) {
208
            if (is_array($path)) {
209
                // ignore psr-4 autoload specifications with multiple search paths
210
                // we can not convert them into aliases as they are ambiguous
211
                continue;
212
            }
213
            $name = str_replace('\\', '/', trim($name, '\\'));
214
            $path = $this->preparePath($package, $path);
215
            if ('psr-0' === $psr) {
216
                $path .= '/' . $name;
217
            }
218
            $aliases["@$name"] = $path;
219
        }
220
221
        return $aliases;
222
    }
223
224
    /**
225
     * Builds path inside of a package.
226
     * @param PackageInterface $package
227
     * @param mixed $path can be absolute or relative
228
     * @return string absolute pathes will stay untouched
229
     */
230
    public function preparePath(PackageInterface $package, $path)
231
    {
232
        $skippable = strncmp($path, '?', 1) === 0 ? '?' : '';
233 2
        if ($skippable) {
234
            $path = substr($path, 1);
235 2
        }
236 2
237
        if (!$this->getFilesystem()->isAbsolutePath($path)) {
238
            $prefix = $package instanceof RootPackageInterface
239
                ? $this->getBaseDir()
240
                : $this->getVendorDir() . '/' . $package->getPrettyName();
241
            $path = $prefix . '/' . $path;
242 1
        }
243
244 1
        return $skippable . $this->getFilesystem()->normalizePath($path);
245
    }
246
247
    /**
248 1
     * Sets [[packages]].
249
     * @param PackageInterface[] $packages
250
     */
251
    public function setPackages(array $packages)
252
    {
253
        $this->packages = $packages;
254
    }
255
256
    /**
257
     * Gets [[packages]].
258
     * @return \Composer\Package\PackageInterface[]
259
     */
260
    public function getPackages()
261
    {
262
        if ($this->packages === null) {
263
            $this->packages = $this->findPackages();
264
        }
265
266
        return $this->packages;
267
    }
268
269
    /**
270
     * Plain list of all project dependencies (including nested) as provided by composer.
271
     * The list is unordered (chaotic, can be different after every update).
272
     */
273
    protected $plainList = [];
274
275
    /**
276
     * Ordered list of package. Order @see findPackages.
277
     */
278
    protected $orderedList = [];
279
280
    /**
281
     * Returns ordered list of packages:
282
     * - listed earlier in the composer.json will get earlier in the list
283
     * - childs before parents.
284
     * @return \Composer\Package\PackageInterface[]
285
     */
286
    public function findPackages()
287
    {
288
        $root = $this->composer->getPackage();
289
        $this->plainList[$root->getPrettyName()] = $root;
290
        foreach ($this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages() as $package) {
291
            $this->plainList[$package->getPrettyName()] = $package;
292
        }
293
        $this->orderedList = [];
294
        $this->iteratePackage($root, true);
295
296
        if ($this->io->isVerbose()) {
297
            $indent = ' - ';
298
            $packages = $indent . implode("\n$indent", $this->orderedList);
299
            $this->io->writeError($packages);
300
        }
301
        $res = [];
302
        foreach ($this->orderedList as $name) {
303
            $res[] = $this->plainList[$name];
304
        }
305
306
        return $res;
307
    }
308
309
    /**
310
     * Iterates through package dependencies.
311
     * @param PackageInterface $package to iterate
312
     * @param bool $includingDev process development dependencies, defaults to not process
313
     */
314
    public function iteratePackage(PackageInterface $package, $includingDev = false)
315
    {
316
        $name = $package->getPrettyName();
317
318
        /// prevent infinite loop in case of circular dependencies
319
        static $processed = [];
320
        if (isset($processed[$name])) {
321
            return;
322
        } else {
323
            $processed[$name] = 1;
324
        }
325
326
        $this->iterateDependencies($package);
327
        if ($includingDev) {
328
            $this->iterateDependencies($package, true);
329
        }
330
        if (!isset($this->orderedList[$name])) {
331
            $this->orderedList[$name] = $name;
332
        }
333
    }
334
335
    /**
336
     * Iterates dependencies of the given package.
337
     * @param PackageInterface $package
338
     * @param bool $dev which dependencies to iterate: true - dev, default - general
339
     */
340
    public function iterateDependencies(PackageInterface $package, $dev = false)
341
    {
342
        $path = $this->preparePath($package, 'composer.json');
343
        if (file_exists($path)) {
344
            $conf = json_decode(file_get_contents($path), true);
345
            $what = $dev ? 'require-dev' : 'require';
346
            $deps = isset($conf[$what]) ? $conf[$what] : [];
347
        } else {
348
            $deps = $dev ? $package->getDevRequires() : $package->getRequires();
349
        }
350
        foreach (array_keys($deps) as $target) {
351
            if (isset($this->plainList[$target]) && !isset($this->orderedList[$target])) {
352
                $this->iteratePackage($this->plainList[$target]);
353
            }
354
        }
355
    }
356
357
    /**
358
     * Get absolute path to package base dir.
359
     * @return string
360
     */
361
    public function getBaseDir()
362
    {
363
        if ($this->baseDir === null) {
364
            $this->baseDir = dirname($this->getVendorDir());
365
        }
366
367
        return $this->baseDir;
368
    }
369
370
    /**
371
     * Get absolute path to composer vendor dir.
372
     * @return string
373
     */
374
    public function getVendorDir()
375
    {
376
        if ($this->vendorDir === null) {
377
            $dir = $this->composer->getConfig()->get('vendor-dir', '/');
378
            $this->vendorDir = $this->getFilesystem()->normalizePath($dir);
379
        }
380
381
        return $this->vendorDir;
382
    }
383
384
    /**
385
     * Getter for filesystem utility.
386
     * @return Filesystem
387
     */
388
    public function getFilesystem()
389
    {
390
        if ($this->filesystem === null) {
391
            $this->filesystem = new Filesystem();
392
        }
393
394
        return $this->filesystem;
395
    }
396
}
397