Completed
Pull Request — master (#98)
by
unknown
05:02
created

MergePlugin   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 252
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 98.96%

Importance

Changes 32
Bugs 2 Features 10
Metric Value
wmc 25
c 32
b 2
f 10
lcom 1
cbo 14
dl 0
loc 252
ccs 95
cts 96
cp 0.9896
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A activate() 0 7 1
A getSubscribedEvents() 0 12 1
A onInstallUpdateOrDump() 0 15 3
A mergeFiles() 0 21 4
A validatePath() 0 12 3
A mergeFile() 0 18 3
A onDependencySolve() 0 18 4
A onPostPackageInstall() 0 14 3
B onPostInstallOrUpdate() 0 42 3
1
<?php
2
/**
3
 * This file is part of the Composer Merge plugin.
4
 *
5
 * Copyright (C) 2015 Bryan Davis, Wikimedia Foundation, and contributors
6
 *
7
 * This software may be modified and distributed under the terms of the MIT
8
 * license. See the LICENSE file for details.
9
 */
10
11
namespace Wikimedia\Composer;
12
13
use Wikimedia\Composer\Merge\ExtraPackage;
14
use Wikimedia\Composer\Merge\MissingFileException;
15
use Wikimedia\Composer\Merge\PluginState;
16
17
use Composer\Composer;
18
use Composer\DependencyResolver\Operation\InstallOperation;
19
use Composer\EventDispatcher\EventSubscriberInterface;
20
use Composer\Factory;
21
use Composer\Installer;
22
use Composer\Installer\InstallerEvent;
23
use Composer\Installer\InstallerEvents;
24
use Composer\Installer\PackageEvent;
25
use Composer\Installer\PackageEvents;
26
use Composer\IO\IOInterface;
27
use Composer\Package\RootPackageInterface;
28
use Composer\Plugin\PluginInterface;
29
use Composer\Script\Event;
30
use Composer\Script\ScriptEvents;
31
32
/**
33
 * Composer plugin that allows merging multiple composer.json files.
34
 *
35
 * When installed, this plugin will look for a "merge-plugin" key in the
36
 * composer configuration's "extra" section. The value for this key is
37
 * a set of options configuring the plugin.
38
 *
39
 * An "include" setting is required. The value of this setting can be either
40
 * a single value or an array of values. Each value is treated as a glob()
41
 * pattern identifying additional composer.json style configuration files to
42
 * merge into the configuration for the current compser execution.
43
 *
44
 * The "autoload", "autoload-dev", "conflict", "provide", "replace",
45
 * "repositories", "require", "require-dev", and "suggest" sections of the
46
 * found configuration files will be merged into the root package
47
 * configuration as though they were directly included in the top-level
48
 * composer.json file.
49
 *
50
 * If included files specify conflicting package versions for "require" or
51
 * "require-dev", the normal Composer dependency solver process will be used
52
 * to attempt to resolve the conflict. Specifying the 'replace' key as true will
53
 * change this default behaviour so that the last-defined version of a package
54
 * will win, allowing for force-overrides of package defines.
55
 *
56
 * By default the "extra" section is not merged. This can be enabled by
57
 * setitng the 'merge-extra' key to true. In normal mode, when the same key is
58
 * found in both the original and the imported extra section, the version in
59
 * the original config is used and the imported version is skipped. If
60
 * 'replace' mode is active, this behaviour changes so the imported version of
61
 * the key is used, replacing the version in the original config.
62
 *
63
 *
64
 * @code
65
 * {
66
 *     "require": {
67
 *         "wikimedia/composer-merge-plugin": "dev-master"
68
 *     },
69
 *     "extra": {
70
 *         "merge-plugin": {
71
 *             "include": [
72
 *                 "composer.local.json"
73
 *             ]
74
 *         }
75
 *     }
76
 * }
77
 * @endcode
78
 *
79
 * @author Bryan Davis <[email protected]>
80
 */
81
class MergePlugin implements PluginInterface, EventSubscriberInterface
82
{
83
84
    /**
85
     * Offical package name
86
     */
87
    const PACKAGE_NAME = 'wikimedia/composer-merge-plugin';
88
89
    /**
90
     * @var Composer $composer
91
     */
92
    protected $composer;
93
94
    /**
95
     * @var PluginState $state
96
     */
97
    protected $state;
98
99
    /**
100
     * @var Logger $logger
101
     */
102
    protected $logger;
103
104
    /**
105
     * @var IOInterface $io
106
     */
107
    protected $io;
108
109
    /**
110
     * Files that have already been processed
111
     *
112
     * @var string[] $loadedFiles
113
     */
114
    protected $loadedFiles = array();
115
116
    /**
117
     * {@inheritdoc}
118
     */
119 109
    public function activate(Composer $composer, IOInterface $io)
120
    {
121 109
        $this->composer = $composer;
122 109
        $this->state = new PluginState($this->composer);
123 109
        $this->io = $io;
124 109
        $this->logger = new Logger('merge-plugin', $io);
125 109
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130 5
    public static function getSubscribedEvents()
131
    {
132
        return array(
133 5
            InstallerEvents::PRE_DEPENDENCIES_SOLVING => 'onDependencySolve',
134 5
            PackageEvents::POST_PACKAGE_INSTALL => 'onPostPackageInstall',
135 5
            ScriptEvents::POST_INSTALL_CMD => 'onPostInstallOrUpdate',
136 5
            ScriptEvents::POST_UPDATE_CMD => 'onPostInstallOrUpdate',
137 5
            ScriptEvents::PRE_AUTOLOAD_DUMP => 'onInstallUpdateOrDump',
138 5
            ScriptEvents::PRE_INSTALL_CMD => 'onInstallUpdateOrDump',
139 5
            ScriptEvents::PRE_UPDATE_CMD => 'onInstallUpdateOrDump',
140 5
        );
141
    }
142
143
    /**
144
     * Handle an event callback for an install, update or dump command by
145
     * checking for "merge-plugin" in the "extra" data and merging package
146
     * contents if found.
147
     *
148
     * @param Event $event
149
     */
150 89
    public function onInstallUpdateOrDump(Event $event)
151
    {
152 89
        $this->state->loadSettings();
153 89
        $this->state->setDevMode($event->isDevMode());
154 89
        $this->mergeFiles($this->state->getIncludes(), false);
155 89
        $this->mergeFiles($this->state->getRequires(), true);
156
157 84
        if ($event->getName() === ScriptEvents::PRE_AUTOLOAD_DUMP) {
158 84
            $this->state->setDumpAutoloader(true);
159 84
            $flags = $event->getFlags();
160 84
            if (isset($flags['optimize'])) {
161 84
                $this->state->setOptimizeAutoloader($flags['optimize']);
162 84
            }
163 84
        }
164 84
    }
165
166
    /**
167
     * Find configuration files matching the configured glob patterns and
168
     * merge their contents with the master package.
169
     *
170
     * @param array $patterns List of files/glob patterns
171
     * @param bool $required Are the patterns required to match files?
172
     * @throws MissingFileException when required and a pattern returns no
173
     *      results
174
     */
175 89
    protected function mergeFiles(array $patterns, $required = false)
176
    {
177 89
        $root = $this->composer->getPackage();
178
179 89
        $files = array_map(
180 89
            function ($files, $pattern) use ($required) {
181 89
                if ($required && !$files) {
182 5
                    throw new MissingFileException(
183 5
                        "merge-plugin: No files matched required '{$pattern}'"
184 5
                    );
185
                }
186 84
                return $files;
187 89
            },
188 89
            array_map(array($this, 'validatePath'), $patterns),
189
            $patterns
190 89
        );
191
192 89
        foreach (array_reduce($files, 'array_merge', array()) as $path) {
193 84
            $this->mergeFile($root, $path);
194 89
        }
195 89
    }
196
197 89
    protected function validatePath($path){
198 89
        if(substr($path, 0, 4) === 'http'){
199 4
            $headers = get_headers ( $path );
200 4
            if ( strpos($headers[0], '404') == 0){
201 4
                return array($path);    
202
            }else{
203
                return array();
204
            }
205
        }else{
206 85
            return glob($path);
207
        }
208
    }
209
210
    /**
211
     * Read a JSON file and merge its contents
212
     *
213
     * @param RootPackageInterface $root
214
     * @param string $path
215
     */
216 84
    protected function mergeFile(RootPackageInterface $root, $path)
217
    {
218 84
        if (isset($this->loadedFiles[$path])) {
219 84
            $this->logger->debug("Already merged <comment>$path</comment>");
220 84
            return;
221
        } else {
222 84
            $this->loadedFiles[$path] = true;
223
        }
224 84
        $this->logger->info("Loading <comment>{$path}</comment>...");
225
226 84
        $package = new ExtraPackage($path, $this->composer, $this->logger, $this->io);
227 84
        $package->mergeInto($root, $this->state);
228
229 84
        if ($this->state->recurseIncludes()) {
230 79
            $this->mergeFiles($package->getIncludes(), false);
231 79
            $this->mergeFiles($package->getRequires(), true);
232 79
        }
233 84
    }
234
235
    /**
236
     * Handle an event callback for pre-dependency solving phase of an install
237
     * or update by adding any duplicate package dependencies found during
238
     * initial merge processing to the request that will be processed by the
239
     * dependency solver.
240
     *
241
     * @param InstallerEvent $event
242
     */
243 84
    public function onDependencySolve(InstallerEvent $event)
244
    {
245 84
        $request = $event->getRequest();
246 84
        foreach ($this->state->getDuplicateLinks('require') as $link) {
247 10
            $this->logger->info(
248 10
                "Adding dependency <comment>{$link}</comment>"
249 10
            );
250 10
            $request->install($link->getTarget(), $link->getConstraint());
251 84
        }
252 84
        if ($this->state->isDevMode()) {
253 79
            foreach ($this->state->getDuplicateLinks('require-dev') as $link) {
254 5
                $this->logger->info(
255 5
                    "Adding dev dependency <comment>{$link}</comment>"
256 5
                );
257 5
                $request->install($link->getTarget(), $link->getConstraint());
258 79
            }
259 79
        }
260 84
    }
261
262
    /**
263
     * Handle an event callback following installation of a new package by
264
     * checking to see if the package that was installed was our plugin.
265
     *
266
     * @param PackageEvent $event
267
     */
268 15
    public function onPostPackageInstall(PackageEvent $event)
269
    {
270 15
        $op = $event->getOperation();
271 15
        if ($op instanceof InstallOperation) {
272 15
            $package = $op->getPackage()->getName();
273 15
            if ($package === self::PACKAGE_NAME) {
274 10
                $this->logger->info('composer-merge-plugin installed');
275 10
                $this->state->setFirstInstall(true);
276 10
                $this->state->setLocked(
277 10
                    $event->getComposer()->getLocker()->isLocked()
278 10
                );
279 10
            }
280 15
        }
281 15
    }
282
283
    /**
284
     * Handle an event callback following an install or update command. If our
285
     * plugin was installed during the run then trigger an update command to
286
     * process any merge-patterns in the current config.
287
     *
288
     * @param Event $event
289
     */
290 84
    public function onPostInstallOrUpdate(Event $event)
291
    {
292
        // @codeCoverageIgnoreStart
293
        if ($this->state->isFirstInstall()) {
294
            $this->state->setFirstInstall(false);
295
            $this->logger->info(
296
                '<comment>' .
297
                'Running additional update to apply merge settings' .
298
                '</comment>'
299
            );
300
301
            $config = $this->composer->getConfig();
302
303
            $preferSource = $config->get('preferred-install') == 'source';
304
            $preferDist = $config->get('preferred-install') == 'dist';
305
306
            $installer = Installer::create(
307
                $event->getIO(),
308
                // Create a new Composer instance to ensure full processing of
309
                // the merged files.
310
                Factory::create($event->getIO(), null, false)
311
            );
312
313
            $installer->setPreferSource($preferSource);
314
            $installer->setPreferDist($preferDist);
315
            $installer->setDevMode($event->isDevMode());
316
            $installer->setDumpAutoloader($this->state->shouldDumpAutoloader());
317
            $installer->setOptimizeAutoloader(
318
                $this->state->shouldOptimizeAutoloader()
319
            );
320
321
            if ($this->state->forceUpdate()) {
322
                // Force update mode so that new packages are processed rather
323
                // than just telling the user that composer.json and
324
                // composer.lock don't match.
325
                $installer->setUpdate(true);
326
            }
327
328
            $installer->run();
329
        }
330
        // @codeCoverageIgnoreEnd
331 84
    }
332
}
333
// vim:sw=4:ts=4:sts=4:et:
334