Completed
Push — IncomprehensibleFinder/Edu-Chr... ( 0d3d24...6fe578 )
by Eduard
03:21
created

Finder::find()   B

Complexity

Conditions 9
Paths 21

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9.0117

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 18
cts 19
cp 0.9474
rs 8.0555
c 0
b 0
f 0
cc 9
nc 21
nop 1
crap 9.0117
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Kata\Algorithm;
6
7
use function count;
8
9
final class Finder
10
{
11
    /** @var Person[] */
12
    private $people;
13
14 6
    public function __construct(array $some_people)
15
    {
16 6
        $this->people = $some_people;
17 6
    }
18
19 6
    public function find(int $criteria): AgeComparatorResult
20
    {
21
        /** @var AgeComparatorResult[] $results */
22 6
        $results = [];
23 6
        $number_of_people = count($this->people);
24
25 6
        foreach ($this->people as $index => $person) {
26 5
            for ($j = $index + 1; $j < $number_of_people; $j++) {
27 4
                $results[] = $this->compareTwoBirthDates($person, $j);
28
            }
29
        }
30
31 6
        if (count($results) < 1) {
32 2
            throw new \InvalidArgumentException('Add at least two people');
33
        }
34
35 4
        $answer = $results[0];
36
37 4
        foreach ($results as $result) {
38
            switch ($criteria) {
39 4
                case Criteria::CLOSEST:
40 2
                    if ($result->age_difference < $answer->age_difference) {
41 1
                        $answer = $result;
42
                    }
43 2
                    break;
44
45 2
                case Criteria::FURTHEST:
46 2
                    if ($result->age_difference > $answer->age_difference) {
47
                        $answer = $result;
48
                    }
49 2
                    break;
50
            }
51
        }
52
53 4
        return $answer;
54
    }
55
56 4
    private function compareTwoBirthDates(
57
        Person $person,
58
        int $j
59
    ): AgeComparatorResult{
60 4
        if ($person->birthDate() < $this->people[$j]->birthDate()) {
61 3
            return new AgeComparatorResult($person, $this->people[$j]);
62
        }
63
64 3
        return new AgeComparatorResult($this->people[$j], $person);
65
    }
66
}
67