Completed
Push — master ( 827d60...5b84dc )
by Andrii
04:45
created

Plugin::preparePath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 9
ccs 0
cts 6
cp 0
rs 9.6666
cc 3
eloc 5
nc 3
nop 2
crap 12
1
<?php
2
3
/*
4
 * Composer plugin for config assembling
5
 *
6
 * @link      https://github.com/hiqdev/composer-config-plugin
7
 * @package   composer-config-plugin
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiqdev\ComposerConfigPlugin;
13
14
use Composer\Composer;
15
use Composer\EventDispatcher\EventSubscriberInterface;
16
use Composer\IO\IOInterface;
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 PACKAGE_TYPE          = 'yii2-extension';
32
    const EXTRA_OPTION_NAME     = 'config-plugin';
33
    const OUTPUT_PATH           = 'hiqdev/config';
34
    const BASE_DIR_SAMPLE       = '<base-dir>';
35
    const VENDOR_DIR_SAMPLE     = '<base-dir>/vendor';
36
37
    /**
38
     * @var PackageInterface[] the array of active composer packages
39
     */
40
    protected $packages;
41
42
    /**
43
     * @var string absolute path to the package base directory.
44
     */
45
    protected $baseDir;
46
47
    /**
48
     * @var string absolute path to vendor directory.
49
     */
50
    protected $vendorDir;
51
52
    /**
53
     * @var Filesystem utility
54
     */
55
    protected $filesystem;
56
57
    /**
58
     * @var array assembled config data
59
     */
60
    protected $data = [
61
        'aliases'    => [],
62
        'extensions' => [],
63
    ];
64
65
    /**
66
     * @var array raw collected data
67
     */
68
    protected $raw = [];
69
70
    /**
71
     * @var array array of not yet merged params
72
     */
73
    protected $rawParams = [];
74
75
    /**
76
     * @var Composer instance
77
     */
78
    protected $composer;
79
80
    /**
81
     * @var IOInterface
82
     */
83
    public $io;
84
85
    /**
86
     * Initializes the plugin object with the passed $composer and $io.
87
     * @param Composer $composer
88
     * @param IOInterface $io
89
     */
90 2
    public function activate(Composer $composer, IOInterface $io)
91
    {
92 2
        $this->composer = $composer;
93 2
        $this->io = $io;
94 2
    }
95
96
    /**
97
     * Returns list of events the plugin is subscribed to.
98
     * @return array list of events
99
     */
100 1
    public static function getSubscribedEvents()
101
    {
102
        return [
103 1
            ScriptEvents::POST_AUTOLOAD_DUMP => [
104 1
                ['onPostAutoloadDump', 0],
105 1
            ],
106 1
        ];
107
    }
108
109
    /**
110
     * This is the main function.
111
     * @param Event $event
112
     */
113
    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...
114
    {
115
        $this->io->writeError('<info>Assembling config files</info>');
116
117
        /// scan packages
118
        foreach ($this->getPackages() as $package) {
119
            if ($package instanceof \Composer\Package\CompletePackageInterface) {
120
                $this->processPackage($package);
121
            }
122
        }
123
        $this->processPackage($this->composer->getPackage());
124
125
        $this->assembleParams();
126
        define('COMPOSER_CONFIG_PLUGIN_DIR', $this->getOutputDir());
127
        $this->assembleConfigs();
128
    }
129
130
    /**
131
     * Scans the given package and collects extensions data.
132
     * @param PackageInterface $package
133
     */
134
    public function processPackage(PackageInterface $package)
135
    {
136
        $extra = $package->getExtra();
137
        $files = isset($extra[self::EXTRA_OPTION_NAME]) ? $extra[self::EXTRA_OPTION_NAME] : null;
138
        if ($package->getType() !== self::PACKAGE_TYPE && is_null($files)) {
139
            return;
140
        }
141
142
        $extension = [
143
            'name'    => $package->getName(),
144
            'version' => $package->getVersion(),
145
        ];
146
        if ($package->getVersion() === '9999999-dev') {
147
            $reference = $package->getSourceReference() ?: $package->getDistReference();
148
            if ($reference) {
149
                $extension['reference'] = $reference;
150
            }
151
        }
152
153
        $aliases = array_merge(
154
            $this->prepareAliases($package, 'psr-0'),
155
            $this->prepareAliases($package, 'psr-4')
156
        );
157
158
        if (isset($files['defines'])) {
159
            foreach ((array) $files['defines'] as $file) {
160
                $this->readConfigFile($package, $file);
161
            }
162
            unset($files['defines']);
163
        }
164
165
        if (isset($files['params'])) {
166
            foreach ((array) $files['params'] as $file) {
167
                $this->rawParams[] = $this->readConfigFile($package, $file);
168
            }
169
            unset($files['params']);
170
        }
171
172
        $this->raw[$package->getName()] = [
173
            'package'   => $package,
174
            'extension' => $extension,
175
            'aliases'   => $aliases,
176
            'files'     => (array) $files,
177
        ];
178
    }
179
180
    public function assembleParams()
181
    {
182
        $this->assembleFile('params', $this->rawParams);
183
    }
184
185
    public function assembleConfigs()
186
    {
187
        $allAliases = [];
0 ignored issues
show
Unused Code introduced by
$allAliases is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
188
        $extensions = [];
0 ignored issues
show
Unused Code introduced by
$extensions is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
189
        $rawConfigs = [
190
            'aliases'    => [],
191
            'extensions' => [],
192
        ];
193
194
        foreach ($this->raw as $name => $info) {
195
            $rawConfigs['extensions'][] = [
196
                $name => $info['extension'],
197
            ];
198
199
            $aliases = $info['aliases'];
200
            $rawConfigs['aliases'][] = $aliases;
201
202
            foreach ($info['files'] as $name => $pathes) {
203
                foreach ((array) $pathes as $path) {
204
                    $rawConfigs[$name][] = $this->readConfigFile($info['package'], $path);
205
                }
206
            }
207
        }
208
209
        foreach ($rawConfigs as $name => $configs) {
210
            if (!in_array($name, ['params', 'aliases', 'extensions'], true)) {
211
                $configs[] = [
212
                    'params'  => $this->data['params'],
213
                    'aliases' => $this->data['aliases'],
214
                ];
215
            }
216
            $this->assembleFile($name, $configs);
217
        }
218
    }
219
220
    protected function assembleFile($name, array $configs)
221
    {
222
        $this->data[$name] = call_user_func_array([Helper::class, 'mergeConfig'], $configs);
223
        $this->writeFile($name, (array) $this->data[$name]);
224
    }
225
226
    /**
227
     * Read extra config.
228
     * @param string $file
229
     * @return array
230
     */
231
    protected function readConfigFile(PackageInterface $package, $file)
232
    {
233
        $skippable = false;
234
        if (strncmp($file, '?', 1) === 0) {
235
            $skippable = true;
236
            $file = substr($file, 1);
237
        }
238
        $__path = $this->preparePath($package, $file);
239
        if (!file_exists($__path)) {
240
            if ($skippable) {
241
                return [];
242
            } else {
243
                $this->io->writeError('<error>Non existent extension config file</error> ' . $file . ' in ' . $package->getName());
244
                exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method readConfigFile() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
245
            }
246
        }
247
        extract($this->data);
248
        return (array) require $__path;
249
    }
250
251
    /**
252
     * Prepare aliases.
253
     *
254
     * @param PackageInterface $package
255
     * @param string 'psr-0' or 'psr-4'
256
     * @return array
257
     */
258
    protected function prepareAliases(PackageInterface $package, $psr)
259
    {
260
        $autoload = $package->getAutoload();
261
        if (empty($autoload[$psr])) {
262
            return [];
263
        }
264
265
        $aliases = [];
266
        foreach ($autoload[$psr] as $name => $path) {
267
            if (is_array($path)) {
268
                // ignore psr-4 autoload specifications with multiple search paths
269
                // we can not convert them into aliases as they are ambiguous
270
                continue;
271
            }
272
            $name = str_replace('\\', '/', trim($name, '\\'));
273
            $path = $this->preparePath($package, $path);
274
            $path = $this->substitutePath($path, $this->getBaseDir(), self::BASE_DIR_SAMPLE);
275
            if ('psr-0' === $psr) {
276
                $path .= '/' . $name;
277
            }
278
            $aliases["@$name"] = $path;
279
        }
280
281
        return $aliases;
282
    }
283
284
    /**
285
     * Substitute path with alias if applicable.
286
     * @param string $path
287
     * @param string $dir
288
     * @param string $alias
289
     * @return string
290
     */
291
    public function substitutePath($path, $dir, $alias)
292
    {
293
        return (substr($path, 0, strlen($dir) + 1) === $dir . '/') ? $alias . substr($path, strlen($dir)) : $path;
294
    }
295
296
    public function preparePath(PackageInterface $package, $path)
297
    {
298
        if (!$this->getFilesystem()->isAbsolutePath($path)) {
299
            $prefix = $package instanceof RootPackageInterface ? $this->getBaseDir() : $this->getVendorDir() . '/' . $package->getPrettyName();
300
            $path = $prefix . '/' . $path;
301
        }
302
303
        return $this->getFilesystem()->normalizePath($path);
304
    }
305
306
    /**
307
     * Get output dir.
308
     * @return string
309
     */
310
    public function getOutputDir()
311
    {
312
        return $this->getVendorDir() . DIRECTORY_SEPARATOR . static::OUTPUT_PATH;
313
    }
314
315
    /**
316
     * Build full path to write file for a given filename.
317
     * @param string $filename
318
     * @return string
319
     */
320
    public function buildOutputPath($filename)
321
    {
322
        return $this->getOutputDir() . DIRECTORY_SEPARATOR . $filename . '.php';
323
    }
324
325
    /**
326
     * Writes file.
327
     * @param string $filename
328
     * @param array $data
329
     */
330
    protected function writeFile($filename, array $data)
331
    {
332
        $path = $this->buildOutputPath($filename);
333
        if (!file_exists(dirname($path))) {
334
            mkdir(dirname($path), 0777, true);
335
        }
336
        $array = str_replace("'" . self::BASE_DIR_SAMPLE, '$baseDir . \'', Helper::exportVar($data));
337
        file_put_contents($path, "<?php\n\n\$baseDir = dirname(dirname(dirname(__DIR__)));\n\nreturn $array;\n");
338
    }
339
340
    /**
341
     * Sets [[packages]].
342
     * @param PackageInterface[] $packages
343
     */
344 2
    public function setPackages(array $packages)
345
    {
346 2
        $this->packages = $packages;
347 2
    }
348
349
    /**
350
     * Gets [[packages]].
351
     * @return \Composer\Package\PackageInterface[]
352
     */
353 1
    public function getPackages()
354
    {
355 1
        if ($this->packages === null) {
356
            $this->packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
357
        }
358
359 1
        return $this->packages;
360
    }
361
362
    /**
363
     * Get absolute path to package base dir.
364
     * @return string
365
     */
366
    public function getBaseDir()
367
    {
368
        if ($this->baseDir === null) {
369
            $this->baseDir = dirname($this->getVendorDir());
370
        }
371
372
        return $this->baseDir;
373
    }
374
375
    /**
376
     * Get absolute path to composer vendor dir.
377
     * @return string
378
     */
379
    public function getVendorDir()
380
    {
381
        if ($this->vendorDir === null) {
382
            $dir = $this->composer->getConfig()->get('vendor-dir', '/');
383
            $this->vendorDir = $this->getFilesystem()->normalizePath($dir);
384
        }
385
386
        return $this->vendorDir;
387
    }
388
389
    /**
390
     * Getter for filesystem utility.
391
     * @return Filesystem
392
     */
393
    public function getFilesystem()
394
    {
395
        if ($this->filesystem === null) {
396
            $this->filesystem = new Filesystem();
397
        }
398
399
        return $this->filesystem;
400
    }
401
}
402