NodeJsVersionMatcher   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 0
loc 45
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isVersionMatching() 0 11 1
A findBestMatchingVersion() 0 15 3
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