NodeJsVersionMatcher::findBestMatchingVersion()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
namespace Mouf\NodeJsInstaller;
3
4
use Composer\Package\Version\VersionParser;
5
6
/**
7
 * Tries to find a match between a set of versions and constraint
8
 */
9
class NodeJsVersionMatcher
10
{
11
    /**
12
     * Return true if $version matches $constraint (expressed as a Composer constraint string)
13
     *
14
     * @param  string $version
15
     * @param  string $constraint
16
     * @return bool
17
     */
18
    public function isVersionMatching($version, $constraint)
19
    {
20
        $versionParser = new VersionParser();
21
22
        $normalizedVersion = $versionParser->normalize($version);
23
24
        $versionAsContraint = $versionParser->parseConstraints($normalizedVersion);
25
        $linkConstraint = $versionParser->parseConstraints($constraint);
26
27
        return $linkConstraint->matches($versionAsContraint);
28
    }
29
30
    /**
31
     * Finds the best version matching $constraint.
32
     * Will return null if no version matches the constraint.
33
     *
34
     * @param  array       $versionList
35
     * @param $constraint
36
     * @return string|null
37
     */
38
    public function findBestMatchingVersion(array $versionList, $constraint)
39
    {
40
        // Let's sort versions in reverse order.
41
        usort($versionList, "version_compare");
42
        $versionList = array_reverse($versionList);
43
44
        // Now, let's find the best match.
45
        foreach ($versionList as $version) {
46
            if ($this->isVersionMatching($version, $constraint)) {
47
                return $version;
48
            }
49
        }
50
51
        return;
52
    }
53
}
54