Completed
Push — master ( 9a6301...9645a9 )
by Bryan
04:34
created

ExtraPackage::addRepositories()   C

Complexity

Conditions 7
Paths 13

Size

Total Lines 42
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 7

Importance

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