1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright Andreas Heigl <[email protected]> |
5
|
|
|
* |
6
|
|
|
* Licenses under the MIT-license. For details see the included file LICENSE.md |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
declare(strict_types=1); |
10
|
|
|
|
11
|
|
|
namespace Org_Heigl\Holidaychecker\Factory; |
12
|
|
|
|
13
|
|
|
use DOMElement; |
14
|
|
|
use Org_Heigl\Holidaychecker\CalendarDayFactory; |
15
|
|
|
use Org_Heigl\Holidaychecker\GregorianWeekday; |
16
|
|
|
use Org_Heigl\Holidaychecker\HolidayIteratorItemInterface; |
17
|
|
|
use Org_Heigl\Holidaychecker\IteratorItem\SwapDecorator; |
18
|
|
|
use Org_Heigl\Holidaychecker\SwapDirection; |
19
|
|
|
use Org_Heigl\Holidaychecker\SwapRule; |
20
|
|
|
use function array_map; |
21
|
|
|
use function explode; |
22
|
|
|
|
23
|
|
|
final class SwapDecoratorFactory implements DecorateFromDomElement |
24
|
|
|
{ |
25
|
|
|
public function decorate(HolidayIteratorItemInterface $element, DOMElement $domElement): HolidayIteratorItemInterface |
26
|
|
|
{ |
27
|
|
|
$rules = $this->getRulesFromDomElement($domElement); |
28
|
|
|
|
29
|
|
|
if ($rules === []) { |
30
|
|
|
return $element; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$day = CalendarDayFactory::createCalendarDay( |
34
|
|
|
(int) $domElement->getAttribute('day'), |
35
|
|
|
(int) $domElement->getAttribute('month'), |
36
|
|
|
($domElement->hasAttribute('calendar') ? $domElement->getAttribute('calendar') : 'gregorian') |
37
|
|
|
); |
38
|
|
|
|
39
|
|
|
if ($domElement->hasAttribute('year')) { |
40
|
|
|
$day->setYear((int) $domElement->getAttribute('year')); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return new SwapDecorator($element, $day, ...$rules); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @return SwapRule[] |
48
|
|
|
*/ |
49
|
|
|
private function getRulesFromDomElement(DOMElement $domElement): array |
50
|
|
|
{ |
51
|
|
|
$attributes = [ |
52
|
|
|
'forward' => SwapDirection::forward(), |
53
|
|
|
'alternateforward' => SwapDirection::forward(), |
54
|
|
|
'rewind' => SwapDirection::rewind(), |
55
|
|
|
'alternaterewind' => SwapDirection::rewind(), |
56
|
|
|
]; |
57
|
|
|
|
58
|
|
|
$rules = []; |
59
|
|
|
foreach ($attributes as $attribute => $direction) { |
60
|
|
|
if ($domElement->hasAttribute($attribute . 'to') && $domElement->hasAttribute($attribute . 'when')) { |
61
|
|
|
$rules[] = $this->createRuleFrom($domElement->getAttribute($attribute . 'to'), $domElement->getAttribute($attribute . 'when'), $direction); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $rules; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function createRuleFrom(string $to, string $when, SwapDirection $direction): SwapRule |
69
|
|
|
{ |
70
|
|
|
return new SwapRule( |
71
|
|
|
$direction, |
72
|
|
|
GregorianWeekday::fromString($to), |
73
|
|
|
...array_map(function ($item) { |
74
|
|
|
return GregorianWeekday::fromString($item); |
75
|
|
|
}, explode(' ', $when)) |
76
|
|
|
); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|