Completed
Push — master ( 560c34...fe7d37 )
by Nikola
06:26
created

SemverComparator::compare()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.2
cc 4
eloc 8
nc 4
nop 2
crap 4
1
<?php
2
3
/**
4
 * This file is part of the Version package.
5
 *
6
 * Copyright (c) Nikola Posa <[email protected]>
7
 *
8
 * For full copyright and license information, please refer to the LICENSE file,
9
 * located at the package root folder.
10
 */
11
12
namespace Version\Comparator;
13
14
use Version\Version;
15
16
/**
17
 * @author Nikola Posa <[email protected]>
18
 */
19
final class SemverComparator implements ComparatorInterface
20
{
21
    /**
22
     * {@inheritDoc}
23
     */
24 37
    public function compare(Version $version1, Version $version2)
25
    {
26 37
        if (0 != ($majorCompareResult = $this->compareNumberPart($version1->getMajor(), $version2->getMajor()))) {
27 10
            return $majorCompareResult;
28
        }
29
30 33
        if (0 != ($minorCompareResult = $this->compareNumberPart($version1->getMinor(), $version2->getMinor()))) {
31 8
            return $minorCompareResult;
32
        }
33
34 27
        if (0 != ($patchCompareResult = $this->compareNumberPart($version1->getPatch(), $version2->getPatch()))) {
35 6
            return $patchCompareResult;
36
        }
37
38 22
        return $this->compareMeta($version1, $version2);
39
    }
40
41 37
    private function compareNumberPart($number1, $number2)
42
    {
43 37
        $diff = $number1 - $number2;
44
45 37
        if ($diff > 0) {
46 13
            return 1;
47
        }
48
49 36
        if ($diff < 0) {
50 11
            return -1;
51
        }
52
53 33
        return 0;
54
    }
55
56 22
    private function compareMeta(Version $version1, Version $version2)
57
    {
58 22
        $v1IsPreRelease = $version1->isPreRelease();
59 22
        $v2IsPreRelease = $version2->isPreRelease();
60
61 22
        if ($v1IsPreRelease xor $v2IsPreRelease) {
62
            return !$v1IsPreRelease
63 3
                ? 1 // normal version has greater precedence than a pre-release version version
64 3
                : -1; // pre-release version has lower precedence than a normal version
65
        }
66
67 19
        $result = $version1->getPreRelease()->compareTo($version2->getPreRelease());
68
69 19
        if ($result > 0) {
70 7
            return 1;
71
        }
72
73 12
        if ($result < 0) {
74 1
            return -1;
75
        }
76
77 11
        return 0;
78
    }
79
}
80