1 | <?php |
||
2 | |||
3 | namespace Ipag\Sdk\Model\Schema; |
||
4 | |||
5 | use DateTimeInterface; |
||
6 | use Ipag\Sdk\Model\Schema\Exception\SchemaAttributeParseException; |
||
7 | use Ipag\Sdk\Util\DateUtil; |
||
8 | |||
9 | /** |
||
10 | * @codeCoverageIgnore |
||
11 | */ |
||
12 | class SchemaDateAttribute extends SchemaAttribute |
||
13 | { |
||
14 | protected string $format; |
||
15 | |||
16 | public function __construct(Schema $schema, string $name, string $format = DateTimeInterface::RFC3339) |
||
17 | { |
||
18 | parent::__construct($schema, $name); |
||
19 | $this->format = $format; |
||
20 | } |
||
21 | |||
22 | // |
||
23 | |||
24 | public function getFormat(): string |
||
25 | { |
||
26 | return $this->format; |
||
27 | } |
||
28 | |||
29 | public function format(string $format): self |
||
30 | { |
||
31 | $this->format = $format; |
||
32 | return $this; |
||
33 | } |
||
34 | |||
35 | // |
||
36 | |||
37 | public function parseContextual($value) |
||
38 | { |
||
39 | if (is_string($value) && $this->format) { |
||
40 | $value = DateUtil::tryParseDate($value, $this->format); |
||
41 | } |
||
42 | |||
43 | if (!$value instanceof DateTimeInterface) { |
||
44 | throw new SchemaAttributeParseException($this, "Provided value is not a valid date"); |
||
45 | } |
||
46 | |||
47 | return $value; |
||
48 | } |
||
49 | |||
50 | public function serialize($value) |
||
51 | { |
||
52 | if (is_null($value)) { |
||
53 | return $value; |
||
54 | } |
||
55 | |||
56 | if ($this->getFormat()) { |
||
57 | return $value->format($this->getFormat()); |
||
58 | } |
||
59 | |||
60 | return $value; |
||
61 | } |
||
62 | |||
63 | public static function from(Schema $schema, string $name): self |
||
64 | { |
||
65 | return parent::from($schema, $name); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
66 | } |
||
67 | } |