1: | <?php declare(strict_types=1); |
2: | |
3: | namespace Salient\Core\Date; |
4: | |
5: | use Salient\Contract\Core\DateFormatterInterface; |
6: | use Salient\Contract\Core\DateParserInterface; |
7: | use Salient\Utility\Date; |
8: | use DateTime; |
9: | use DateTimeImmutable; |
10: | use DateTimeInterface; |
11: | use DateTimeZone; |
12: | |
13: | |
14: | |
15: | |
16: | final class DateFormatter implements DateFormatterInterface |
17: | { |
18: | private string $Format; |
19: | private ?DateTimeZone $Timezone; |
20: | |
21: | private array $Parsers; |
22: | private string $TimezoneName; |
23: | |
24: | |
25: | |
26: | |
27: | |
28: | |
29: | |
30: | |
31: | |
32: | |
33: | |
34: | |
35: | |
36: | |
37: | public function __construct( |
38: | string $format = DateTimeInterface::ATOM, |
39: | $timezone = null, |
40: | DateParserInterface ...$parsers |
41: | ) { |
42: | $this->Format = $format; |
43: | $this->Timezone = is_string($timezone) |
44: | ? new DateTimeZone($timezone) |
45: | : $timezone; |
46: | $this->Parsers = $parsers |
47: | ? $parsers |
48: | : [new DateFormatParser($format)]; |
49: | |
50: | if ($this->Timezone) { |
51: | $this->TimezoneName = $this->Timezone->getName(); |
52: | } |
53: | } |
54: | |
55: | |
56: | |
57: | |
58: | public function format(DateTimeInterface $date): string |
59: | { |
60: | if ( |
61: | $this->Timezone |
62: | && $this->TimezoneName !== $date->getTimezone()->getName() |
63: | ) { |
64: | $date = Date::immutable($date)->setTimezone($this->Timezone); |
65: | } |
66: | return $date->format($this->Format); |
67: | } |
68: | |
69: | |
70: | |
71: | |
72: | public function parse(string $value, ?DateTimeZone $timezone = null): ?DateTimeImmutable |
73: | { |
74: | $timezone ??= $this->Timezone; |
75: | foreach ($this->Parsers as $parser) { |
76: | if ($date = $parser->parse($value, $timezone)) { |
77: | return $date; |
78: | } |
79: | } |
80: | return null; |
81: | } |
82: | } |
83: | |