Completed
Push — master ( 54142e...5e447a )
by Bryan
09:44
created

ExtraPackage::unwrapIfNeeded()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 9.4285
cc 3
eloc 7
nc 2
nop 2
crap 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\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 140
    public function __construct($path, Composer $composer, Logger $logger)
72
    {
73 140
        $this->path = $path;
74 140
        $this->composer = $composer;
75 140
        $this->logger = $logger;
76 140
        $this->json = $this->readPackageJson($path);
77 140
        $this->package = $this->loadPackage($this->json);
78 140
        $this->versionParser = new VersionParser();
79 140
    }
80
81
    /**
82
     * Get list of additional packages to include if precessing recursively.
83
     *
84
     * @return array
85
     */
86 135
    public function getIncludes()
87
    {
88 135
        return isset($this->json['extra']['merge-plugin']['include']) ?
89 135
            $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 135
    public function getRequires()
98
    {
99 135
        return isset($this->json['extra']['merge-plugin']['require']) ?
100 135
            $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 140
    protected function readPackageJson($path)
115
    {
116 140
        $file = new JsonFile($path);
117 140
        $json = $file->read();
118 140
        if (!isset($json['name'])) {
119 130
            $json['name'] = 'merge-plugin/' .
120 130
                strtr($path, DIRECTORY_SEPARATOR, '-');
121 130
        }
122 140
        if (!isset($json['version'])) {
123 140
            $json['version'] = '1.0.0';
124 140
        }
125 140
        return $json;
126
    }
127
128
    /**
129
     * @param array $json
130
     * @return CompletePackage
131
     */
132 140
    protected function loadPackage(array $json)
133
    {
134 140
        $loader = new ArrayLoader();
135 140
        $package = $loader->load($json);
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 140
        return $package;
145
    }
146
147
    /**
148
     * Merge this package into a RootPackageInterface
149
     *
150
     * @param RootPackageInterface $root
151
     * @param PluginState $state
152
     */
153 140
    public function mergeInto(RootPackageInterface $root, PluginState $state)
154
    {
155 140
        $this->prependRepositories($root);
156
157 140
        $this->mergeRequires('require', $root, $state);
158
159 140
        $this->mergePackageLinks('conflict', $root);
160 140
        $this->mergePackageLinks('replace', $root);
161 140
        $this->mergePackageLinks('provide', $root);
162
163 140
        $this->mergeSuggests($root);
164
165 140
        $this->mergeAutoload('autoload', $root);
166
167 140
        $this->mergeExtra($root, $state);
168
169 140
        if ($state->isDevMode()) {
170 75
            $this->mergeDevInto($root, $state);
171 75
        } else {
172 65
            $this->mergeReferences($root);
173
        }
174 140
    }
175
176
    /**
177
     * Merge just the dev portion into a RootPackageInterface
178
     *
179
     * @param RootPackageInterface $root
180
     * @param PluginState $state
181
     */
182 135
    public function mergeDevInto(RootPackageInterface $root, PluginState $state)
183
    {
184 135
        $this->mergeRequires('require-dev', $root, $state);
185 135
        $this->mergeAutoload('devAutoload', $root);
186 135
        $this->mergeReferences($root);
187 135
    }
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 140
    protected function prependRepositories(RootPackageInterface $root)
196
    {
197 140
        if (!isset($this->json['repositories'])) {
198 120
            return;
199
        }
200 20
        $repoManager = $this->composer->getRepositoryManager();
201 20
        $newRepos = array();
202
203 20
        foreach ($this->json['repositories'] as $repoJson) {
204 20
            if (!isset($repoJson['type'])) {
205 15
                continue;
206
            }
207 20
            $this->logger->info("Prepending {$repoJson['type']} repository");
208 20
            $repo = $repoManager->createRepository(
209 20
                $repoJson['type'],
210
                $repoJson
211 20
            );
212 20
            $repoManager->prependRepository($repo);
213 20
            $newRepos[] = $repo;
214 20
        }
215
216 20
        $unwrapped = self::unwrapIfNeeded($root, 'setRepositories');
217 20
        $unwrapped->setRepositories(array_merge(
218 20
            $newRepos,
219 20
            $root->getRepositories()
220 20
        ));
221 20
    }
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 140
    protected function mergeRequires(
231
        $type,
232
        RootPackageInterface $root,
233
        PluginState $state
234
    ) {
235 140
        $linkType = BasePackage::$supportedLinkTypes[$type];
236 140
        $getter = 'get' . ucfirst($linkType['method']);
237 140
        $setter = 'set' . ucfirst($linkType['method']);
238
239 140
        $requires = $this->package->{$getter}();
240 140
        if (empty($requires)) {
241 105
            return;
242
        }
243
244 85
        $this->mergeStabilityFlags($root, $requires);
245
246 85
        $requires = $this->replaceSelfVersionDependencies(
247 85
            $type,
248 85
            $requires,
249
            $root
250 85
        );
251
252 85
        $root->{$setter}($this->mergeOrDefer(
253 85
            $type,
254 85
            $root->{$getter}(),
255 85
            $requires,
256
            $state
257 85
        ));
258 85
    }
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 85
    protected function mergeOrDefer(
271
        $type,
272
        array $origin,
273
        array $merge,
274
        $state
275
    ) {
276 85
        $dups = array();
277 85
        foreach ($merge as $name => $link) {
278 85
            if (!isset($origin[$name]) || $state->replaceDuplicateLinks()) {
279 85
                $this->logger->info("Merging <comment>{$name}</comment>");
280 85
                $origin[$name] = $link;
281 85
            } else {
282
                // Defer to solver.
283 25
                $this->logger->info(
284 25
                    "Deferring duplicate <comment>{$name}</comment>"
285 25
                );
286 25
                $dups[] = $link;
287
            }
288 85
        }
289 85
        $state->addDuplicateLinks($type, $dups);
290 85
        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 140
    protected function mergeAutoload($type, RootPackageInterface $root)
300
    {
301 140
        $getter = 'get' . ucfirst($type);
302 140
        $setter = 'set' . ucfirst($type);
303
304 140
        $autoload = $this->package->{$getter}();
305 140
        if (empty($autoload)) {
306 130
            return;
307
        }
308
309 15
        $unwrapped = self::unwrapIfNeeded($root, $setter);
310 15
        $unwrapped->{$setter}(array_merge_recursive(
311 15
            $root->{$getter}(),
312 15
            $this->fixRelativePaths($autoload)
313 15
        ));
314 15
    }
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 15
    protected function fixRelativePaths(array $paths)
324
    {
325 15
        $base = dirname($this->path);
326 15
        $base = ($base === '.') ? '' : "{$base}/";
327
328 15
        array_walk_recursive(
329 15
            $paths,
330
            function (&$path) use ($base) {
331 15
                $path = "{$base}{$path}";
332 15
            }
333 15
        );
334 15
        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 85
    protected function mergeStabilityFlags(
345
        RootPackageInterface $root,
346
        array $requires
347
    ) {
348 85
        $flags = $root->getStabilityFlags();
349 85
        $sf = new StabilityFlags($flags, $root->getMinimumStability());
350
351 85
        $unwrapped = self::unwrapIfNeeded($root, 'setStabilityFlags');
352 85
        $unwrapped->setStabilityFlags(array_merge(
353 85
            $flags,
354 85
            $sf->extractAll($requires)
355 85
        ));
356 85
    }
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 140
    protected function mergePackageLinks($type, RootPackageInterface $root)
365
    {
366 140
        $linkType = BasePackage::$supportedLinkTypes[$type];
367 140
        $getter = 'get' . ucfirst($linkType['method']);
368 140
        $setter = 'set' . ucfirst($linkType['method']);
369
370 140
        $links = $this->package->{$getter}();
371 140
        if (!empty($links)) {
372 30
            $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 30
            $unwrapped->{$setter}(array_merge(
382 30
                $root->{$getter}(),
383 30
                $this->replaceSelfVersionDependencies($type, $links, $root)
384 30
            ));
385 30
        }
386 140
    }
387
388
    /**
389
     * Merge suggested packages into a RootPackageInterface
390
     *
391
     * @param RootPackageInterface $root
392
     */
393 140
    protected function mergeSuggests(RootPackageInterface $root)
394
    {
395 140
        $suggests = $this->package->getSuggests();
396 140
        if (!empty($suggests)) {
397 15
            $unwrapped = self::unwrapIfNeeded($root, 'setSuggests');
398 15
            $unwrapped->setSuggests(array_merge(
399 15
                $root->getSuggests(),
400
                $suggests
401 15
            ));
402 15
        }
403 140
    }
404
405
    /**
406
     * Merge extra config into a RootPackageInterface
407
     *
408
     * @param RootPackageInterface $root
409
     * @param PluginState $state
410
     */
411 140
    public function mergeExtra(RootPackageInterface $root, PluginState $state)
412
    {
413 140
        $extra = $this->package->getExtra();
414 140
        unset($extra['merge-plugin']);
415 140
        if (!$state->shouldMergeExtra() || empty($extra)) {
416 110
            return;
417
        }
418
419 30
        $rootExtra = $root->getExtra();
420 30
        $unwrapped = self::unwrapIfNeeded($root, 'setExtra');
421
422 30
        if ($state->replaceDuplicateLinks()) {
423 10
            $unwrapped->setExtra(
424 10
                self::mergeExtraArray($state->shouldMergeExtraDeep(), $rootExtra, $extra)
425 10
            );
426 10
        } else {
427 20
            if (!$state->shouldMergeExtraDeep()) {
428 15
                foreach (array_intersect(
429 15
                    array_keys($extra),
430 15
                    array_keys($rootExtra)
431 15
                ) 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 15
                }
437 15
            }
438 20
            $unwrapped->setExtra(
439 20
                self::mergeExtraArray($state->shouldMergeExtraDeep(), $extra, $rootExtra)
440 20
            );
441
        }
442 30
    }
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 30
    public static function mergeExtraArray($mergeDeep, $array1, $array2)
453
    {
454 30
        if ($mergeDeep) {
455 10
            return NestedArray::mergeDeep($array1, $array2);
456
        }
457
458 20
        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 100
    protected function replaceSelfVersionDependencies(
471
        $type,
472
        array $links,
473
        RootPackageInterface $root
474
    ) {
475 100
        $linkType = BasePackage::$supportedLinkTypes[$type];
476 100
        $version = $root->getVersion();
477 100
        $prettyVersion = $root->getPrettyVersion();
478 100
        $vp = $this->versionParser;
479
480 100
        $method = 'get' . ucfirst($linkType['method']);
481 100
        $packages = $root->$method();
482
483 100
        return array_map(
484 100
            function ($link) use ($linkType, $version, $prettyVersion, $vp, $packages) {
485 100
                if ('self.version' === $link->getPrettyConstraint()) {
486 15
                    if (isset($packages[$link->getSource()])) {
487
                        /** @var Link $package */
488 10
                        $package = $packages[$link->getSource()];
489 10
                        return new Link(
490 10
                            $link->getSource(),
491 10
                            $link->getTarget(),
492 10
                            $vp->parseConstraints($package->getConstraint()->getPrettyString()),
493 10
                            $linkType['description'],
494 10
                            $package->getPrettyConstraint()
495 10
                        );
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 100
                return $link;
507 100
            },
508
            $links
509 100
        );
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 140
    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 140
        return $root;
542
    }
543
544
    /**
545
     * Update the root packages reference information.
546
     *
547
     * @param RootPackageInterface $root
548
     */
549 140
    protected function mergeReferences(RootPackageInterface $root)
550
    {
551
        // Merge source reference information for merged packages.
552
        // @see RootPackageLoader::load
553 140
        $references = array();
554 140
        $unwrapped = $this->unwrapIfNeeded($root, 'setReferences');
555 140
        foreach (array('require', 'require-dev') as $linkType) {
556 140
            $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
557 140
            $method = 'get'.ucfirst($linkInfo['method']);
558 140
            $links = array();
559 140
            foreach ($unwrapped->$method() as $link) {
560 55
                $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
561 140
            }
562 140
            $references = $this->extractReferences($links, $references);
563 140
        }
564 140
        $unwrapped->setReferences($references);
565 140
    }
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 140
    protected function extractReferences(array $requires, array $references)
576
    {
577 140
        foreach ($requires as $reqName => $reqVersion) {
578 55
            $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
579 55
            $stabilityName = VersionParser::parseStability($reqVersion);
580
            if (
581 55
                preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) &&
582
                $stabilityName === 'dev'
583 55
            ) {
584 15
                $name = strtolower($reqName);
585 15
                $references[$name] = $match[1];
586 15
            }
587 140
        }
588
589 140
        return $references;
590
    }
591
}
592
// vim:sw=4:ts=4:sts=4:et:
593