Completed
Push — master ( a935f2...c47dc8 )
by Andrii
05:47
created

Plugin   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 318
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 11.9%

Importance

Changes 14
Bugs 3 Features 0
Metric Value
wmc 46
c 14
b 3
f 0
lcom 1
cbo 7
dl 0
loc 318
ccs 15
cts 126
cp 0.119
rs 8.3999

16 Methods

Rating   Name   Duplication   Size   Complexity  
A activate() 0 5 1
A getSubscribedEvents() 0 8 1
A saveFile() 0 9 2
B processPackage() 0 25 5
B onPostAutoloadDump() 0 15 5
D mergeConfig() 0 25 9
A extractConfigPath() 0 5 2
A readExtraConfig() 0 9 2
B prepareAliases() 0 25 5
A substitutePath() 0 4 2
A preparePath() 0 9 3
A setPackages() 0 4 1
A getPackages() 0 8 2
A getBaseDir() 0 8 2
A getVendorDir() 0 9 2
A getFilesystem() 0 8 2

How to fix   Complexity   

Complex Class

Complex classes like Plugin often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Plugin, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * Composer plugin for Yii extensions
5
 *
6
 * @link      https://github.com/hiqdev/composer-extension-plugin
7
 * @package   composer-extension-plugin
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiqdev\composerextensionplugin;
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 CONFIG_PATH_OPTION    = 'extension-config';
33
    const YII2_EXTENSIONS_FILE  = 'yiisoft/extensions.php';
34
    const MERGED_CONFIG_FILE    = 'hiqdev/extensions-config.php';
35
    const BASE_DIR_ALIAS        = '<base-dir>';
36
    const VENDOR_DIR_ALIAS      = '<base-dir>/vendor';
37
38
    /**
39
     * @var PackageInterface[] the array of active composer packages
40
     */
41
    protected $packages;
42
43
    /**
44
     * @var string absolute path to the package base directory.
45
     */
46
    protected $baseDir;
47
48
    /**
49
     * @var string absolute path to vendor directory.
50
     */
51
    protected $vendorDir;
52
53
    /**
54
     * @var Filesystem utility
55
     */
56
    protected $filesystem;
57
58
    /**
59
     * @var array extra configuration
60
     */
61
    protected $extraconfig = [
62
        'aliases' => [
63
            '@vendor' => self::VENDOR_DIR_ALIAS,
64
        ],
65
    ];
66
67
    /**
68
     * @var array extensions
69
     */
70
    protected $extensions = [];
71
72
    /**
73
     * @var Composer instance
74
     */
75
    protected $composer;
76
77
    /**
78
     * @var IOInterface
79
     */
80
    public $io;
81
82
    /**
83
     * Initializes the plugin object with the passed $composer and $io.
84
     * @param Composer $composer
85
     * @param IOInterface $io
86
     * @void
87
     */
88 2
    public function activate(Composer $composer, IOInterface $io)
89
    {
90 2
        $this->composer = $composer;
91 2
        $this->io = $io;
92 2
    }
93
94
    /**
95
     * Returns list of events the plugin is subscribed to.
96
     * @return array list of events
97
     */
98 1
    public static function getSubscribedEvents()
99
    {
100
        return [
101 1
            ScriptEvents::POST_AUTOLOAD_DUMP => [
102 1
                ['onPostAutoloadDump', 0],
103 1
            ],
104 1
        ];
105
    }
106
107
    /**
108
     * Simply rewrites extensions file from scratch.
109
     * @param Event $event
110
     * @void
111
     */
112
    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...
113
    {
114
        $this->io->writeError('<info>Generating yii2 config files</info>');
115
        $this->processPackage($this->composer->getPackage());
116
        foreach ($this->getPackages() as $package) {
117
            if ($package instanceof \Composer\Package\CompletePackageInterface
118
            && ($package->getType() === self::PACKAGE_TYPE || $this->extractConfigPath($package))) {
119
                $this->processPackage($package);
120
            }
121
        }
122
123
    //  $this->saveFile(static::YII2_EXTENSIONS_FILE, $this->extensions);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
124
        $this->saveFile(static::YII2_EXTENSIONS_FILE, []);
125
        $this->saveFile(static::MERGED_CONFIG_FILE, $this->extraconfig);
126
    }
127
128
    /**
129
     * Writes file.
130
     * @param string $file
131
     * @param array $data
132
     * @void
133
     */
134
    protected function saveFile($file, array $data)
135
    {
136
        $path = $this->getVendorDir() . '/' . $file;
137
        if (!file_exists(dirname($path))) {
138
            mkdir(dirname($path), 0777, true);
139
        }
140
        $array = str_replace("'" . self::BASE_DIR_ALIAS, '$baseDir . \'', var_export($data, true));
141
        file_put_contents($path, "<?php\n\n\$baseDir = dirname(dirname(__DIR__));\n\nreturn $array;\n");
142
    }
143
144
    /**
145
     * Scans the given package and collects extensions data.
146
     * @param PackageInterface $package
147
     * @void
148
     */
149
    public function processPackage(PackageInterface $package)
150
    {
151
        $extension = [
152
            'name'    => $package->getName(),
153
            'version' => $package->getVersion(),
154
        ];
155
        if ($package->getVersion() === '9999999-dev') {
156
            $reference = $package->getSourceReference() ?: $package->getDistReference();
157
            if ($reference) {
158
                $extension['reference'] = $reference;
159
            }
160
        }
161
        $this->extensions[$package->getName()] = $extension;
162
163
        $this->extraconfig['aliases'] = array_merge(
164
            $this->extraconfig['aliases'],
165
            $this->prepareAliases($package, 'psr-0'),
166
            $this->prepareAliases($package, 'psr-4')
167
        );
168
169
        $path = $this->extractConfigPath($package);
170
        if ($path) {
171
            $this->extraconfig = static::mergeConfig($this->extraconfig, $this->readExtraConfig($package, $path));
172
        }
173
    }
174
175
    /**
176
     * Merges two or more arrays into one recursively.
177
     * Based on Yii2 yii\helpers\BaseArrayHelper::merge.
178
     * @param array $a array to be merged to
179
     * @param array $b array to be merged from
180
     * @return array the merged array
181
     */
182
    public static function mergeConfig($a, $b)
0 ignored issues
show
Unused Code introduced by
The parameter $a 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...
Unused Code introduced by
The parameter $b 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...
183
    {
184
        $args = func_get_args();
185
        $res = array_shift($args);
186
        foreach ($args as $items) {
187
            if (!is_array($items)) {
188
                continue;
189
            }
190
            foreach ($items as $k => $v) {
191
                if (is_int($k)) {
192
                    if (isset($res[$k])) {
193
                        $res[] = $v;
194
                    } else {
195
                        $res[$k] = $v;
196
                    }
197
                } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
198
                    $res[$k] = self::mergeConfig($res[$k], $v);
199
                } else {
200
                    $res[$k] = $v;
201
                }
202
            }
203
        }
204
205
        return $res;
206
    }
207
208
    public function extractConfigPath(PackageInterface $package)
209
    {
210
        $extra = $package->getExtra();
211
        return isset($extra[static::CONFIG_PATH_OPTION]) ? $extra[static::CONFIG_PATH_OPTION] : null;
212
    }
213
214
    /**
215
     * Read extra config.
216
     * @param string $file
217
     * @return array
218
     */
219
    protected function readExtraConfig(PackageInterface $package, $file)
220
    {
221
        $path = $this->preparePath($package, $file);
222
        if (!file_exists($path)) {
223
            $this->io->writeError('<error>Non existent extraconfig file</error> ' . $file . ' in ' . $package->getName());
224
            exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method readExtraConfig() 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...
225
        }
226
        return require $path;
227
    }
228
229
    /**
230
     * Prepare aliases.
231
     *
232
     * @param PackageInterface $package
233
     * @param string 'psr-0' or 'psr-4'
234
     * @return array
235
     */
236
    protected function prepareAliases(PackageInterface $package, $psr)
237
    {
238
        $autoload = $package->getAutoload();
239
        if (empty($autoload[$psr])) {
240
            return [];
241
        }
242
243
        $aliases = [];
244
        foreach ($autoload[$psr] as $name => $path) {
245
            if (is_array($path)) {
246
                // ignore psr-4 autoload specifications with multiple search paths
247
                // we can not convert them into aliases as they are ambiguous
248
                continue;
249
            }
250
            $name = str_replace('\\', '/', trim($name, '\\'));
251
            $path = $this->preparePath($package, $path);
252
            $path = $this->substitutePath($path, $this->getBaseDir(), self::BASE_DIR_ALIAS);
253
            if ('psr-0' === $psr) {
254
                $path .= '/' . $name;
255
            }
256
            $aliases["@$name"] = $path;
257
        }
258
259
        return $aliases;
260
    }
261
262
    /**
263
     * Substitute path with alias if applicable.
264
     * @param string $path
265
     * @param string $dir
266
     * @param string $alias
267
     * @return string
268
     */
269
    public function substitutePath($path, $dir, $alias)
270
    {
271
        return (substr($path, 0, strlen($dir) + 1) === $dir . '/') ? $alias . substr($path, strlen($dir)) : $path;
272
    }
273
274
    public function preparePath(PackageInterface $package, $path)
275
    {
276
        if (!$this->getFilesystem()->isAbsolutePath($path)) {
277
            $prefix = $package instanceof RootPackageInterface ? $this->getBaseDir() : $this->getVendorDir() . '/' . $package->getPrettyName();
278
            $path = $prefix . '/' . $path;
279
        }
280
281
        return $this->getFilesystem()->normalizePath($path);
282
    }
283
284
    /**
285
     * Sets [[packages]].
286
     * @param PackageInterface[] $packages
287
     * @void
288
     */
289 2
    public function setPackages(array $packages)
290
    {
291 2
        $this->packages = $packages;
292 2
    }
293
294
    /**
295
     * Gets [[packages]].
296
     * @return \Composer\Package\PackageInterface[]
297
     */
298 1
    public function getPackages()
299
    {
300 1
        if ($this->packages === null) {
301
            $this->packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
302
        }
303
304 1
        return $this->packages;
305
    }
306
307
    /**
308
     * Get absolute path to package base dir.
309
     * @return string
310
     */
311
    public function getBaseDir()
312
    {
313
        if ($this->baseDir === null) {
314
            $this->baseDir = dirname($this->getVendorDir());
315
        }
316
317
        return $this->baseDir;
318
    }
319
320
    /**
321
     * Get absolute path to composer vendor dir.
322
     * @return string
323
     */
324
    public function getVendorDir()
325
    {
326
        if ($this->vendorDir === null) {
327
            $dir = $this->composer->getConfig()->get('vendor-dir', '/');
328
            $this->vendorDir = $this->getFilesystem()->normalizePath($dir);
329
        }
330
331
        return $this->vendorDir;
332
    }
333
334
    /**
335
     * Getter for filesystem utility.
336
     * @return Filesystem
337
     */
338
    public function getFilesystem()
339
    {
340
        if ($this->filesystem === null) {
341
            $this->filesystem = new Filesystem();
342
        }
343
344
        return $this->filesystem;
345
    }
346
}
347