Passed
Push — master ( 3f7870...ee79c5 )
by Tomasz
01:36
created

StdRangesCalculator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 92.31%

Importance

Changes 0
Metric Value
wmc 11
lcom 0
cbo 1
dl 0
loc 60
ccs 24
cts 26
cp 0.9231
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A sortRanges() 0 6 1
A sub() 0 3 1
B mergeRanges() 0 23 7
A sum() 0 9 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Hop\Ranges;
6
7
final class StdRangesCalculator implements RangesCalculator
8
{
9
    /**
10
     * @inheritdoc
11
     */
12 4
    public function sum(Range ...$ranges): array
13
    {
14 4
        if (\count($ranges) === 0) {
15 1
            return [];
16
        }
17
18 3
        $this->sortRanges($ranges);
19 3
        return $this->mergeRanges($ranges);
20
    }
21
22
    /**
23
     * @param Range[] $ranges
24
     */
25
    private function sortRanges(array &$ranges): void
26
    {
27 3
        \usort($ranges, function (Range $range1, Range $range2): int {
28 3
            return $range1->dateFrom() <=> $range2->dateFrom();
29 3
        });
30 3
    }
31
32
    /**
33
     * @inheritdoc
34
     */
35
    public function sub(Range $minuend, Range ...$subtrahends): array
36
    {
37
    }
38
39
    /**
40
     * @param Range[] $ranges
41
     * @return array
42
     */
43 3
    private function mergeRanges(array $ranges): array
44
    {
45 3
        $result = [];
46 3
        $startRange = null;
47 3
        $endRange = null;
48 3
        foreach ($ranges as $key => $range) {
49 3
            $nextRange = @$ranges[$key + 1];
50 3
            if ($startRange === null) {
51 3
                $startRange = $range->dateFrom();
52
            }
53
54 3
            if ($endRange === null || $range->dateTo() > $endRange) {
55 3
                $endRange = $range->dateTo();
56
            }
57
58 3
            if ($nextRange == null || $nextRange->dateFrom() > $range->dateTo()) {
59 3
                $result[] = new Range($startRange, $endRange);
60 3
                $startRange = null;
61 3
                $endRange = null;
62
            }
63
        }
64 3
        return $result;
65
    }
66
}
67