Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
96.30% |
26 / 27 |
|
85.71% |
6 / 7 |
CRAP | |
0.00% |
0 / 1 |
| DateTime | |
96.30% |
26 / 27 |
|
85.71% |
6 / 7 |
14 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
5 | |||
| __toString | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| isset | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| unwrap | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| format | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| localize | |
88.89% |
8 / 9 |
|
0.00% |
0 / 1 |
2.01 | |||
| json | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Value; |
| 6 | |
| 7 | use Cosray\Field\Field; |
| 8 | use Cosray\Field\Owner; |
| 9 | use DateTimeImmutable; |
| 10 | use DateTimeZone; |
| 11 | use IntlDateFormatter; |
| 12 | |
| 13 | class DateTime extends Value |
| 14 | { |
| 15 | public const FORMAT = 'Y-m-d H:i:s'; |
| 16 | |
| 17 | public readonly ?DateTimeImmutable $datetime; |
| 18 | public readonly ?DateTimeZone $timezone; |
| 19 | |
| 20 | public function __construct(Owner $owner, Field $field, ValueContext $context) |
| 21 | { |
| 22 | parent::__construct($owner, $field, $context); |
| 23 | |
| 24 | $timezone = $this->meta('timezone'); |
| 25 | $this->timezone = is_string($timezone) && $timezone !== '' ? new DateTimeZone($timezone) : null; |
| 26 | |
| 27 | $value = $this->value(); |
| 28 | |
| 29 | if (is_string($value) && $value !== '') { |
| 30 | $this->datetime = DateTimeImmutable::createFromFormat( |
| 31 | static::FORMAT, |
| 32 | $value, |
| 33 | $this->timezone, |
| 34 | ); |
| 35 | } else { |
| 36 | $this->datetime = null; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | public function __toString(): string |
| 41 | { |
| 42 | return $this->format(static::FORMAT); |
| 43 | } |
| 44 | |
| 45 | public function isset(): bool |
| 46 | { |
| 47 | return isset($this->datetime) ? true : false; |
| 48 | } |
| 49 | |
| 50 | public function unwrap(): ?DateTimeImmutable |
| 51 | { |
| 52 | return $this->datetime; |
| 53 | } |
| 54 | |
| 55 | public function format(string $format): string |
| 56 | { |
| 57 | if ($this->datetime) { |
| 58 | return $this->datetime->format($format); |
| 59 | } |
| 60 | |
| 61 | return ''; |
| 62 | } |
| 63 | |
| 64 | public function localize( |
| 65 | int $dateFormat = IntlDateFormatter::MEDIUM, |
| 66 | int $timeFormat = IntlDateFormatter::MEDIUM, |
| 67 | ): string { |
| 68 | if ($this->datetime) { |
| 69 | $formatter = new IntlDateFormatter( |
| 70 | $this->locale->id, |
| 71 | $dateFormat, |
| 72 | $timeFormat, |
| 73 | $this->timezone, |
| 74 | ); |
| 75 | |
| 76 | return $formatter->format($this->datetime->getTimestamp()); |
| 77 | } |
| 78 | |
| 79 | return ''; |
| 80 | } |
| 81 | |
| 82 | public function json(): mixed |
| 83 | { |
| 84 | return $this->__toString(); |
| 85 | } |
| 86 | } |