Passed
Push — master ( 8a6a58...6a4eb4 )
by Andrii
13:36
created

src/Plugin.php (1 issue)

Severity
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
use hiqdev\composer\config\exceptions\FailedReadException;
20
use hiqdev\composer\config\readers\ReaderFactory;
21
22
/**
23
 * Plugin class.
24
 *
25
 * @author Andrii Vasyliev <[email protected]>
26
 */
27
class Plugin implements PluginInterface, EventSubscriberInterface
28
{
29
    /**
30
     * @var Package[] the array of active composer packages
31
     */
32
    protected $packages;
33
34
    private $alternatives = [];
35
36
    private $outputDir;
37
38
    private $rootPackage;
39
40
    /**
41
     * @var array config name => list of files
42
     */
43
    protected $files = [
44
        'dotenv'  => [],
45
        'defines' => [],
46
        'params'  => [],
47
    ];
48
49
    protected $colors = ['red', 'green', 'yellow', 'cyan', 'magenta', 'blue'];
50
51
    /**
52
     * @var array package name => configs as listed in `composer.json`
53
     */
54
    protected $originalFiles = [];
55
56
    /**
57
     * @var Builder
58
     */
59
    protected $builder;
60
61
    /**
62
     * @var Composer instance
63
     */
64
    protected $composer;
65
66
    /**
67
     * @var IOInterface
68
     */
69
    public $io;
70
71
    /**
72
     * Initializes the plugin object with the passed $composer and $io.
73
     * @param Composer $composer
74
     * @param IOInterface $io
75
     */
76
    public function activate(Composer $composer, IOInterface $io)
77
    {
78
        $this->composer = $composer;
79
        $this->io = $io;
80
    }
81
82
    /**
83
     * Returns list of events the plugin is subscribed to.
84
     * @return array list of events
85
     */
86
    public static function getSubscribedEvents()
87
    {
88 2
        return [
89
            ScriptEvents::POST_AUTOLOAD_DUMP => [
90 2
                ['onPostAutoloadDump', 0],
91 2
            ],
92 2
        ];
93
    }
94
95
    /**
96
     * This is the main function.
97
     * @param Event $event
98 1
     */
99
    public function onPostAutoloadDump(Event $event)
100
    {
101 1
        $this->io->overwriteError('<info>Assembling config files</info>');
102
103
        $this->builder = new Builder();
104
105
        $this->initAutoload();
106
        $this->scanPackages();
107
        $this->reorderFiles();
108
        $this->showDepsTree();
109
110
        $this->builder->setOutputDir($this->outputDir);
111
        $this->builder->buildAllConfigs($this->files);
112
113
        $save = $this->files;
114
        foreach ($this->alternatives as $name => $files) {
115
            $this->files = $save;
116
            $builder = $this->builder->createAlternative($name);
117
            $this->addFiles($this->rootPackage, $files);
118
            $builder->buildAllConfigs($this->files);
119
        }
120
    }
121
122
    protected function initAutoload()
123
    {
124
        $dir = dirname(dirname(dirname(__DIR__)));
125
        require_once "$dir/autoload.php";
126
    }
127
128
    protected function scanPackages()
129
    {
130
        foreach ($this->getPackages() as $package) {
131
            if ($package->isComplete()) {
132
                $this->processPackage($package);
133
            }
134
        }
135
    }
136
137
    protected function reorderFiles(): void
138
    {
139
        foreach (array_keys($this->files) as $name) {
140
            $this->files[$name] = $this->getAllFiles($name);
141
        }
142
        foreach ($this->files as $name => $files) {
143
            $this->files[$name] = $this->orderFiles($files);
144
        }
145
    }
146
147
    protected function getAllFiles(string $name): array
148
    {
149
        if (empty($this->files[$name])) {
150
            return[];
151
        }
152
        $res = [];
153
        foreach ($this->files[$name] as $file) {
154
            if (strncmp($file, '$', 1) === 0) {
155
                $res = array_merge($res, $this->getAllFiles(substr($file, 1)));
156
            } else {
157
                $res[] = $file;
158
            }
159
        }
160
161
        return $res;
162
    }
163
164
    protected function orderFiles(array $files): array
165
    {
166
        if (empty($files)) {
167
            return [];
168
        }
169
        $keys = array_combine($files, $files);
170
        $res = [];
171
        foreach ($this->orderedFiles as $file) {
172
            if (isset($keys[$file])) {
173
                $res[] = $file;
174
            }
175
        }
176
177
        return $res;
178
    }
179
180
    /**
181
     * Scans the given package and collects packages data.
182
     * @param Package $package
183
     */
184
    protected function processPackage(Package $package)
185
    {
186
        $files = $package->getFiles();
187
        $this->originalFiles[$package->getPrettyName()] = $files;
188
189
        if (!empty($files)) {
190
            $this->addFiles($package, $files);
191
        }
192
        if ($package->isRoot()) {
193
            $this->rootPackage = $package;
194
            $this->loadDotEnv($package);
195
            $devFiles = $package->getDevFiles();
196
            if (!empty($devFiles)) {
197
                $this->addFiles($package, $devFiles);
198
            }
199
            $this->outputDir = $package->getOutputDir();
200
            $alternatives = $package->getAlternatives();
201
            if (is_string($alternatives)) {
0 ignored issues
show
The condition is_string($alternatives) is always false.
Loading history...
202
                $this->alternatives = $this->readConfig($package, $alternatives);
203
            } else {
204
                $this->alternatives = $alternatives;
205
            }
206
        }
207
208
        $aliases = $package->collectAliases();
209
210
        $this->builder->mergeAliases($aliases);
211
        $this->builder->setPackage($package->getPrettyName(), array_filter([
212
            'name' => $package->getPrettyName(),
213
            'version' => $package->getVersion(),
214
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
215
            'aliases' => $aliases,
216
        ]));
217
    }
218
219
    private function readConfig($package, $file): array
220
    {
221
        $path = $package->preparePath($file);
222
        if (!file_exists($path)) {
223
            throw new FailedReadException("failed read file: $file");
224
        }
225
        $reader = ReaderFactory::get($this->builder, $path);
226
227
        return $reader->read($path);
228
229
    }
230
231
    protected function loadDotEnv(Package $package)
232
    {
233
        $path = $package->preparePath('.env');
234
        if (file_exists($path) && class_exists('Dotenv\Dotenv')) {
235
            $this->addFile($package, 'dotenv', $path);
236
        }
237
    }
238
239
    /**
240
     * Adds given files to the list of files to be processed.
241
     * Prepares `defines` in reversed order (outer package first) because
242
     * constants cannot be redefined.
243
     * @param Package $package
244
     * @param array $files
245
     */
246
    protected function addFiles(Package $package, array $files)
247
    {
248
        foreach ($files as $name => $paths) {
249
            $paths = (array) $paths;
250
            if ('defines' === $name) {
251
                $paths = array_reverse($paths);
252
            }
253
            foreach ($paths as $path) {
254
                $this->addFile($package, $name, $path);
255
            }
256
        }
257
    }
258
259
    protected $orderedFiles = [];
260
261
    protected function addFile(Package $package, string $name, string $path)
262
    {
263
        $path = $package->preparePath($path);
264
        if (!isset($this->files[$name])) {
265
            $this->files[$name] = [];
266
        }
267
        if (in_array($path, $this->files[$name], true)) {
268
            return;
269
        }
270
        if ('defines' === $name) {
271
            array_unshift($this->orderedFiles, $path);
272
            array_unshift($this->files[$name], $path);
273
        } else {
274
            array_push($this->orderedFiles, $path);
275
            array_push($this->files[$name], $path);
276
        }
277
    }
278
279
    /**
280
     * Sets [[packages]].
281
     * @param Package[] $packages
282
     */
283
    public function setPackages(array $packages)
284
    {
285
        $this->packages = $packages;
286
    }
287
288
    /**
289
     * Gets [[packages]].
290
     * @return Package[]
291
     */
292
    public function getPackages()
293 2
    {
294
        if (null === $this->packages) {
295 2
            $this->packages = $this->findPackages();
296 2
        }
297
298
        return $this->packages;
299
    }
300
301
    /**
302 1
     * Plain list of all project dependencies (including nested) as provided by composer.
303
     * The list is unordered (chaotic, can be different after every update).
304 1
     */
305
    protected $plainList = [];
306
307
    /**
308 1
     * Ordered list of package in form: package => depth
309
     * For order description @see findPackages.
310
     */
311
    protected $orderedList = [];
312
313
    /**
314
     * Returns ordered list of packages:
315
     * - listed earlier in the composer.json will get earlier in the list
316
     * - childs before parents.
317
     * @return Package[]
318
     */
319
    public function findPackages()
320
    {
321
        $root = new Package($this->composer->getPackage(), $this->composer);
322
        $this->plainList[$root->getPrettyName()] = $root;
323
        foreach ($this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages() as $package) {
324
            $this->plainList[$package->getPrettyName()] = new Package($package, $this->composer);
325
        }
326
        $this->orderedList = [];
327
        $this->iteratePackage($root, true);
328
329
        $res = [];
330
        foreach (array_keys($this->orderedList) as $name) {
331
            $res[] = $this->plainList[$name];
332
        }
333
334
        return $res;
335
    }
336
337
    /**
338
     * Iterates through package dependencies.
339
     * @param Package $package to iterate
340
     * @param bool $includingDev process development dependencies, defaults to not process
341
     */
342
    protected function iteratePackage(Package $package, $includingDev = false)
343
    {
344
        $name = $package->getPrettyName();
345
346
        /// prevent infinite loop in case of circular dependencies
347
        static $processed = [];
348
        if (isset($processed[$name])) {
349
            return;
350
        } else {
351
            $processed[$name] = 1;
352
        }
353
354
        /// package depth in dependency hierarchy
355
        static $depth = 0;
356
        ++$depth;
357
358
        $this->iterateDependencies($package);
359
        if ($includingDev) {
360
            $this->iterateDependencies($package, true);
361
        }
362
        if (!isset($this->orderedList[$name])) {
363
            $this->orderedList[$name] = $depth;
364
        }
365
366
        --$depth;
367
    }
368
369
    /**
370
     * Iterates dependencies of the given package.
371
     * @param Package $package
372
     * @param bool $dev which dependencies to iterate: true - dev, default - general
373
     */
374
    protected function iterateDependencies(Package $package, $dev = false)
375
    {
376
        $deps = $dev ? $package->getDevRequires() : $package->getRequires();
377
        foreach (array_keys($deps) as $target) {
378
            if (isset($this->plainList[$target]) && empty($this->orderedList[$target])) {
379
                $this->iteratePackage($this->plainList[$target]);
380
            }
381
        }
382
    }
383
384
    protected function showDepsTree()
385
    {
386
        if (!$this->io->isVerbose()) {
387
            return;
388
        }
389
390
        foreach (array_reverse($this->orderedList) as $name => $depth) {
391
            $deps = $this->originalFiles[$name];
392
            $color = $this->colors[$depth % count($this->colors)];
393
            $indent = str_repeat('   ', $depth - 1);
394
            $package = $this->plainList[$name];
395
            $showdeps = $deps ? '<comment>[' . implode(',', array_keys($deps)) . ']</>' : '';
396
            $this->io->write(sprintf('%s - <fg=%s;options=bold>%s</> %s %s', $indent, $color, $name, $package->getFullPrettyVersion(), $showdeps));
397
        }
398
    }
399
}
400