-
-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathResolvesCalendarDates.php
More file actions
99 lines (74 loc) · 2.78 KB
/
ResolvesCalendarDates.php
File metadata and controls
99 lines (74 loc) · 2.78 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Spatie\Holidays\Calendars;
use Carbon\CarbonImmutable;
use Carbon\CarbonPeriod;
use Carbon\Exceptions\InvalidFormatException;
use Spatie\Holidays\Countries\Country;
use Spatie\Holidays\Exceptions\InvalidYear;
/** @mixin Country */
trait ResolvesCalendarDates
{
/** @param array<string> $collection */
protected function getSingleDayHoliday(array $collection, int $year): CarbonImmutable
{
$date = $collection[$year] ?? null;
if ($date === null) {
throw InvalidYear::range($this->countryCode(), 1970, 2037);
}
$date = CarbonImmutable::createFromFormat('Y-m-d', "{$year}-{$date}")?->startOfDay();
if ($date === null) {
throw new InvalidFormatException('Invalid date for holiday');
}
return $date;
}
/**
* @param array<string|array<string>> $collection
* @return array<CarbonPeriod>
*/
protected function getMultiDayHoliday(array $collection, int $year, int $totalDays): array
{
$date = $collection[$year] ?? null;
if ($date === null) {
throw InvalidYear::range($this->countryCode(), 1970, 2037);
}
$overlap = $this->getOverlapping($collection, $year, $totalDays);
if ($overlap) {
$period = $this->createPeriod($overlap, $year - 1, $totalDays);
$date = [$period, $date];
}
if (! is_array($date)) {
return [$this->createPeriod($date, $year, $totalDays)];
}
$periods = [];
$dates = $date;
/** @var CarbonPeriod|string $date */
foreach ($dates as $date) {
if ($date instanceof CarbonPeriod) {
$periods[] = $date;
continue;
}
$periods[] = $this->createPeriod($date, $year, $totalDays);
}
return $periods;
}
protected function createPeriod(string $date, int $year, int $totalDays): CarbonPeriod
{
$start = CarbonImmutable::createFromFormat('Y-m-d', "{$year}-{$date}")?->startOfDay();
$end = $start->addDays($totalDays - 1)->startOfDay();
return CarbonPeriod::create($start, '1 day', $end);
}
/** @param array<string|array<string>> $collection */
protected function getOverlapping(array $collection, int $year, int $totalDays): ?string
{
if ($year === 1970) {
return null;
}
$date = $collection[$year - 1] ?? throw InvalidYear::range($this->countryCode(), 1970, 2037);
if (is_array($date)) {
$date = end($date);
}
$start = CarbonImmutable::createFromFormat('Y-m-d', "{$year}-{$date}")?->startOfDay();
$end = $start?->addDays($totalDays - 1)->startOfDay();
return ($end?->year !== $year) ? (string) $date : null;
}
}