forked from spatie/period
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeriodDuration.php
63 lines (49 loc) · 1.92 KB
/
PeriodDuration.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
declare(strict_types=1);
namespace Spatie\Period;
use DateTimeImmutable;
class PeriodDuration
{
public function __construct(
private Period $period
) {
}
public function equals(PeriodDuration $other): bool
{
return $this->startAndEndDatesAreTheSameAs($other)
|| $this->includedStartAndEndDatesAreTheSameAs($other)
|| $this->numberOfDaysIsTheSameAs($other)
|| $this->compareTo($other) === 0;
}
public function isLargerThan(PeriodDuration $other): bool
{
return $this->compareTo($other) === 1;
}
public function isSmallerThan(PeriodDuration $other): bool
{
return $this->compareTo($other) === -1;
}
public function compareTo(PeriodDuration $other): int
{
$now = new DateTimeImmutable('@' . time()); // Ensure a TimeZone independent instance
$here = $this->period->includedEnd()->diff($this->period->includedStart(), true);
$there = $other->period->includedEnd()->diff($other->period->includedStart(), true);
return $now->add($here)->getTimestamp() <=> $now->add($there)->getTimestamp();
}
private function startAndEndDatesAreTheSameAs(PeriodDuration $other): bool
{
return $this->period->start() == $other->period->start()
&& $this->period->end() == $other->period->end();
}
private function includedStartAndEndDatesAreTheSameAs(PeriodDuration $other): bool
{
return $this->period->includedStart() == $other->period->includedStart()
&& $this->period->includedEnd() == $other->period->includedEnd();
}
private function numberOfDaysIsTheSameAs(PeriodDuration $other)
{
$here = $this->period->includedEnd()->diff($this->period->includedStart(), true);
$there = $other->period->includedEnd()->diff($other->period->includedStart(), true);
return $here->format('%a') === $there->format('%a');
}
}