Completed
Pull Request — master (#1)
by Abdul Malik
04:32 queued 02:09
created

Installer::getVersions()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
ccs 10
cts 10
cp 1
rs 8.8571
cc 5
eloc 9
nc 10
nop 2
crap 5
1
<?php
2
3
namespace PackageVersions;
4
5
use Composer\Composer;
6
use Composer\Config;
7
use Composer\EventDispatcher\EventSubscriberInterface;
8
use Composer\IO\IOInterface;
9
use Composer\Package\AliasPackage;
10
use Composer\Package\Locker;
11
use Composer\Package\PackageInterface;
12
use Composer\Package\RootPackageInterface;
13
use Composer\Plugin\PluginInterface;
14
use Composer\Script\Event;
15
use Composer\Script\ScriptEvents;
16
17
final class Installer implements PluginInterface, EventSubscriberInterface
18
{
19
    private static $generatedClassTemplate = <<<'PHP'
20
<?php
21
22
namespace PackageVersions;
23
24
/**
25
 * This class is generated by samsonasik/package-versions, specifically by
26
 * @see \PackageVersions\Installer
27
 *
28
 * This file is overwritten at every run of `composer install` or `composer update`.
29
 */
30
%s
31
{
32
    const VERSIONS = %s;
33
34
    private function __construct()
35
    {
36
    }
37
38
    /**
39
     * @throws \OutOfBoundsException if a version cannot be located
40
     */
41
    public static function getVersion($packageName)
42
    {
43
        if (null !== self::VERSIONS[$packageName]) {
44
            throw new \OutOfBoundsException(
45
                'Required package "' . $packageName . '" is not installed: cannot detect its version'
46
            );
47
        }
48
49
        return self::VERSIONS[$packageName];
50
    }
51
}
52
53
PHP;
54
55
    /**
56
     * {@inheritDoc}
57
     */
58 1
    public function activate(Composer $composer, IOInterface $io)
59
    {
60 1
        $composer->getEventDispatcher()->addSubscriber($this);
61 1
    }
62
63
    /**
64
     * {@inheritDoc}
65
     */
66 1
    public static function getSubscribedEvents()
67
    {
68
        return [
69 1
            ScriptEvents::POST_INSTALL_CMD => 'dumpVersionsClass',
70 1
            ScriptEvents::POST_UPDATE_CMD  => 'dumpVersionsClass',
71
        ];
72
    }
73
74
    /**
75
     * @param Event $composerEvent
76
     *
77
     * @return void
78
     *
79
     * @throws \RuntimeException
80
     */
81 9
    public static function dumpVersionsClass(Event $composerEvent)
82
    {
83 9
        $io = $composerEvent->getIO();
84
85 9
        $io->write('<info>samsonasik/package-versions:</info>  Generating version class...');
86
87 9
        $composer = $composerEvent->getComposer();
88
89 9
        self::writeVersionClassToFile(
90 9
            self::generateVersionsClass($composer),
91 9
            $composer->getConfig(),
92 9
            $composer->getPackage()
93
        );
94
95 9
        $io->write('<info>samsonasik/package-versions:</info> ...done generating version class');
96 9
    }
97
98 9
    private static function generateVersionsClass(Composer $composer)
99
    {
100 9
        return sprintf(
101 9
            self::$generatedClassTemplate,
102 9
            'fin' . 'al ' . 'cla' . 'ss ' . 'Versions', // note: workaround for regex-based code parsers :-(
103 9
            var_export(iterator_to_array(self::getVersions($composer->getLocker(), $composer->getPackage())), true)
104
        );
105
    }
106
107
    /**
108
     * @param string               $versionClassSource
109
     * @param Config               $composerConfig
110
     * @param RootPackageInterface $rootPackage
111
     *
112
     * @return void
113
     *
114
     * @throws \RuntimeException
115
     */
116 9
    private static function writeVersionClassToFile(
117
        $versionClassSource,
118
        Config $composerConfig,
119
        RootPackageInterface $rootPackage
120
    ) {
121 9
        file_put_contents(
122 9
            self::locateRootPackageInstallPath($composerConfig, $rootPackage)
123 9
            . '/src/PackageVersions/Versions.php',
124
            $versionClassSource,
125 9
            0664
126
        );
127 9
    }
128
129
    /**
130
     * @param Config               $composerConfig
131
     * @param RootPackageInterface $rootPackage
132
     *
133
     * @return string
134
     *
135
     * @throws \RuntimeException
136
     */
137 9
    private static function locateRootPackageInstallPath(
138
        Config $composerConfig,
139
        RootPackageInterface $rootPackage
140
    ) {
141 9
        if ('samsonasik/package-versions' === self::getRootPackageAlias($rootPackage)->getName()) {
142 3
            return dirname($composerConfig->get('vendor-dir'));
143
        }
144
145 6
        return $composerConfig->get('vendor-dir') . '/samsonasik/package-versions';
146
    }
147
148 9
    private static function getRootPackageAlias(RootPackageInterface $rootPackage)
149
    {
150 9
        $package = $rootPackage;
151
152 9
        while ($package instanceof AliasPackage) {
153 4
            $package = $package->getAliasOf();
154
        }
155
156 9
        return $package;
157
    }
158
159
    /**
160
     * @param Locker               $locker
161
     * @param RootPackageInterface $rootPackage
162
     *
163
     * @return \Generator|\string[]
164
     */
165 9
    private static function getVersions(Locker $locker, RootPackageInterface $rootPackage)
166
    {
167 9
        $lockData = $locker->getLockData();
168
169 9
        $lockData['packages-dev'] = isset($lockData['packages-dev']) ? $lockData['packages-dev'] : [];
170
171 9
        foreach (array_merge($lockData['packages'], $lockData['packages-dev']) as $package) {
172 3
            yield $package['name'] => $package['version'] . '@' . (
173 3
                isset($package['source']['reference'])
174 2
                    ? $package['source']['reference']
175 3
                    : (isset($package['dist']['reference']) ? $package['dist']['reference'] : '')
176
            );
177
        }
178
179 9
        yield $rootPackage->getName() => $rootPackage->getVersion() . '@' . $rootPackage->getSourceReference();
180 9
    }
181
}
182