Completed
Pull Request — master (#124)
by Bryan
03:34
created

ExtraPackage::mergeDevInto()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
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\Merge;
12
13
use Wikimedia\Composer\Logger;
14
15
use Composer\Composer;
16
use Composer\Json\JsonFile;
17
use Composer\Package\BasePackage;
18
use Composer\Package\CompletePackage;
19
use Composer\Package\Link;
20
use Composer\Package\Loader\ArrayLoader;
21
use Composer\Package\RootAliasPackage;
22
use Composer\Package\RootPackage;
23
use Composer\Package\RootPackageInterface;
24
use Composer\Package\Version\VersionParser;
25
use UnexpectedValueException;
26
27
/**
28
 * Processing for a composer.json file that will be merged into
29
 * a RootPackageInterface
30
 *
31
 * @author Bryan Davis <[email protected]>
32
 */
33
class ExtraPackage
34
{
35
36
    /**
37
     * @var Composer $composer
38
     */
39
    protected $composer;
40
41
    /**
42
     * @var Logger $logger
43
     */
44
    protected $logger;
45
46
    /**
47
     * @var string $path
48
     */
49
    protected $path;
50
51
    /**
52
     * @var array $json
53
     */
54
    protected $json;
55
56
    /**
57
     * @var CompletePackage $package
58
     */
59
    protected $package;
60
61
    /**
62
     * @var VersionParser $versionParser
63
     */
64
    protected $versionParser;
65
66
    /**
67
     * @param string $path Path to composer.json file
68
     * @param Composer $composer
69
     * @param Logger $logger
70
     */
71 100
    public function __construct($path, Composer $composer, Logger $logger)
72
    {
73 100
        $this->path = $path;
74 100
        $this->composer = $composer;
75 100
        $this->logger = $logger;
76 100
        $this->json = $this->readPackageJson($path);
77 100
        $this->package = $this->loadPackage($this->json);
0 ignored issues
show
Documentation introduced by
$this->json is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
78 100
        $this->versionParser = new VersionParser();
79 100
    }
80
81
    /**
82
     * Get list of additional packages to include if precessing recursively.
83
     *
84
     * @return array
85
     */
86 95
    public function getIncludes()
87
    {
88 95
        return isset($this->json['extra']['merge-plugin']['include']) ?
89 95
            $this->json['extra']['merge-plugin']['include'] : array();
90
    }
91
92
    /**
93
     * Get list of additional packages to require if precessing recursively.
94
     *
95
     * @return array
96
     */
97 95
    public function getRequires()
98
    {
99 95
        return isset($this->json['extra']['merge-plugin']['require']) ?
100 95
            $this->json['extra']['merge-plugin']['require'] : array();
101
    }
102
103
    /**
104
     * Read the contents of a composer.json style file into an array.
105
     *
106
     * The package contents are fixed up to be usable to create a Package
107
     * object by providing dummy "name" and "version" values if they have not
108
     * been provided in the file. This is consistent with the default root
109
     * package loading behavior of Composer.
110
     *
111
     * @param string $path
112
     * @return array
113
     */
114 100
    protected function readPackageJson($path)
115
    {
116 100
        $file = new JsonFile($path);
117 100
        $json = $file->read();
118 100
        if (!isset($json['name'])) {
119 95
            $json['name'] = 'merge-plugin/' .
120 95
                strtr($path, DIRECTORY_SEPARATOR, '-');
121 95
        }
122 100
        if (!isset($json['version'])) {
123 100
            $json['version'] = '1.0.0';
124 100
        }
125 100
        return $json;
126
    }
127
128
    /**
129
     * @param string $json
130
     * @return CompletePackage
131
     */
132 100
    protected function loadPackage($json)
133
    {
134 100
        $loader = new ArrayLoader();
135 100
        $package = $loader->load($json);
0 ignored issues
show
Documentation introduced by
$json is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
136
        // @codeCoverageIgnoreStart
137
        if (!$package instanceof CompletePackage) {
138
            throw new UnexpectedValueException(
139
                'Expected instance of CompletePackage, got ' .
140
                get_class($package)
141
            );
142
        }
143
        // @codeCoverageIgnoreEnd
144 100
        return $package;
145
    }
146
147
    /**
148
     * Merge this package into a RootPackageInterface
149
     *
150
     * @param RootPackageInterface $root
151
     * @param PluginState $state
152
     */
153 100
    public function mergeInto(RootPackageInterface $root, PluginState $state)
154
    {
155 100
        $this->prependRepositories($root);
156
157 100
        $this->mergeRequires('require', $root, $state);
158
159 100
        $this->mergePackageLinks('conflict', $root);
160 100
        $this->mergePackageLinks('replace', $root);
161 100
        $this->mergePackageLinks('provide', $root);
162
163 100
        $this->mergeSuggests($root);
164
165 100
        $this->mergeAutoload('autoload', $root);
166
167 100
        $this->mergeExtra($root, $state);
168
169 100
        if ($state->isDevMode()) {
170 95
            $this->mergeDevInto($root, $state);
171 95
        } else {
172 5
            $this->mergeReferences($root);
173
        }
174 100
    }
175
176
    /**
177
     * Merge just the dev portion into a RootPackageInterface
178
     *
179
     * @param RootPackageInterface $root
180
     * @param PluginState $state
181
     */
182 95
    public function mergeDevInto(RootPackageInterface $root, PluginState $state)
183
    {
184 95
        $this->mergeRequires('require-dev', $root, $state);
185 95
        $this->mergeAutoload('devAutoload', $root);
186 95
        $this->mergeReferences($root);
187 95
    }
188
189
    /**
190
     * Add a collection of repositories described by the given configuration
191
     * to the given package and the global repository manager.
192
     *
193
     * @param RootPackageInterface $root
194
     */
195 100
    protected function prependRepositories(RootPackageInterface $root)
196
    {
197 100
        if (!isset($this->json['repositories'])) {
198 85
            return;
199
        }
200 15
        $repoManager = $this->composer->getRepositoryManager();
201 15
        $newRepos = array();
202
203 15
        foreach ($this->json['repositories'] as $repoJson) {
204 15
            if (!isset($repoJson['type'])) {
205 10
                continue;
206
            }
207 15
            $this->logger->info("Prepending {$repoJson['type']} repository");
208 15
            $repo = $repoManager->createRepository(
209 15
                $repoJson['type'],
210
                $repoJson
211 15
            );
212 15
            $repoManager->prependRepository($repo);
213 15
            $newRepos[] = $repo;
214 15
        }
215
216 15
        $unwrapped = self::unwrapIfNeeded($root, 'setRepositories');
217 15
        $unwrapped->setRepositories(array_merge(
218 15
            $newRepos,
219 15
            $root->getRepositories()
220 15
        ));
221 15
    }
222
223
    /**
224
     * Merge require or require-dev into a RootPackageInterface
225
     *
226
     * @param string $type 'require' or 'require-dev'
227
     * @param RootPackageInterface $root
228
     * @param PluginState $state
229
     */
230 100
    protected function mergeRequires(
231
        $type,
232
        RootPackageInterface $root,
233
        PluginState $state
234
    ) {
235 100
        $linkType = BasePackage::$supportedLinkTypes[$type];
236 100
        $getter = 'get' . ucfirst($linkType['method']);
237 100
        $setter = 'set' . ucfirst($linkType['method']);
238
239 100
        $requires = $this->package->{$getter}();
240 100
        if (empty($requires)) {
241 80
            return;
242
        }
243
244 65
        $this->mergeStabilityFlags($root, $requires);
245
246 65
        $requires = $this->replaceSelfVersionDependencies(
247 65
            $type,
248 65
            $requires,
249
            $root
250 65
        );
251
252 65
        $root->{$setter}($this->mergeOrDefer(
253 65
            $type,
254 65
            $root->{$getter}(),
255 65
            $requires,
256
            $state
257 65
        ));
258 65
    }
259
260
    /**
261
     * Merge two collections of package links and collect duplicates for
262
     * subsequent processing.
263
     *
264
     * @param string $type 'require' or 'require-dev'
265
     * @param array $origin Primary collection
266
     * @param array $merge Additional collection
267
     * @param PluginState $state
268
     * @return array Merged collection
269
     */
270 65
    protected function mergeOrDefer(
271
        $type,
272
        array $origin,
273
        array $merge,
274
        $state
275
    ) {
276 65
        $dups = array();
277 65
        foreach ($merge as $name => $link) {
278 65
            if (!isset($origin[$name]) || $state->replaceDuplicateLinks()) {
279 65
                $this->logger->info("Merging <comment>{$name}</comment>");
280 65
                $origin[$name] = $link;
281 65
            } else {
282
                // Defer to solver.
283 15
                $this->logger->info(
284 15
                    "Deferring duplicate <comment>{$name}</comment>"
285 15
                );
286 15
                $dups[] = $link;
287
            }
288 65
        }
289 65
        $state->addDuplicateLinks($type, $dups);
290 65
        return $origin;
291
    }
292
293
    /**
294
     * Merge autoload or autoload-dev into a RootPackageInterface
295
     *
296
     * @param string $type 'autoload' or 'devAutoload'
297
     * @param RootPackageInterface $root
298
     */
299 100
    protected function mergeAutoload($type, RootPackageInterface $root)
300
    {
301 100
        $getter = 'get' . ucfirst($type);
302 100
        $setter = 'set' . ucfirst($type);
303
304 100
        $autoload = $this->package->{$getter}();
305 100
        if (empty($autoload)) {
306 95
            return;
307
        }
308
309 10
        $unwrapped = self::unwrapIfNeeded($root, $setter);
310 10
        $unwrapped->{$setter}(array_merge_recursive(
311 10
            $root->{$getter}(),
312 10
            $this->fixRelativePaths($autoload)
313 10
        ));
314 10
    }
315
316
    /**
317
     * Fix a collection of paths that are relative to this package to be
318
     * relative to the base package.
319
     *
320
     * @param array $paths
321
     * @return array
322
     */
323 10
    protected function fixRelativePaths(array $paths)
324
    {
325 10
        $base = dirname($this->path);
326 10
        $base = ($base === '.') ? '' : "{$base}/";
327
328 10
        array_walk_recursive(
329 10
            $paths,
330
            function (&$path) use ($base) {
331 10
                $path = "{$base}{$path}";
332 10
            }
333 10
        );
334 10
        return $paths;
335
    }
336
337
    /**
338
     * Extract and merge stability flags from the given collection of
339
     * requires and merge them into a RootPackageInterface
340
     *
341
     * @param RootPackageInterface $root
342
     * @param array $requires
343
     */
344 65
    protected function mergeStabilityFlags(
345
        RootPackageInterface $root,
346
        array $requires
347
    ) {
348 65
        $flags = $root->getStabilityFlags();
349 65
        $sf = new StabilityFlags($flags, $root->getMinimumStability());
350
351 65
        $unwrapped = self::unwrapIfNeeded($root, 'setStabilityFlags');
352 65
        $unwrapped->setStabilityFlags(array_merge(
353 65
            $flags,
354 65
            $sf->extractAll($requires)
355 65
        ));
356 65
    }
357
358
    /**
359
     * Merge package links of the given type  into a RootPackageInterface
360
     *
361
     * @param string $type 'conflict', 'replace' or 'provide'
362
     * @param RootPackageInterface $root
363
     */
364 100
    protected function mergePackageLinks($type, RootPackageInterface $root)
365
    {
366 100
        $linkType = BasePackage::$supportedLinkTypes[$type];
367 100
        $getter = 'get' . ucfirst($linkType['method']);
368 100
        $setter = 'set' . ucfirst($linkType['method']);
369
370 100
        $links = $this->package->{$getter}();
371 100
        if (!empty($links)) {
372 20
            $unwrapped = self::unwrapIfNeeded($root, $setter);
373
            // @codeCoverageIgnoreStart
374
            if ($root !== $unwrapped) {
375
                $this->logger->warning(
376
                    'This Composer version does not support ' .
377
                    "'{$type}' merging for aliased packages."
378
                );
379
            }
380
            // @codeCoverageIgnoreEnd
381 20
            $unwrapped->{$setter}(array_merge(
382 20
                $root->{$getter}(),
383 20
                $this->replaceSelfVersionDependencies($type, $links, $root)
384 20
            ));
385 20
        }
386 100
    }
387
388
    /**
389
     * Merge suggested packages into a RootPackageInterface
390
     *
391
     * @param RootPackageInterface $root
392
     */
393 100
    protected function mergeSuggests(RootPackageInterface $root)
394
    {
395 100
        $suggests = $this->package->getSuggests();
396 100
        if (!empty($suggests)) {
397 10
            $unwrapped = self::unwrapIfNeeded($root, 'setSuggests');
398 10
            $unwrapped->setSuggests(array_merge(
399 10
                $root->getSuggests(),
400
                $suggests
401 10
            ));
402 10
        }
403 100
    }
404
405
    /**
406
     * Merge extra config into a RootPackageInterface
407
     *
408
     * @param RootPackageInterface $root
409
     * @param PluginState $state
410
     */
411 100
    public function mergeExtra(RootPackageInterface $root, PluginState $state)
412
    {
413 100
        $extra = $this->package->getExtra();
414 100
        unset($extra['merge-plugin']);
415 100
        if (!$state->shouldMergeExtra() || empty($extra)) {
416 85
            return;
417
        }
418
419 15
        $rootExtra = $root->getExtra();
420 15
        $unwrapped = self::unwrapIfNeeded($root, 'setExtra');
421
422 15
        if ($state->replaceDuplicateLinks()) {
423 5
            $unwrapped->setExtra(
424 5
                self::mergeExtraArray($state->shouldMergeExtraDeep(), $rootExtra, $extra)
425 5
            );
426 5
        } else {
427 10
            if (!$state->shouldMergeExtraDeep()) {
428 10
                foreach (array_intersect(
429 10
                    array_keys($extra),
430 10
                    array_keys($rootExtra)
431 10
                ) as $key) {
432 5
                    $this->logger->info(
433 5
                        "Ignoring duplicate <comment>{$key}</comment> in ".
434 5
                        "<comment>{$this->path}</comment> extra config."
435 5
                    );
436 10
                }
437 10
            }
438 10
            $unwrapped->setExtra(
439 10
                self::mergeExtraArray($state->shouldMergeExtraDeep(), $extra, $rootExtra)
440 10
            );
441
        }
442 15
    }
443
444
    /**
445
     * Merges two arrays either via arrayMergeDeep or via array_merge.
446
     *
447
     * @param bool $mergeDeep
448
     * @param array $array1
449
     * @param array $array2
450
     * @return array
451
     */
452 15
    public static function mergeExtraArray($mergeDeep, $array1, $array2)
453
    {
454 15
        if ($mergeDeep) {
455
            return NestedArray::mergeDeep($array1, $array2);
456
        }
457
458 15
        return array_merge($array1, $array2);
459
    }
460
461
    /**
462
     * Update Links with a 'self.version' constraint with the root package's
463
     * version.
464
     *
465
     * @param string $type Link type
466
     * @param array $links
467
     * @param RootPackageInterface $root
468
     * @return array
469
     */
470 75
    protected function replaceSelfVersionDependencies(
471
        $type,
472
        array $links,
473
        RootPackageInterface $root
474
    ) {
475 75
        $linkType = BasePackage::$supportedLinkTypes[$type];
476 75
        $version = $root->getVersion();
477 75
        $prettyVersion = $root->getPrettyVersion();
478 75
        $vp = $this->versionParser;
479
480 75
        $method = 'get' . ucfirst($linkType['method']);
481 75
        $packages = $root->$method();
482
483 75
        return array_map(
484 75
            function ($link) use ($linkType, $version, $prettyVersion, $vp, $packages) {
485 75
                if ('self.version' === $link->getPrettyConstraint()) {
486 10
                    if (isset($packages[$link->getSource()])) {
487
                        /** @var Link $package */
488 5
                        $package = $packages[$link->getSource()];
489 5
                        return new Link(
490 5
                            $link->getSource(),
491 5
                            $link->getTarget(),
492 5
                            $vp->parseConstraints($package->getConstraint()->getPrettyString()),
493 5
                            $linkType['description'],
494 5
                            $package->getPrettyConstraint()
495 5
                        );
496
                    }
497
498 5
                    return new Link(
499 5
                        $link->getSource(),
500 5
                        $link->getTarget(),
501 5
                        $vp->parseConstraints($version),
502 5
                        $linkType['description'],
503
                        $prettyVersion
504 5
                    );
505
                }
506 75
                return $link;
507 75
            },
508
            $links
509 75
        );
510
    }
511
512
    /**
513
     * Get a full featured Package from a RootPackageInterface.
514
     *
515
     * In Composer versions before 599ad77 the RootPackageInterface only
516
     * defines a sub-set of operations needed by composer-merge-plugin and
517
     * RootAliasPackage only implemented those methods defined by the
518
     * interface. Most of the unimplemented methods in RootAliasPackage can be
519
     * worked around because the getter methods that are implemented proxy to
520
     * the aliased package which we can modify by unwrapping. The exception
521
     * being modifying the 'conflicts', 'provides' and 'replaces' collections.
522
     * We have no way to actually modify those collections unfortunately in
523
     * older versions of Composer.
524
     *
525
     * @param RootPackageInterface $root
526
     * @param string $method Method needed
527
     * @return RootPackageInterface|RootPackage
528
     */
529 100
    public static function unwrapIfNeeded(
530
        RootPackageInterface $root,
531
        $method = 'setExtra'
532
    ) {
533
        // @codeCoverageIgnoreStart
534
        if ($root instanceof RootAliasPackage &&
535
            !method_exists($root, $method)
536
        ) {
537
            // Unwrap and return the aliased RootPackage.
538
            $root = $root->getAliasOf();
539
        }
540
        // @codeCoverageIgnoreEnd
541 100
        return $root;
542
    }
543
544
    /**
545
     * Update the root packages reference information.
546
     *
547
     * @param RootPackageInterface $root
548
     */
549 100
    protected function mergeReferences(RootPackageInterface $root)
550
    {
551
        // Merge source reference information for merged packages.
552
        // @see RootPackageLoader::load
553 100
        $references = array();
554 100
        $unwrapped = $this->unwrapIfNeeded($root, 'setReferences');
555 100
        foreach (array('require', 'require-dev') as $linkType) {
556 100
            $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
557 100
            $method = 'get'.ucfirst($linkInfo['method']);
558 100
            $links = array();
559 100
            foreach ($unwrapped->$method() as $link) {
560 40
                $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
561 100
            }
562 100
            $references = $this->extractReferences($links, $references);
563 100
        }
564 100
        $unwrapped->setReferences($references);
565 100
    }
566
567
    /**
568
     * Extract vcs revision from version constraint (dev-master#abc123.
569
     *
570
     * @param array $requires
571
     * @param array $references
572
     * @return array
573
     * @see RootPackageLoader::extractReferences()
574
     */
575 100
    protected function extractReferences(array $requires, array $references)
576
    {
577 100
        foreach ($requires as $reqName => $reqVersion) {
578 40
            $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
579 40
            $stabilityName = VersionParser::parseStability($reqVersion);
580
            if (
581 40
                preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) &&
582
                $stabilityName === 'dev'
583 40
            ) {
584 10
                $name = strtolower($reqName);
585 10
                $references[$name] = $match[1];
586 10
            }
587 100
        }
588
589 100
        return $references;
590
    }
591
}
592
// vim:sw=4:ts=4:sts=4:et:
593