|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Version\Comparison; |
|
6
|
|
|
|
|
7
|
|
|
use Version\Extension\PreRelease; |
|
8
|
|
|
use Version\Version; |
|
9
|
|
|
|
|
10
|
|
|
final class SemverComparator implements Comparator |
|
11
|
|
|
{ |
|
12
|
36 |
|
public function compare(Version $version1, Version $version2): int |
|
13
|
|
|
{ |
|
14
|
36 |
|
if (0 !== ($numberComparisonResult = $this->compareNumbers($version1, $version2))) { |
|
15
|
17 |
|
return $numberComparisonResult; |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
23 |
|
if ($version1->isPreRelease() && $version2->isPreRelease()) { |
|
19
|
10 |
|
return $this->comparePreReleases($version1->getPreRelease(), $version2->getPreRelease()); |
|
|
|
|
|
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
13 |
|
return $this->resolvePreReleasePrecedence($version1, $version2); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
36 |
|
private function compareNumbers(Version $version1, Version $version2): int |
|
26
|
|
|
{ |
|
27
|
36 |
|
return [$version1->getMajor(), $version1->getMinor(), $version1->getPatch()] <=> [$version2->getMajor(), $version2->getMinor(), $version2->getPatch()]; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
10 |
|
private function comparePreReleases(PreRelease $preRelease1, PreRelease $preRelease2): int |
|
31
|
|
|
{ |
|
32
|
10 |
|
$preRelease1Ids = $preRelease1->getIdentifiers(); |
|
33
|
10 |
|
$preRelease2Ids = $preRelease2->getIdentifiers(); |
|
34
|
|
|
|
|
35
|
10 |
|
$preRelease1IdsCount = count($preRelease1Ids); |
|
36
|
10 |
|
$preRelease2IdsCount = count($preRelease2Ids); |
|
37
|
|
|
|
|
38
|
10 |
|
$limit = min($preRelease1IdsCount, $preRelease2IdsCount); |
|
39
|
|
|
|
|
40
|
10 |
|
for ($i = 0; $i < $limit; $i++) { |
|
41
|
10 |
|
if ($preRelease1Ids[$i] === $preRelease2Ids[$i]) { |
|
42
|
5 |
|
continue; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
7 |
|
return $preRelease1Ids[$i] <=> $preRelease2Ids[$i]; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
3 |
|
return $preRelease1IdsCount - $preRelease2IdsCount; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
13 |
|
private function resolvePreReleasePrecedence(Version $version1, Version $version2): int |
|
52
|
|
|
{ |
|
53
|
|
|
//pre-release version has lower precedence than a normal version |
|
54
|
13 |
|
return -1 * ($version1->isPreRelease() <=> $version2->isPreRelease()); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: