Passed
Push — master ( 382e1a...3fd618 )
by Allan
03:29
created

Context::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * Copyright © Vaimo Group. All rights reserved.
4
 * See LICENSE_VAIMO.txt for license details.
5
 */
6
namespace Vaimo\ComposerChangelogs\Composer;
7
8
class Context
9
{
10
    /**
11
     * @var \Composer\Composer[]
12
     */
13
    private $instances;
14
15
    /**
16
     * @var \Composer\Package\PackageInterface[][]
17
     */
18
    private $packages;
19
20
    /**
21
     * @param \Composer\Composer[]
22
     */
23
    public function __construct(
24
        array $instances
25
    ) {
26
        $this->instances = $instances;
27
    }
28
29
    public function getActivePackages()
30
    {
31
        return array_reduce(
32
            $this->getPackageMap(),
33
            'array_replace',
34
            array()
35
        );
36
    }
37
38
    public function getLocalComposer()
39
    {
40
        return end($this->instances);
41
    }
42
43
    private function getPackageMap()
44
    {
45
        if ($this->packages === null) {
46
            $result = array();
47
48
            foreach ($this->instances as $instanceIndex => $instance) {
49
                $repository = $instance->getRepositoryManager()->getLocalRepository();
50
51
                if (!isset($this->packages[$instanceIndex])) {
52
                    $this->packages[$instanceIndex] = array();
53
                }
54
55
                foreach ($repository->getCanonicalPackages() as $package) {
56
                    $name = $package->getName();
57
58
                    if (isset($result[$name])) {
59
                        continue;
60
                    }
61
62
                    $result[$name] = true;
63
                    $this->packages[$instanceIndex][$name] = $package;
64
                }
65
            }
66
        }
67
68
        return $this->packages;
69
    }
70
71
    public function getInstanceForPackage(\Composer\Package\PackageInterface $package)
72
    {
73
        $name = $package->getName();
74
        $packageMap = $this->getPackageMap();
75
76
        foreach ($packageMap as $index => $packages) {
77
            if (!isset($packages[$name])) {
78
                continue;
79
            }
80
81
            return $this->instances[$index];
82
        }
83
84
        $message = sprintf(
85
            'Failed to resolve Composer instance for package: %s',
86
            $name
87
        );
88
        
89
        throw new \Vaimo\ComposerChangelogs\Exceptions\RuntimeException($message);
90
    }
91
}
92