1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Stadly\Date; |
6
|
|
|
|
7
|
|
|
use DateInterval; |
8
|
|
|
|
9
|
|
|
final class Interval |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param DateInterval $a First date interval to compare. |
13
|
|
|
* @param DateInterval $b Second date interval to compare. |
14
|
|
|
* @return int|null 0 if $a == $b, < 0 if $a < b, > 0 if $a > $b, null if undetermined. |
15
|
|
|
*/ |
16
|
44 |
|
public static function compare(DateInterval $a, DateInterval $b): ?int |
17
|
|
|
{ |
18
|
44 |
|
$aSeconds = self::getSecondsInInterval($a); |
19
|
44 |
|
$aMonths = self::getMonthsInInterval($a); |
20
|
44 |
|
$bSeconds = self::getSecondsInInterval($b); |
21
|
44 |
|
$bMonths = self::getMonthsInInterval($b); |
22
|
|
|
|
23
|
44 |
|
$minSecondsPerMonth = 28 * 24 * 60 * 60; |
24
|
44 |
|
$maxSecondsPerMonth = 31 * 24 * 60 * 60; |
25
|
|
|
|
26
|
44 |
|
if ($aSeconds === $bSeconds || $aMonths === $bMonths) { |
27
|
28 |
|
return $aSeconds + $aMonths <=> $bSeconds + $bMonths; |
28
|
|
|
} |
29
|
|
|
|
30
|
16 |
|
if ($aSeconds + $maxSecondsPerMonth * $aMonths < $bSeconds + $minSecondsPerMonth * $bMonths) { |
31
|
4 |
|
return -1; |
32
|
|
|
} |
33
|
|
|
|
34
|
12 |
|
if ($bSeconds + $maxSecondsPerMonth * $bMonths < $aSeconds + $minSecondsPerMonth * $aMonths) { |
35
|
4 |
|
return 1; |
36
|
|
|
} |
37
|
|
|
|
38
|
8 |
|
return null; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param DateInterval $interval Date interval. |
43
|
|
|
* @return int Number of months in the date interval. |
44
|
|
|
*/ |
45
|
44 |
|
private static function getMonthsInInterval(DateInterval $interval): int |
46
|
|
|
{ |
47
|
44 |
|
$years = $interval->y; |
48
|
44 |
|
$months = $years * 12 + $interval->m; |
49
|
|
|
|
50
|
44 |
|
if ($interval->invert === 1) { |
51
|
15 |
|
return -$months; |
52
|
|
|
} |
53
|
|
|
|
54
|
31 |
|
return $months; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param DateInterval $interval Date interval. |
59
|
|
|
* @return float Number of seconds in the date interval. |
60
|
|
|
*/ |
61
|
44 |
|
private static function getSecondsInInterval(DateInterval $interval): float |
62
|
|
|
{ |
63
|
44 |
|
$days = $interval->d; |
64
|
44 |
|
$hours = $days * 24 + $interval->h; |
65
|
44 |
|
$minutes = $hours * 60 + $interval->i; |
66
|
44 |
|
$seconds = $minutes * 60 + $interval->s + $interval->f; |
67
|
|
|
|
68
|
44 |
|
if ($interval->invert === 1) { |
69
|
15 |
|
return -$seconds; |
70
|
|
|
} |
71
|
|
|
|
72
|
31 |
|
return $seconds; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|