Completed
Pull Request — master (#123)
by Bryan
22:39 queued 20:39
created

MergePlugin   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 238
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 100%

Importance

Changes 32
Bugs 2 Features 9
Metric Value
wmc 22
c 32
b 2
f 9
lcom 1
cbo 14
dl 0
loc 238
ccs 88
cts 88
cp 1
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A activate() 0 6 1
A getSubscribedEvents() 0 12 1
A onInstallUpdateOrDump() 0 15 3
A mergeFiles() 0 21 4
A mergeFile() 0 18 3
B onDependencySolve() 0 23 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
     * Files that have already been processed
106
     *
107
     * @var string[] $loadedFiles
108
     */
109
    protected $loadedFiles = array();
110
111
    /**
112
     * {@inheritdoc}
113
     */
114 120
    public function activate(Composer $composer, IOInterface $io)
115
    {
116 120
        $this->composer = $composer;
117 120
        $this->state = new PluginState($this->composer);
118 120
        $this->logger = new Logger('merge-plugin', $io);
119 120
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124 5
    public static function getSubscribedEvents()
125
    {
126
        return array(
127 5
            InstallerEvents::PRE_DEPENDENCIES_SOLVING => 'onDependencySolve',
128 5
            PackageEvents::POST_PACKAGE_INSTALL => 'onPostPackageInstall',
129 5
            ScriptEvents::POST_INSTALL_CMD => 'onPostInstallOrUpdate',
130 5
            ScriptEvents::POST_UPDATE_CMD => 'onPostInstallOrUpdate',
131 5
            ScriptEvents::PRE_AUTOLOAD_DUMP => 'onInstallUpdateOrDump',
132 5
            ScriptEvents::PRE_INSTALL_CMD => 'onInstallUpdateOrDump',
133 5
            ScriptEvents::PRE_UPDATE_CMD => 'onInstallUpdateOrDump',
134 5
        );
135
    }
136
137
    /**
138
     * Handle an event callback for an install, update or dump command by
139
     * checking for "merge-plugin" in the "extra" data and merging package
140
     * contents if found.
141
     *
142
     * @param Event $event
143
     */
144 100
    public function onInstallUpdateOrDump(Event $event)
145
    {
146 100
        $this->state->loadSettings();
147 100
        $this->state->setDevMode($event->isDevMode());
148 100
        $this->mergeFiles($this->state->getIncludes(), false);
149 100
        $this->mergeFiles($this->state->getRequires(), true);
150
151 95
        if ($event->getName() === ScriptEvents::PRE_AUTOLOAD_DUMP) {
152 95
            $this->state->setDumpAutoloader(true);
153 95
            $flags = $event->getFlags();
154 95
            if (isset($flags['optimize'])) {
155 95
                $this->state->setOptimizeAutoloader($flags['optimize']);
156 95
            }
157 95
        }
158 95
    }
159
160
    /**
161
     * Find configuration files matching the configured glob patterns and
162
     * merge their contents with the master package.
163
     *
164
     * @param array $patterns List of files/glob patterns
165
     * @param bool $required Are the patterns required to match files?
166
     * @throws MissingFileException when required and a pattern returns no
167
     *      results
168
     */
169 100
    protected function mergeFiles(array $patterns, $required = false)
170
    {
171 100
        $root = $this->composer->getPackage();
172
173 100
        $files = array_map(
174 100
            function ($files, $pattern) use ($required) {
175 100
                if ($required && !$files) {
176 5
                    throw new MissingFileException(
177 5
                        "merge-plugin: No files matched required '{$pattern}'"
178 5
                    );
179
                }
180 95
                return $files;
181 100
            },
182 100
            array_map('glob', $patterns),
183
            $patterns
184 100
        );
185
186 100
        foreach (array_reduce($files, 'array_merge', array()) as $path) {
187 95
            $this->mergeFile($root, $path);
188 100
        }
189 100
    }
190
191
    /**
192
     * Read a JSON file and merge its contents
193
     *
194
     * @param RootPackageInterface $root
195
     * @param string $path
196
     */
197 95
    protected function mergeFile(RootPackageInterface $root, $path)
198
    {
199 95
        if (isset($this->loadedFiles[$path])) {
200 95
            $this->logger->debug("Already merged <comment>$path</comment>");
201 95
            return;
202
        } else {
203 95
            $this->loadedFiles[$path] = true;
204
        }
205 95
        $this->logger->info("Loading <comment>{$path}</comment>...");
206
207 95
        $package = new ExtraPackage($path, $this->composer, $this->logger);
208 95
        $package->mergeInto($root, $this->state);
209
210 95
        if ($this->state->recurseIncludes()) {
211 90
            $this->mergeFiles($package->getIncludes(), false);
212 90
            $this->mergeFiles($package->getRequires(), true);
213 90
        }
214 95
    }
215
216
    /**
217
     * Handle an event callback for pre-dependency solving phase of an install
218
     * or update by adding any duplicate package dependencies found during
219
     * initial merge processing to the request that will be processed by the
220
     * dependency solver.
221
     *
222
     * @param InstallerEvent $event
223
     */
224 95
    public function onDependencySolve(InstallerEvent $event)
225
    {
226 95
        $request = $event->getRequest();
227 95
        foreach ($this->state->getDuplicateLinks('require') as $link) {
228 15
            $this->logger->info(
229 15
                "Adding dependency <comment>{$link}</comment>"
230 15
            );
231 15
            $request->install($link->getTarget(), $link->getConstraint());
232 95
        }
233
234
        // Issue #113: Check devMode of event rather than our global state.
235
        // Composer fires the PRE_DEPENDENCIES_SOLVING event twice for
236
        // `--no-dev` operations to decide which packages are dev only
237
        // requirements.
238 95
        if ($event->isDevMode()) {
239 95
            foreach ($this->state->getDuplicateLinks('require-dev') as $link) {
240 5
                $this->logger->info(
241 5
                    "Adding dev dependency <comment>{$link}</comment>"
242 5
                );
243 5
                $request->install($link->getTarget(), $link->getConstraint());
244 95
            }
245 95
        }
246 95
    }
247
248
    /**
249
     * Handle an event callback following installation of a new package by
250
     * checking to see if the package that was installed was our plugin.
251
     *
252
     * @param PackageEvent $event
253
     */
254 15
    public function onPostPackageInstall(PackageEvent $event)
255
    {
256 15
        $op = $event->getOperation();
257 15
        if ($op instanceof InstallOperation) {
258 15
            $package = $op->getPackage()->getName();
259 15
            if ($package === self::PACKAGE_NAME) {
260 10
                $this->logger->info('composer-merge-plugin installed');
261 10
                $this->state->setFirstInstall(true);
262 10
                $this->state->setLocked(
263 10
                    $event->getComposer()->getLocker()->isLocked()
264 10
                );
265 10
            }
266 15
        }
267 15
    }
268
269
    /**
270
     * Handle an event callback following an install or update command. If our
271
     * plugin was installed during the run then trigger an update command to
272
     * process any merge-patterns in the current config.
273
     *
274
     * @param Event $event
275
     */
276 95
    public function onPostInstallOrUpdate(Event $event)
277
    {
278
        // @codeCoverageIgnoreStart
279
        if ($this->state->isFirstInstall()) {
280
            $this->state->setFirstInstall(false);
281
            $this->logger->info(
282
                '<comment>' .
283
                'Running additional update to apply merge settings' .
284
                '</comment>'
285
            );
286
287
            $config = $this->composer->getConfig();
288
289
            $preferSource = $config->get('preferred-install') == 'source';
290
            $preferDist = $config->get('preferred-install') == 'dist';
291
292
            $installer = Installer::create(
293
                $event->getIO(),
294
                // Create a new Composer instance to ensure full processing of
295
                // the merged files.
296
                Factory::create($event->getIO(), null, false)
297
            );
298
299
            $installer->setPreferSource($preferSource);
300
            $installer->setPreferDist($preferDist);
301
            $installer->setDevMode($event->isDevMode());
302
            $installer->setDumpAutoloader($this->state->shouldDumpAutoloader());
303
            $installer->setOptimizeAutoloader(
304
                $this->state->shouldOptimizeAutoloader()
305
            );
306
307
            if ($this->state->forceUpdate()) {
308
                // Force update mode so that new packages are processed rather
309
                // than just telling the user that composer.json and
310
                // composer.lock don't match.
311
                $installer->setUpdate(true);
312
            }
313
314
            $installer->run();
315
        }
316
        // @codeCoverageIgnoreEnd
317 95
    }
318
}
319
// vim:sw=4:ts=4:sts=4:et:
320