1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Kata\Algorithm; |
6
|
|
|
|
7
|
|
|
final class Finder |
8
|
|
|
{ |
9
|
|
|
/** @var User[] */ |
10
|
|
|
private $users; |
11
|
|
|
|
12
|
6 |
|
public function __construct(array $users) |
13
|
|
|
{ |
14
|
6 |
|
$this->users = $users; |
15
|
6 |
|
} |
16
|
|
|
|
17
|
6 |
|
public function find(int $orderMode): UsersBirthDateDifference |
18
|
|
|
{ |
19
|
|
|
/** @var UsersBirthDateDifference[] $usersBirthDateDifferenceList */ |
20
|
6 |
|
$usersBirthDateDifferenceList = []; |
21
|
6 |
|
$totalUsers = count($this->users); |
22
|
|
|
|
23
|
6 |
|
foreach ($this->users as $i => $user) { |
24
|
5 |
|
for ($j = $i + 1; $j < $totalUsers; $j++) { |
25
|
4 |
|
$usersBirthDateDifference = new UsersBirthDateDifference(); |
26
|
|
|
|
27
|
4 |
|
if ($user->birthDate < $this->users[$j]->birthDate) { |
28
|
3 |
|
$usersBirthDateDifference->youngerUser = $user; |
29
|
3 |
|
$usersBirthDateDifference->olderUser = $this->users[$j]; |
30
|
|
|
} else { |
31
|
3 |
|
$usersBirthDateDifference->youngerUser = $this->users[$j]; |
32
|
3 |
|
$usersBirthDateDifference->olderUser = $user; |
33
|
|
|
} |
34
|
|
|
|
35
|
4 |
|
$usersBirthDateDifference->dateDifference = $usersBirthDateDifference->olderUser->birthDate->getTimestamp() |
36
|
4 |
|
- $usersBirthDateDifference->youngerUser->birthDate->getTimestamp(); |
37
|
|
|
|
38
|
4 |
|
$usersBirthDateDifferenceList[] = $usersBirthDateDifference; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
6 |
|
if (count($usersBirthDateDifferenceList) < 1) { |
43
|
2 |
|
return new UsersBirthDateDifference(); |
44
|
|
|
} |
45
|
|
|
|
46
|
4 |
|
return $this->orderByAgeDifference($orderMode, $usersBirthDateDifferenceList); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* |
51
|
|
|
* |
52
|
|
|
* @param int $orderMode |
53
|
|
|
* @param UsersBirthDateDifference[] $usersBirthDateDifferenceList |
54
|
|
|
* @return UsersBirthDateDifference |
55
|
|
|
*/ |
56
|
4 |
|
private function orderByAgeDifference(int $orderMode, array $usersBirthDateDifferenceList): UsersBirthDateDifference |
57
|
|
|
{ |
58
|
|
|
usort($usersBirthDateDifferenceList, function(UsersBirthDateDifference $firstElement, UsersBirthDateDifference $secondElement) use ($orderMode) { |
59
|
2 |
|
if (BirthDateDifference::SHORTEST === $orderMode) { |
60
|
1 |
|
return $firstElement->dateDifference <=> $secondElement->dateDifference; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
return $secondElement->dateDifference <=> $firstElement->dateDifference; |
64
|
4 |
|
}); |
65
|
|
|
|
66
|
4 |
|
return current($usersBirthDateDifferenceList); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|