Completed
Pull Request — master (#114)
by Fabian
25:20
created

ExtraPackage::mergeExtraArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 3
crap 2
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
use Wikimedia\Composer\NestedArray;
15
16
use Composer\Composer;
17
use Composer\Json\JsonFile;
18
use Composer\Package\BasePackage;
19
use Composer\Package\CompletePackage;
20
use Composer\Package\Link;
21
use Composer\Package\Loader\ArrayLoader;
22
use Composer\Package\RootAliasPackage;
23
use Composer\Package\RootPackage;
24
use Composer\Package\RootPackageInterface;
25
use Composer\Package\Version\VersionParser;
26
use UnexpectedValueException;
27
28
/**
29
 * Processing for a composer.json file that will be merged into
30
 * a RootPackageInterface
31
 *
32
 * @author Bryan Davis <[email protected]>
33
 */
34
class ExtraPackage
35
{
36
37
    /**
38
     * @var Composer $composer
39
     */
40
    protected $composer;
41
42
    /**
43
     * @var Logger $logger
44
     */
45
    protected $logger;
46
47
    /**
48
     * @var string $path
49
     */
50
    protected $path;
51
52
    /**
53
     * @var array $json
54
     */
55
    protected $json;
56
57
    /**
58
     * @var CompletePackage $package
59
     */
60
    protected $package;
61
62
    /**
63
     * @var VersionParser $versionParser
64
     */
65
    protected $versionParser;
66
67
    /**
68
     * @param string $path Path to composer.json file
69
     * @param Composer $composer
70
     * @param Logger $logger
71 95
     */
72
    public function __construct($path, Composer $composer, Logger $logger)
73 95
    {
74 95
        $this->path = $path;
75 95
        $this->composer = $composer;
76 95
        $this->logger = $logger;
77 95
        $this->json = $this->readPackageJson($path);
78 95
        $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...
79 95
        $this->versionParser = new VersionParser();
80
    }
81
82
    /**
83
     * Get list of additional packages to include if precessing recursively.
84
     *
85
     * @return array
86 90
     */
87
    public function getIncludes()
88 90
    {
89 90
        return isset($this->json['extra']['merge-plugin']['include']) ?
90
            $this->json['extra']['merge-plugin']['include'] : array();
91
    }
92
93
    /**
94
     * Get list of additional packages to require if precessing recursively.
95
     *
96
     * @return array
97 90
     */
98
    public function getRequires()
99 90
    {
100 90
        return isset($this->json['extra']['merge-plugin']['require']) ?
101
            $this->json['extra']['merge-plugin']['require'] : array();
102
    }
103
104
    /**
105
     * Read the contents of a composer.json style file into an array.
106
     *
107
     * The package contents are fixed up to be usable to create a Package
108
     * object by providing dummy "name" and "version" values if they have not
109
     * been provided in the file. This is consistent with the default root
110
     * package loading behavior of Composer.
111
     *
112
     * @param string $path
113
     * @return array
114 95
     */
115
    protected function readPackageJson($path)
116 95
    {
117 95
        $file = new JsonFile($path);
118 95
        $json = $file->read();
119 90
        if (!isset($json['name'])) {
120 90
            $json['name'] = 'merge-plugin/' .
121 90
                strtr($path, DIRECTORY_SEPARATOR, '-');
122 95
        }
123 95
        if (!isset($json['version'])) {
124 95
            $json['version'] = '1.0.0';
125 95
        }
126
        return $json;
127
    }
128
129
    /**
130
     * @param string $json
131
     * @return CompletePackage
132 95
     */
133
    protected function loadPackage($json)
134 95
    {
135 95
        $loader = new ArrayLoader();
136
        $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...
137
        // @codeCoverageIgnoreStart
138
        if (!$package instanceof CompletePackage) {
139
            throw new UnexpectedValueException(
140
                'Expected instance of CompletePackage, got ' .
141
                get_class($package)
142
            );
143
        }
144 95
        // @codeCoverageIgnoreEnd
145
        return $package;
146
    }
147
148
    /**
149
     * Merge this package into a RootPackageInterface
150
     *
151
     * @param RootPackageInterface $root
152
     * @param PluginState $state
153 95
     */
154
    public function mergeInto(RootPackageInterface $root, PluginState $state)
155 95
    {
156
        $this->addRepositories($root);
157 95
158 95
        $this->mergeRequires('require', $root, $state);
159 90
        if ($state->isDevMode()) {
160 90
            $this->mergeRequires('require-dev', $root, $state);
161
        }
162 95
163 95
        $this->mergePackageLinks('conflict', $root);
164 95
        $this->mergePackageLinks('replace', $root);
165
        $this->mergePackageLinks('provide', $root);
166 95
167
        $this->mergeSuggests($root);
168 95
169 95
        $this->mergeAutoload('autoload', $root);
170 90
        if ($state->isDevMode()) {
171 90
            $this->mergeAutoload('devAutoload', $root);
172
        }
173 95
174 95
        $this->mergeExtra($root, $state);
175 95
        $this->mergeReferences($root);
176
    }
177
178
    /**
179
     * Add a collection of repositories described by the given configuration
180
     * to the given package and the global repository manager.
181
     *
182
     * @param RootPackageInterface $root
183 95
     */
184
    protected function addRepositories(RootPackageInterface $root)
185 95
    {
186 85
        if (!isset($this->json['repositories'])) {
187
            return;
188 10
        }
189 10
        $repoManager = $this->composer->getRepositoryManager();
190
        $newRepos = array();
191 10
192 10
        foreach ($this->json['repositories'] as $repoJson) {
193 10
            if (!isset($repoJson['type'])) {
194
                continue;
195 10
            }
196 10
            $this->logger->info("Adding {$repoJson['type']} repository");
197 10
            $repo = $repoManager->createRepository(
198
                $repoJson['type'],
199 10
                $repoJson
200 10
            );
201 10
            $repoManager->addRepository($repo);
202 10
            $newRepos[] = $repo;
203
        }
204 10
205 10
        $unwrapped = self::unwrapIfNeeded($root, 'setRepositories');
206 10
        $unwrapped->setRepositories(array_merge(
207 10
            $newRepos,
208 10
            $root->getRepositories()
209 10
        ));
210
    }
211
212
    /**
213
     * Merge require or require-dev into a RootPackageInterface
214
     *
215
     * @param string $type 'require' or 'require-dev'
216
     * @param RootPackageInterface $root
217
     * @param PluginState $state
218 95
     */
219
    protected function mergeRequires(
220
        $type,
221
        RootPackageInterface $root,
222
        PluginState $state
223 95
    ) {
224 95
        $linkType = BasePackage::$supportedLinkTypes[$type];
225 95
        $getter = 'get' . ucfirst($linkType['method']);
226
        $setter = 'set' . ucfirst($linkType['method']);
227 95
228 95
        $requires = $this->package->{$getter}();
229 75
        if (empty($requires)) {
230
            return;
231
        }
232 65
233
        $this->mergeStabilityFlags($root, $requires);
234 65
235 65
        $requires = $this->replaceSelfVersionDependencies(
236 65
            $type,
237
            $requires,
238 65
            $root
239
        );
240 65
241 65
        $root->{$setter}($this->mergeOrDefer(
242 65
            $type,
243 65
            $root->{$getter}(),
244
            $requires,
245 65
            $state
246 65
        ));
247
    }
248
249
    /**
250
     * Merge two collections of package links and collect duplicates for
251
     * subsequent processing.
252
     *
253
     * @param string $type 'require' or 'require-dev'
254
     * @param array $origin Primary collection
255
     * @param array $merge Additional collection
256
     * @param PluginState $state
257
     * @return array Merged collection
258 65
     */
259
    protected function mergeOrDefer(
260
        $type,
261
        array $origin,
262
        array $merge,
263
        $state
264 65
    ) {
265 65
        $dups = array();
266 65
        foreach ($merge as $name => $link) {
267 65
            if (!isset($origin[$name]) || $state->replaceDuplicateLinks()) {
268 65
                $this->logger->info("Merging <comment>{$name}</comment>");
269 65
                $origin[$name] = $link;
270
            } else {
271 15
                // Defer to solver.
272 15
                $this->logger->info(
273 15
                    "Deferring duplicate <comment>{$name}</comment>"
274 15
                );
275
                $dups[] = $link;
276 65
            }
277 65
        }
278 65
        $state->addDuplicateLinks($type, $dups);
279
        return $origin;
280
    }
281
282
    /**
283
     * Merge autoload or autoload-dev into a RootPackageInterface
284
     *
285
     * @param string $type 'autoload' or 'devAutoload'
286
     * @param RootPackageInterface $root
287 95
     */
288
    protected function mergeAutoload($type, RootPackageInterface $root)
289 95
    {
290 95
        $getter = 'get' . ucfirst($type);
291
        $setter = 'set' . ucfirst($type);
292 95
293 95
        $autoload = $this->package->{$getter}();
294 90
        if (empty($autoload)) {
295
            return;
296
        }
297 10
298 10
        $unwrapped = self::unwrapIfNeeded($root, $setter);
299 10
        $unwrapped->{$setter}(array_merge_recursive(
300 10
            $root->{$getter}(),
301 10
            $this->fixRelativePaths($autoload)
302 10
        ));
303
    }
304
305
    /**
306
     * Fix a collection of paths that are relative to this package to be
307
     * relative to the base package.
308
     *
309
     * @param array $paths
310
     * @return array
311 10
     */
312
    protected function fixRelativePaths(array $paths)
313 10
    {
314 10
        $base = dirname($this->path);
315
        $base = ($base === '.') ? '' : "{$base}/";
316 10
317 10
        array_walk_recursive(
318
            $paths,
319 10
            function (&$path) use ($base) {
320 10
                $path = "{$base}{$path}";
321 10
            }
322 10
        );
323
        return $paths;
324
    }
325
326
    /**
327
     * Extract and merge stability flags from the given collection of
328
     * requires and merge them into a RootPackageInterface
329
     *
330
     * @param RootPackageInterface $root
331
     * @param array $requires
332 65
     */
333
    protected function mergeStabilityFlags(
334
        RootPackageInterface $root,
335
        array $requires
336 65
    ) {
337 65
        $flags = $root->getStabilityFlags();
338
        $sf = new StabilityFlags($flags, $root->getMinimumStability());
339 65
340 65
        $unwrapped = self::unwrapIfNeeded($root, 'setStabilityFlags');
341 65
        $unwrapped->setStabilityFlags(array_merge(
342 65
            $flags,
343 65
            $sf->extractAll($requires)
344 65
        ));
345
    }
346
347
    /**
348
     * Merge package links of the given type  into a RootPackageInterface
349
     *
350
     * @param string $type 'conflict', 'replace' or 'provide'
351
     * @param RootPackageInterface $root
352 95
     */
353
    protected function mergePackageLinks($type, RootPackageInterface $root)
354 95
    {
355 95
        $linkType = BasePackage::$supportedLinkTypes[$type];
356 95
        $getter = 'get' . ucfirst($linkType['method']);
357
        $setter = 'set' . ucfirst($linkType['method']);
358 95
359 95
        $links = $this->package->{$getter}();
360 20
        if (!empty($links)) {
361
            $unwrapped = self::unwrapIfNeeded($root, $setter);
362
            // @codeCoverageIgnoreStart
363
            if ($root !== $unwrapped) {
364
                $this->logger->warning(
365
                    'This Composer version does not support ' .
366
                    "'{$type}' merging for aliased packages."
367
                );
368
            }
369 20
            // @codeCoverageIgnoreEnd
370 20
            $unwrapped->{$setter}(array_merge(
371 20
                $root->{$getter}(),
372 20
                $this->replaceSelfVersionDependencies($type, $links, $root)
373 20
            ));
374 95
        }
375
    }
376
377
    /**
378
     * Merge suggested packages into a RootPackageInterface
379
     *
380
     * @param RootPackageInterface $root
381 95
     */
382
    protected function mergeSuggests(RootPackageInterface $root)
383 95
    {
384 95
        $suggests = $this->package->getSuggests();
385 10
        if (!empty($suggests)) {
386 10
            $unwrapped = self::unwrapIfNeeded($root, 'setSuggests');
387 10
            $unwrapped->setSuggests(array_merge(
388
                $root->getSuggests(),
389 10
                $suggests
390 10
            ));
391 95
        }
392
    }
393
394
    /**
395
     * Merge extra config into a RootPackageInterface
396
     *
397
     * @param RootPackageInterface $root
398
     * @param PluginState $state
399 95
     */
400
    public function mergeExtra(RootPackageInterface $root, PluginState $state)
401 95
    {
402 95
        $extra = $this->package->getExtra();
403 95
        unset($extra['merge-plugin']);
404 80
        if (!$state->shouldMergeExtra() || empty($extra)) {
405
            return;
406
        }
407 15
408 15
        $rootExtra = $root->getExtra();
409
        $unwrapped = self::unwrapIfNeeded($root, 'setExtra');
410 15
411 5
        if ($state->replaceDuplicateLinks()) {
412 5
            $unwrapped->setExtra(
413 5
                self::mergeExtraArray($state->shouldMergeExtraDeep(), $rootExtra, $extra)
414
            );
415 5
        } else {
416 10
            if (!$state->shouldMergeExtraDeep()) {
417 10
                foreach (array_intersect(
418 10
                    array_keys($extra),
419 10
                    array_keys($rootExtra)
420 5
                ) as $key) {
421 5
                    $this->logger->info(
422 5
                        "Ignoring duplicate <comment>{$key}</comment> in ".
423 5
                        "<comment>{$this->path}</comment> extra config."
424 10
                    );
425 10
                }
426 10
            }
427 10
            $unwrapped->setExtra(
428
                self::mergeExtraArray($state->shouldMergeExtraDeep(), $extra, $rootExtra)
429 15
            );
430
        }
431
    }
432
433
    /**
434
     * Merges two arrays either via arrayMergeDeep or via array_merge.
435
     *
436
     * @param bool $mergeDeep
437
     * @param array $array1
438
     * @param array $array2
439
     * @return array
440 75
     */
441
    public static function mergeExtraArray($mergeDeep, $array1, $array2)
442
    {
443
        if ($mergeDeep) {
444
            return NestedArray::mergeDeep($array1, $array2);
445 75
        }
446 75
447 75
        return array_merge($array1, $array2);
448 75
    }
449
450 75
    /**
451 75
     * Update Links with a 'self.version' constraint with the root package's
452
     * version.
453 75
     *
454 75
     * @param string $type Link type
455 75
     * @param array $links
456 10
     * @param RootPackageInterface $root
457
     * @return array
458 5
     */
459 5
    protected function replaceSelfVersionDependencies(
460 5
        $type,
461 5
        array $links,
462 5
        RootPackageInterface $root
463 5
    ) {
464 5
        $linkType = BasePackage::$supportedLinkTypes[$type];
465 5
        $version = $root->getVersion();
466
        $prettyVersion = $root->getPrettyVersion();
467
        $vp = $this->versionParser;
468 5
469 5
        $method = 'get' . ucfirst($linkType['method']);
470 5
        $packages = $root->$method();
471 5
472 5
        return array_map(
473
            function ($link) use ($linkType, $version, $prettyVersion, $vp, $packages) {
474 5
                if ('self.version' === $link->getPrettyConstraint()) {
475
                    if (isset($packages[$link->getSource()])) {
476 75
                        /** @var Link $package */
477 75
                        $package = $packages[$link->getSource()];
478
                        return new Link(
479 75
                            $link->getSource(),
480
                            $link->getTarget(),
481
                            $vp->parseConstraints($package->getConstraint()->getPrettyString()),
482
                            $linkType['description'],
483
                            $package->getPrettyConstraint()
484
                        );
485
                    }
486
487
                    return new Link(
488
                        $link->getSource(),
489
                        $link->getTarget(),
490
                        $vp->parseConstraints($version),
491
                        $linkType['description'],
492
                        $prettyVersion
493
                    );
494
                }
495
                return $link;
496
            },
497
            $links
498
        );
499 95
    }
500
501
    /**
502
     * Get a full featured Package from a RootPackageInterface.
503
     *
504
     * In Composer versions before 599ad77 the RootPackageInterface only
505
     * defines a sub-set of operations needed by composer-merge-plugin and
506
     * RootAliasPackage only implemented those methods defined by the
507
     * interface. Most of the unimplemented methods in RootAliasPackage can be
508
     * worked around because the getter methods that are implemented proxy to
509
     * the aliased package which we can modify by unwrapping. The exception
510
     * being modifying the 'conflicts', 'provides' and 'replaces' collections.
511 95
     * We have no way to actually modify those collections unfortunately in
512
     * older versions of Composer.
513
     *
514
     * @param RootPackageInterface $root
515
     * @param string $method Method needed
516
     * @return RootPackageInterface|RootPackage
517
     */
518
    public static function unwrapIfNeeded(
519 95
        RootPackageInterface $root,
520
        $method = 'setExtra'
521
    ) {
522
        // @codeCoverageIgnoreStart
523 95
        if ($root instanceof RootAliasPackage &&
524 95
            !method_exists($root, $method)
525 95
        ) {
526 95
            // Unwrap and return the aliased RootPackage.
527 95
            $root = $root->getAliasOf();
528 95
        }
529 95
        // @codeCoverageIgnoreEnd
530 35
        return $root;
531 95
    }
532 95
533 95
    /**
534 95
     * Update the root packages reference information.
535 95
     *
536
     * @param RootPackageInterface $root
537
     */
538
    protected function mergeReferences(RootPackageInterface $root)
539
    {
540
        // Merge source reference information for merged packages.
541
        // @see RootPackageLoader::load
542
        $references = array();
543
        $unwrapped = $this->unwrapIfNeeded($root, 'setReferences');
544
        foreach (array('require', 'require-dev') as $linkType) {
545 95
            $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
546
            $method = 'get'.ucfirst($linkInfo['method']);
547 95
            $links = array();
548 35
            foreach ($unwrapped->$method() as $link) {
549 35
                $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
550
            }
551 35
            $references = $this->extractReferences($links, $references);
552
        }
553 35
        $unwrapped->setReferences($references);
554 5
    }
555 5
556 5
    /**
557 95
     * Extract vcs revision from version constraint (dev-master#abc123.
558
     *
559 95
     * @param array $requires
560
     * @param array $references
561
     * @return array
562
     * @see RootPackageLoader::extractReferences()
563
     */
564
    protected function extractReferences(array $requires, array $references)
565
    {
566
        foreach ($requires as $reqName => $reqVersion) {
567
            $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
568
            $stabilityName = VersionParser::parseStability($reqVersion);
569
            if (
570
                preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) &&
571
                $stabilityName === 'dev'
572
            ) {
573
                $name = strtolower($reqName);
574
                $references[$name] = $match[1];
575
            }
576
        }
577
578
        return $references;
579
    }
580
}
581
// vim:sw=4:ts=4:sts=4:et:
582