Completed
Push — master ( c71fd6...224338 )
by Andrii
01:54
created

Plugin::findPackages()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 0
cts 18
cp 0
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 15
nc 8
nop 0
crap 20
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 = array_merge(
150
            $this->prepareAliases($package, 'psr-0'),
151
            $this->prepareAliases($package, 'psr-4')
152
        );
153
        $this->aliases = array_merge($this->aliases, $aliases);
154
155
        $this->extensions[$package->getPrettyName()] = array_filter([
156
            'name' => $package->getPrettyName(),
157
            'version' => $package->getVersion(),
158
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
159
            'aliases' => $aliases,
160
        ]);
161
    }
162
163
    protected function processFiles(CompletePackageInterface $package, array $files)
164
    {
165
        foreach ($files as $name => $pathes) {
166
            foreach ((array) $pathes as $path) {
167
                if (!isset($this->files[$name])) {
168
                    $this->files[$name] = [];
169
                }
170
                array_push($this->files[$name], $this->preparePath($package, $path));
171
            }
172
        }
173
    }
174
175
    /**
176
     * Prepare aliases.
177
     * @param PackageInterface $package
178
     * @param string 'psr-0' or 'psr-4'
179
     * @return array
180
     */
181
    protected function prepareAliases(PackageInterface $package, $psr)
182
    {
183
        $autoload = $package->getAutoload();
184
        if (empty($autoload[$psr])) {
185
            return [];
186
        }
187
188
        $aliases = [];
189
        foreach ($autoload[$psr] as $name => $path) {
190
            if (is_array($path)) {
191
                // ignore psr-4 autoload specifications with multiple search paths
192
                // we can not convert them into aliases as they are ambiguous
193
                continue;
194
            }
195
            $name = str_replace('\\', '/', trim($name, '\\'));
196
            $path = $this->preparePath($package, $path);
197
            if ('psr-0' === $psr) {
198
                $path .= '/' . $name;
199
            }
200
            $aliases["@$name"] = $path;
201
        }
202
203
        return $aliases;
204
    }
205
206
    /**
207
     * Builds path inside of a package.
208
     * @param PackageInterface $package
209
     * @param mixed $path can be absolute or relative
210
     * @return string absolute pathes will stay untouched
211
     */
212
    public function preparePath(PackageInterface $package, $path)
213
    {
214
        $skippable = strncmp($path, '?', 1) === 0 ? '?' : '';
215
        if ($skippable) {
216
            $path = substr($path, 1);
217
        }
218
219
        if (!$this->getFilesystem()->isAbsolutePath($path)) {
220
            $prefix = $package instanceof RootPackageInterface
221
                ? $this->getBaseDir()
222
                : $this->getVendorDir() . '/' . $package->getPrettyName();
223
            $path = $prefix . '/' . $path;
224
        }
225
226
        return $skippable . $this->getFilesystem()->normalizePath($path);
227
    }
228
229
    /**
230
     * Sets [[packages]].
231
     * @param PackageInterface[] $packages
232
     */
233 2
    public function setPackages(array $packages)
234
    {
235 2
        $this->packages = $packages;
236 2
    }
237
238
    /**
239
     * Gets [[packages]].
240
     * @return \Composer\Package\PackageInterface[]
241
     */
242 1
    public function getPackages()
243
    {
244 1
        if ($this->packages === null) {
245
            $this->packages = $this->findPackages();
246
        }
247
248 1
        return $this->packages;
249
    }
250
251
    /**
252
     * Plain list of all project dependencies (including nested) as provided by composer.
253
     * The list is unordered (chaotic, can be different after every update).
254
     */
255
    protected $plainList = [];
256
257
    /**
258
     * Ordered list of package. Order @see findPackages.
259
     */
260
    protected $orderedList = [];
261
262
    /**
263
     * Returns ordered list of packages:
264
     * - listed earlier in the composer.json will get earlier in the list
265
     * - childs before parents.
266
     * @return \Composer\Package\PackageInterface[]
267
     */
268
    public function findPackages()
269
    {
270
        $root = $this->composer->getPackage();
271
        $this->plainList[$root->getPrettyName()] = $root;
272
        foreach ($this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages() as $package) {
273
            $this->plainList[$package->getPrettyName()] = $package;
274
        }
275
        $this->orderedList = [];
276
        $this->iteratePackage($root, true);
277
278
        if ($this->io->isVerbose()) {
279
            $indent = ' - ';
280
            $packages = $indent . implode("\n$indent", $this->orderedList);
281
            $this->io->writeError($packages);
282
        }
283
        $res = [];
284
        foreach ($this->orderedList as $name) {
285
            $res[] = $this->plainList[$name];
286
        }
287
288
        return $res;
289
    }
290
291
    /**
292
     * Iterates through package dependencies.
293
     * @param PackageInterface $package to iterate
294
     * @param bool $includingDev process development dependencies, defaults to not process
295
     */
296
    public function iteratePackage(PackageInterface $package, $includingDev = false)
297
    {
298
        $name = $package->getPrettyName();
299
300
        /// prevent infinite loop in case of circular dependencies
301
        static $processed = [];
302
        if (isset($processed[$name])) {
303
            return;
304
        } else {
305
            $processed[$name] = 1;
306
        }
307
308
        $this->iterateDependencies($package);
309
        if ($includingDev) {
310
            $this->iterateDependencies($package, true);
311
        }
312
        if (!isset($this->orderedList[$name])) {
313
            $this->orderedList[$name] = $name;
314
        }
315
    }
316
317
    /**
318
     * Iterates dependencies of the given package.
319
     * @param PackageInterface $package
320
     * @param bool $dev which dependencies to iterate: true - dev, default - general
321
     */
322
    public function iterateDependencies(PackageInterface $package, $dev = false)
323
    {
324
        $path = $this->preparePath($package, 'composer.json');
325
        if (file_exists($path)) {
326
            $conf = json_decode(file_get_contents($path), true);
327
            $what = $dev ? 'require-dev' : 'require';
328
            $deps = isset($conf[$what]) ? $conf[$what] : [];
329
        } else {
330
            $deps = $dev ? $package->getDevRequires() : $package->getRequires();
331
        }
332
        foreach (array_keys($deps) as $target) {
333
            if (isset($this->plainList[$target]) && !isset($this->orderedList[$target])) {
334
                $this->iteratePackage($this->plainList[$target]);
335
            }
336
        }
337
    }
338
339
    /**
340
     * Get absolute path to package base dir.
341
     * @return string
342
     */
343
    public function getBaseDir()
344
    {
345
        if ($this->baseDir === null) {
346
            $this->baseDir = dirname($this->getVendorDir());
347
        }
348
349
        return $this->baseDir;
350
    }
351
352
    /**
353
     * Get absolute path to composer vendor dir.
354
     * @return string
355
     */
356
    public function getVendorDir()
357
    {
358
        if ($this->vendorDir === null) {
359
            $dir = $this->composer->getConfig()->get('vendor-dir', '/');
360
            $this->vendorDir = $this->getFilesystem()->normalizePath($dir);
361
        }
362
363
        return $this->vendorDir;
364
    }
365
366
    /**
367
     * Getter for filesystem utility.
368
     * @return Filesystem
369
     */
370
    public function getFilesystem()
371
    {
372
        if ($this->filesystem === null) {
373
            $this->filesystem = new Filesystem();
374
        }
375
376
        return $this->filesystem;
377
    }
378
}
379