Completed
Pull Request — master (#117)
by Fabian
12:11
created

MergePlugin::onInit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 1
eloc 5
nc 1
nop 1
crap 1
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
     * Name of the composer 1.1 init event.
91
     */
92
    const INIT = 'init';
93
94
    /**
95
     * @var Composer $composer
96
     */
97
    protected $composer;
98
99
    /**
100
     * @var PluginState $state
101
     */
102
    protected $state;
103
104
    /**
105
     * @var Logger $logger
106
     */
107
    protected $logger;
108
109
    /**
110
     * Files that have already been fully processed
111
     *
112
     * @var string[] $loadedFiles
113
     */
114
    protected $loadedFiles = array();
115
116
    /**
117
     * Files that have already been partially processed
118
     *
119
     * @var string[] $partiallyLoadedFiles
120
     */
121
    protected $partiallyLoadedFiles = array();
122
123
    /**
124
     * {@inheritdoc}
125
     */
126 120
    public function activate(Composer $composer, IOInterface $io)
127
    {
128 120
        $this->composer = $composer;
129 120
        $this->state = new PluginState($this->composer);
130 120
        $this->logger = new Logger('merge-plugin', $io);
131 120
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136 5
    public static function getSubscribedEvents()
137
    {
138
        return array(
139
            // Use our own constant to make this event optional. Once
140
            // composer-1.1 is required, this can use PluginEvents::INIT
141
            // instead.
142 5
            self::INIT => 'onInit',
143 5
            InstallerEvents::PRE_DEPENDENCIES_SOLVING => 'onDependencySolve',
144 5
            PackageEvents::POST_PACKAGE_INSTALL => 'onPostPackageInstall',
145 5
            ScriptEvents::POST_INSTALL_CMD => 'onPostInstallOrUpdate',
146 5
            ScriptEvents::POST_UPDATE_CMD => 'onPostInstallOrUpdate',
147 5
            ScriptEvents::PRE_AUTOLOAD_DUMP => 'onInstallUpdateOrDump',
148 5
            ScriptEvents::PRE_INSTALL_CMD => 'onInstallUpdateOrDump',
149 5
            ScriptEvents::PRE_UPDATE_CMD => 'onInstallUpdateOrDump',
150 5
        );
151
    }
152
153
    /**
154
     * Handle an event callback for initialization.
155
     *
156
     * @param \Composer\EventDispatcher\Event $event
157
     */
158 100
    public function onInit(\Composer\EventDispatcher\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...
159
    {
160 100
        $this->state->loadSettings();
161
        // It is not possible to know if the user specified --dev or --no-dev
162
        // so assume it is false. The dev section will be merged later when
163
        // the other events fire.
164 100
        $this->state->setDevMode(false);
165 100
        $this->mergeFiles($this->state->getIncludes(), false);
166 100
        $this->mergeFiles($this->state->getRequires(), true);
167 95
    }
168
169
    /**
170
     * Handle an event callback for an install, update or dump command by
171
     * checking for "merge-plugin" in the "extra" data and merging package
172
     * contents if found.
173
     *
174
     * @param Event $event
175
     */
176 95
    public function onInstallUpdateOrDump(Event $event)
177
    {
178 95
        $this->state->loadSettings();
179 95
        $this->state->setDevMode($event->isDevMode());
180 95
        $this->mergeFiles($this->state->getIncludes(), false);
181 95
        $this->mergeFiles($this->state->getRequires(), true);
182
183 95
        if ($event->getName() === ScriptEvents::PRE_AUTOLOAD_DUMP) {
184 95
            $this->state->setDumpAutoloader(true);
185 95
            $flags = $event->getFlags();
186 95
            if (isset($flags['optimize'])) {
187 95
                $this->state->setOptimizeAutoloader($flags['optimize']);
188 95
            }
189 95
        }
190 95
    }
191
192
    /**
193
     * Find configuration files matching the configured glob patterns and
194
     * merge their contents with the master package.
195
     *
196
     * @param array $patterns List of files/glob patterns
197
     * @param bool $required Are the patterns required to match files?
198
     * @throws MissingFileException when required and a pattern returns no
199
     *      results
200
     */
201 100
    protected function mergeFiles(array $patterns, $required = false)
202
    {
203 100
        $root = $this->composer->getPackage();
204
205 100
        $files = array_map(
206 100
            function ($files, $pattern) use ($required) {
207 100
                if ($required && !$files) {
208 5
                    throw new MissingFileException(
209 5
                        "merge-plugin: No files matched required '{$pattern}'"
210 5
                    );
211
                }
212 95
                return $files;
213 100
            },
214 100
            array_map('glob', $patterns),
215
            $patterns
216 100
        );
217
218 100
        foreach (array_reduce($files, 'array_merge', array()) as $path) {
219 95
            $this->mergeFile($root, $path);
220 100
        }
221 100
    }
222
223
    /**
224
     * Read a JSON file and merge its contents
225
     *
226
     * @param RootPackageInterface $root
227
     * @param string $path
228
     */
229 95
    protected function mergeFile(RootPackageInterface $root, $path)
230
    {
231 95
        if (isset($this->loadedFiles[$path]) ||
232 95
            (isset($this->partiallyLoadedFiles[$path]) && !$this->state->isDevMode())) {
233 95
            $this->logger->debug("Already merged <comment>$path</comment> completely");
234 95
            return;
235
        }
236
237 95
        $this->logger->info("Loading <comment>{$path}</comment>...");
238
239 95
        $package = new ExtraPackage($path, $this->composer, $this->logger);
240
241
        // If something was already loaded, merge just the dev section.
242 95
        if (isset($this->partiallyLoadedFiles[$path])) {
243 90
            $package->mergeDev($root, $this->state);
244 90
        } else {
245 95
            $package->mergeInto($root, $this->state);
246
        }
247
248 95
        if ($this->state->isDevMode()) {
249 90
            $this->loadedFiles[$path] = true;
250 90
        } else {
251 95
            $this->partiallyLoadedFiles[$path] = true;
252
        }
253
254 95
        if ($this->state->recurseIncludes()) {
255 90
            $this->mergeFiles($package->getIncludes(), false);
256 90
            $this->mergeFiles($package->getRequires(), true);
257 90
        }
258 95
    }
259
260
    /**
261
     * Handle an event callback for pre-dependency solving phase of an install
262
     * or update by adding any duplicate package dependencies found during
263
     * initial merge processing to the request that will be processed by the
264
     * dependency solver.
265
     *
266
     * @param InstallerEvent $event
267
     */
268 95
    public function onDependencySolve(InstallerEvent $event)
269
    {
270 95
        $request = $event->getRequest();
271 95
        foreach ($this->state->getDuplicateLinks('require') as $link) {
272 15
            $this->logger->info(
273 15
                "Adding dependency <comment>{$link}</comment>"
274 15
            );
275 15
            $request->install($link->getTarget(), $link->getConstraint());
276 95
        }
277 95
        if ($this->state->isDevMode()) {
278 90
            foreach ($this->state->getDuplicateLinks('require-dev') as $link) {
279 5
                $this->logger->info(
280 5
                    "Adding dev dependency <comment>{$link}</comment>"
281 5
                );
282 5
                $request->install($link->getTarget(), $link->getConstraint());
283 90
            }
284 90
        }
285 95
    }
286
287
    /**
288
     * Handle an event callback following installation of a new package by
289
     * checking to see if the package that was installed was our plugin.
290
     *
291
     * @param PackageEvent $event
292
     */
293 15
    public function onPostPackageInstall(PackageEvent $event)
294
    {
295 15
        $op = $event->getOperation();
296 15
        if ($op instanceof InstallOperation) {
297 15
            $package = $op->getPackage()->getName();
298 15
            if ($package === self::PACKAGE_NAME) {
299 10
                $this->logger->info('composer-merge-plugin installed');
300 10
                $this->state->setFirstInstall(true);
301 10
                $this->state->setLocked(
302 10
                    $event->getComposer()->getLocker()->isLocked()
303 10
                );
304 10
            }
305 15
        }
306 15
    }
307
308
    /**
309
     * Handle an event callback following an install or update command. If our
310
     * plugin was installed during the run then trigger an update command to
311
     * process any merge-patterns in the current config.
312
     *
313
     * @param Event $event
314
     */
315 95
    public function onPostInstallOrUpdate(Event $event)
316
    {
317
        // @codeCoverageIgnoreStart
318
        if ($this->state->isFirstInstall()) {
319
            $this->state->setFirstInstall(false);
320
            $this->logger->info(
321
                '<comment>' .
322
                'Running additional update to apply merge settings' .
323
                '</comment>'
324
            );
325
326
            $config = $this->composer->getConfig();
327
328
            $preferSource = $config->get('preferred-install') == 'source';
329
            $preferDist = $config->get('preferred-install') == 'dist';
330
331
            $installer = Installer::create(
332
                $event->getIO(),
333
                // Create a new Composer instance to ensure full processing of
334
                // the merged files.
335
                Factory::create($event->getIO(), null, false)
336
            );
337
338
            $installer->setPreferSource($preferSource);
339
            $installer->setPreferDist($preferDist);
340
            $installer->setDevMode($event->isDevMode());
341
            $installer->setDumpAutoloader($this->state->shouldDumpAutoloader());
342
            $installer->setOptimizeAutoloader(
343
                $this->state->shouldOptimizeAutoloader()
344
            );
345
346
            if ($this->state->forceUpdate()) {
347
                // Force update mode so that new packages are processed rather
348
                // than just telling the user that composer.json and
349
                // composer.lock don't match.
350
                $installer->setUpdate(true);
351
            }
352
353
            $installer->run();
354
        }
355
        // @codeCoverageIgnoreEnd
356 95
    }
357
}
358
// vim:sw=4:ts=4:sts=4:et:
359