Completed
Push — master ( 959c97...0c8c82 )
by Andrii
11:08
created

Plugin::loadDotEnv()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 12
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
20
/**
21
 * Plugin class.
22
 *
23
 * @author Andrii Vasyliev <[email protected]>
24
 */
25
class Plugin implements PluginInterface, EventSubscriberInterface
26
{
27
    private const EXTRA_OPTION_NAME = 'config-plugin';
28
    private const EXTRA_DEV_OPTION_NAME = 'config-plugin-dev';
29
30
    /**
31
     * @var Package[] the array of active composer packages
32
     */
33
    protected $packages;
34
35
    /**
36
     * @var array config name => list of files
37
     */
38
    protected $files = [
39
        'dotenv'  => [],
40
        'aliases' => [],
41
        'defines' => [],
42
        'params'  => [],
43
    ];
44
45
    protected $colors = ['red', 'green', 'yellow', 'cyan', 'magenta', 'blue'];
46
47
    /**
48
     * @var array package name => configs as listed in `composer.json`
49
     */
50
    protected $originalFiles = [];
51
52
    /**
53
     * @var Builder
54
     */
55
    protected $builder;
56
57
    /**
58
     * @var Composer instance
59
     */
60
    protected $composer;
61
62
    /**
63
     * @var IOInterface
64
     */
65
    public $io;
66
67
    /**
68
     * Initializes the plugin object with the passed $composer and $io.
69
     * @param Composer $composer
70
     * @param IOInterface $io
71
     */
72
    public function activate(Composer $composer, IOInterface $io)
73
    {
74
        $this->composer = $composer;
75
        $this->io = $io;
76
    }
77
78
    /**
79
     * Returns list of events the plugin is subscribed to.
80
     * @return array list of events
81
     */
82
    public static function getSubscribedEvents()
83
    {
84
        return [
85
            ScriptEvents::POST_AUTOLOAD_DUMP => [
86
                ['onPostAutoloadDump', 0],
87
            ],
88 2
        ];
89
    }
90 2
91 2
    /**
92 2
     * This is the main function.
93
     * @param Event $event
94
     */
95
    public function onPostAutoloadDump(Event $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

95
    public function onPostAutoloadDump(/** @scrutinizer ignore-unused */ Event $event)

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

Loading history...
96
    {
97
        $this->io->overwriteError('<info>Assembling config files</info>');
98 1
99
        $this->builder = new Builder();
100
101 1
        $this->initAutoload();
102
        $this->scanPackages();
103
        $this->showDepsTree();
104
105
        $this->builder->buildAllConfigs($this->files);
106
    }
107
108
    protected function initAutoload()
109
    {
110
        $dir = dirname(dirname(dirname(__DIR__)));
111
        require_once "$dir/autoload.php";
112
    }
113
114
    protected function scanPackages()
115
    {
116
        foreach ($this->getPackages() as $package) {
117
            if ($package->isComplete()) {
118
                $this->processPackage($package);
119
            }
120
        }
121
    }
122
123
    /**
124
     * Scans the given package and collects packages data.
125
     * @param Package $package
126
     */
127
    protected function processPackage(Package $package)
128
    {
129
        $extra = $package->getExtra();
130
        $files = isset($extra[self::EXTRA_OPTION_NAME]) ? $extra[self::EXTRA_OPTION_NAME] : null;
131
        $this->originalFiles[$package->getPrettyName()] = $files;
132
133
        if (is_array($files)) {
134
            $this->addFiles($package, $files);
135
        }
136
        if ($package->isRoot()) {
137
            $this->loadDotEnv($package);
138
            if (!empty($extra[self::EXTRA_DEV_OPTION_NAME])) {
139
                $this->addFiles($package, $extra[self::EXTRA_DEV_OPTION_NAME]);
140
            }
141
        }
142
143
        $aliases = $package->collectAliases();
144
145
        $this->builder->mergeAliases($aliases);
146
        $this->builder->setPackage($package->getPrettyName(), array_filter([
147
            'name' => $package->getPrettyName(),
148
            'version' => $package->getVersion(),
149
            'reference' => $package->getSourceReference() ?: $package->getDistReference(),
150
            'aliases' => $aliases,
151
        ]));
152
    }
153
154
    protected function loadDotEnv(Package $package)
155
    {
156
        $path = $package->preparePath('.env');
157
        if (file_exists($path) && class_exists('Dotenv\Dotenv')) {
158
            $this->addFile($package, 'dotenv', $path);
159
        }
160
    }
161
162
    /**
163
     * Adds given files to the list of files to be processed.
164
     * Prepares `defines` in reversed order (outer package first) because
165
     * constants cannot be redefined.
166
     * @param Package $package
167
     * @param array $files
168
     */
169
    protected function addFiles(Package $package, array $files)
170
    {
171
        foreach ($files as $name => $paths) {
172
            $paths = (array) $paths;
173
            if ('defines' === $name) {
174
                $paths = array_reverse($paths);
175
            }
176
            foreach ($paths as $path) {
177
                $this->addFile($package, $name, $path);
178
            }
179
        }
180
    }
181
182
    protected function addFile(Package $package, string $name, string $path)
183
    {
184
        $path = $package->preparePath($path);
185
        if (!isset($this->files[$name])) {
186
            $this->files[$name] = [];
187
        }
188
        if (in_array($path, $this->files[$name], true)) {
189
            return;
190
        }
191
        if ('defines' === $name) {
192
            array_unshift($this->files[$name], $path);
193
        } else {
194
            array_push($this->files[$name], $path);
195
        }
196
    }
197
198
    /**
199
     * Sets [[packages]].
200
     * @param Package[] $packages
201
     */
202
    public function setPackages(array $packages)
203
    {
204
        $this->packages = $packages;
205
    }
206
207
    /**
208
     * Gets [[packages]].
209
     * @return Package[]
210
     */
211
    public function getPackages()
212
    {
213
        if (null === $this->packages) {
214
            $this->packages = $this->findPackages();
215
        }
216
217
        return $this->packages;
218
    }
219
220
    /**
221
     * Plain list of all project dependencies (including nested) as provided by composer.
222
     * The list is unordered (chaotic, can be different after every update).
223
     */
224
    protected $plainList = [];
225
226
    /**
227
     * Ordered list of package in form: package => depth
228
     * For order description @see findPackages.
229
     */
230
    protected $orderedList = [];
231
232
    /**
233
     * Returns ordered list of packages:
234
     * - listed earlier in the composer.json will get earlier in the list
235
     * - childs before parents.
236
     * @return Package[]
237
     */
238
    public function findPackages()
239
    {
240
        $root = new Package($this->composer->getPackage(), $this->composer);
241
        $this->plainList[$root->getPrettyName()] = $root;
242
        foreach ($this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages() as $package) {
243
            $this->plainList[$package->getPrettyName()] = new Package($package, $this->composer);
244
        }
245
        $this->orderedList = [];
246
        $this->iteratePackage($root, true);
247
248
        $res = [];
249
        foreach (array_keys($this->orderedList) as $name) {
250
            $res[] = $this->plainList[$name];
251
        }
252
253
        return $res;
254
    }
255
256
    /**
257
     * Iterates through package dependencies.
258
     * @param Package $package to iterate
259
     * @param bool $includingDev process development dependencies, defaults to not process
260
     */
261
    protected function iteratePackage(Package $package, $includingDev = false)
262
    {
263
        $name = $package->getPrettyName();
264
265
        /// prevent infinite loop in case of circular dependencies
266
        static $processed = [];
267
        if (isset($processed[$name])) {
268
            return;
269
        } else {
270
            $processed[$name] = 1;
271
        }
272
273
        /// package depth in dependency hierarchy
274
        static $depth = 0;
275
        ++$depth;
276
277
        $this->iterateDependencies($package);
278
        if ($includingDev) {
279
            $this->iterateDependencies($package, true);
280
        }
281
        if (!isset($this->orderedList[$name])) {
282
            $this->orderedList[$name] = $depth;
283
        }
284
285
        --$depth;
286
    }
287
288
    /**
289
     * Iterates dependencies of the given package.
290
     * @param Package $package
291
     * @param bool $dev which dependencies to iterate: true - dev, default - general
292
     */
293 2
    protected function iterateDependencies(Package $package, $dev = false)
294
    {
295 2
        $deps = $dev ? $package->getDevRequires() : $package->getRequires();
296 2
        foreach (array_keys($deps) as $target) {
297
            if (isset($this->plainList[$target]) && empty($this->orderedList[$target])) {
298
                $this->iteratePackage($this->plainList[$target]);
299
            }
300
        }
301
    }
302 1
303
    protected function showDepsTree()
304 1
    {
305
        if (!$this->io->isVerbose()) {
306
            return;
307
        }
308 1
309
        foreach (array_reverse($this->orderedList) as $name => $depth) {
310
            $deps = $this->originalFiles[$name];
311
            $color = $this->colors[$depth % count($this->colors)];
312
            $indent = str_repeat('   ', $depth - 1);
313
            $package = $this->plainList[$name];
314
            $showdeps = $deps ? '<comment>[' . implode(',', array_keys($deps)) . ']</>' : '';
315
            $this->io->write(sprintf('%s - <fg=%s;options=bold>%s</> %s %s', $indent, $color, $name, $package->getFullPrettyVersion(), $showdeps));
316
        }
317
    }
318
}
319