Completed
Push — master ( c5181d...c8e170 )
by Nikola
01:19
created

PreRelease::empty()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 4
cts 5
cp 0.8
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.032
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Version\Extension;
6
7
use Version\Assert\VersionAssert;
8
9
class PreRelease extends Extension
10
{
11 29
    protected function validate(string $identifier): void
12
    {
13 29
        VersionAssert::that($identifier)->regex(
14 29
            '/^[0-9A-Za-z\-]+$/',
15 29
            'Pre-release version is not valid; identifiers must include only alphanumerics and hyphen'
16
        );
17 28
    }
18
19 21
    public function compareTo(PreRelease $preRelease): int
20
    {
21 21
        $preRelease1Ids = array_values($this->getIdentifiers());
22 21
        $preRelease2Ids = array_values($preRelease->getIdentifiers());
23
24 21
        $preRelease1IdsCount = count($preRelease1Ids);
25 21
        $preRelease2IdsCount = count($preRelease2Ids);
26
27 21
        $limit = min($preRelease1IdsCount, $preRelease2IdsCount);
28
29 21
        for ($i = 0; $i < $limit; $i++) {
30 10
            if ($preRelease1Ids[$i] === $preRelease2Ids[$i]) {
31 5
                continue;
32
            }
33
34 7
            return $this->compareIdentifiers($preRelease1Ids[$i], $preRelease2Ids[$i]);
35
        }
36
37 14
        return $preRelease1IdsCount - $preRelease2IdsCount;
38
    }
39
40 7
    private function compareIdentifiers($identifier1, $identifier2): int
41
    {
42 7
        $identifier1IsNumber = ctype_digit($identifier1);
43 7
        $identifier2IsNumber = ctype_digit($identifier2);
44
45 7
        if ($identifier1IsNumber xor $identifier2IsNumber) {
46 1
            return $identifier1IsNumber ? -1 : 1;
47
        }
48
49 6
        if ($identifier1IsNumber && $identifier2IsNumber) {
50 2
            return (int) $identifier1 - (int) $identifier2;
51
        }
52
53 4
        return strcmp($identifier1, $identifier2);
54
    }
55
}
56