Completed
Push — master ( 8e5216...cac524 )
by Nikola
10s
created

PreRelease::compareIdentifiers()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 8.8571
cc 5
eloc 8
nc 4
nop 2
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Version\Extension;
6
7
use Version\Exception\InvalidIdentifierException;
8
9
class PreRelease extends BaseExtension
10
{
11 31
    protected function validate(string $identifier) : void
12
    {
13 31
        if (! preg_match('/^[0-9A-Za-z\-]+$/', $identifier)) {
14 2
            throw InvalidIdentifierException::forExtensionIdentifier($this, $identifier);
15
        }
16 30
    }
17
18 20
    public function compareTo(PreRelease $preRelease) : int
19
    {
20 20
        $firstPreReleaseIdentifiers = array_values($this->getIdentifiers());
21 20
        $secondPreReleaseIdentifiers = array_values($preRelease->getIdentifiers());
22
23 20
        $pr1Count = count($firstPreReleaseIdentifiers);
24 20
        $pr2Count = count($secondPreReleaseIdentifiers);
25
26 20
        $limit = min($pr1Count, $pr2Count);
27
28 20
        for ($i = 0; $i < $limit; $i++) {
29 9
            if ($firstPreReleaseIdentifiers[$i] === $secondPreReleaseIdentifiers[$i]) {
30 6
                continue;
31
            }
32
33 5
            return $this->compareIdentifiers($firstPreReleaseIdentifiers[$i], $secondPreReleaseIdentifiers[$i]);
34
        }
35
36 15
        return $pr1Count - $pr2Count;
37
    }
38
39 5
    private function compareIdentifiers($identifier1, $identifier2) : int
40
    {
41 5
        $pr1IsAlpha = ctype_alpha($identifier1);
42 5
        $pr2IsAlpha = ctype_alpha($identifier2);
43
44 5
        if ($pr1IsAlpha xor $pr2IsAlpha) {
45 1
            return $pr1IsAlpha ? 1 : -1;
46
        }
47
48 4
        if (ctype_digit($identifier1) && ctype_digit($identifier2)) {
49 1
            return (int) $identifier1 - (int) $identifier2;
50
        }
51
52 3
        return strcmp($identifier1, $identifier2);
53
    }
54
}
55