Completed
Pull Request — master (#114)
by Fabian
24:02 queued 22:13
created

ExtraPackage::mergePackageLinks()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

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