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

StdRangesCalculator::sum()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 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