1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* Copyright (c) Nate Brunette. |
4
|
|
|
* Distributed under the MIT License (http://opensource.org/licenses/MIT) |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
declare(strict_types=1); |
8
|
|
|
|
9
|
|
|
namespace Tebru\Gson; |
10
|
|
|
|
11
|
|
|
use DateTimeInterface; |
12
|
|
|
use Tebru\Gson\Exception\JsonSyntaxException; |
13
|
|
|
use Tebru\PhpType\TypeToken; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class DateTimeTypeAdapter |
17
|
|
|
* |
18
|
|
|
* @author Nate Brunette <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class DateTimeTypeAdapter extends TypeAdapter |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var TypeToken |
24
|
|
|
*/ |
25
|
|
|
private $type; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var string |
29
|
|
|
*/ |
30
|
|
|
private $format; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Constructor |
34
|
|
|
* |
35
|
|
|
* @param TypeToken $type |
36
|
|
|
* @param string $format |
37
|
|
|
*/ |
38
|
|
|
public function __construct(TypeToken $type, string $format) |
39
|
|
|
{ |
40
|
|
|
$this->type = $type; |
41
|
|
|
$this->format = $format; |
42
|
7 |
|
} |
43
|
|
|
|
44
|
7 |
|
/** |
45
|
7 |
|
* Read the next value, convert it to its type and return it |
46
|
7 |
|
* |
47
|
|
|
* @param JsonReadable $reader |
48
|
|
|
* @return DateTimeInterface|null |
49
|
|
|
* @throws \Tebru\Gson\Exception\JsonSyntaxException If the DateTime could not be created from format |
50
|
|
|
*/ |
51
|
|
|
public function read(JsonReadable $reader): ?DateTimeInterface |
52
|
|
|
{ |
53
|
|
|
if ($reader->peek() === JsonToken::NULL) { |
54
|
|
|
$reader->nextNull(); |
55
|
4 |
|
return null; |
56
|
|
|
} |
57
|
4 |
|
|
58
|
1 |
|
$formattedDateTime = $reader->nextString(); |
59
|
1 |
|
|
60
|
|
|
$class = $this->type->getRawType(); |
61
|
|
|
|
62
|
3 |
|
/** @noinspection PhpUndefinedMethodInspection */ |
63
|
|
|
$dateTime = $class::createFromFormat($this->format, $formattedDateTime); |
64
|
3 |
|
|
65
|
|
|
if ($dateTime !== false) { |
66
|
|
|
return $dateTime; |
67
|
3 |
|
} |
68
|
|
|
|
69
|
3 |
|
throw new JsonSyntaxException(\sprintf( |
70
|
2 |
|
'Could not create "%s" class from "%s" using format "%s" at "%s"', |
71
|
|
|
$class, |
72
|
|
|
$formattedDateTime, |
73
|
1 |
|
$this->format, |
74
|
1 |
|
$reader->getPath() |
75
|
1 |
|
)); |
76
|
1 |
|
} |
77
|
1 |
|
|
78
|
1 |
|
/** |
79
|
|
|
* Write the value to the writer for the type |
80
|
|
|
* |
81
|
|
|
* @param JsonWritable $writer |
82
|
|
|
* @param DateTimeInterface $value |
83
|
|
|
* @return void |
84
|
|
|
*/ |
85
|
|
|
public function write(JsonWritable $writer, $value): void |
86
|
|
|
{ |
87
|
|
|
if (null === $value) { |
88
|
|
|
$writer->writeNull(); |
89
|
3 |
|
|
90
|
|
|
return; |
91
|
3 |
|
} |
92
|
1 |
|
|
93
|
|
|
$dateTime = $value->format($this->format); |
94
|
1 |
|
$writer->writeString($dateTime); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|