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

PreRelease   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
c 0
b 0
f 0
lcom 0
cbo 1
dl 0
loc 46
ccs 23
cts 23
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 6 2
A compareTo() 0 20 3
B compareIdentifiers() 0 15 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