1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace CCT\Kong\Serializer\Handler; |
6
|
|
|
|
7
|
|
|
use JMS\Serializer\Context; |
8
|
|
|
use JMS\Serializer\Handler\SubscribingHandlerInterface; |
9
|
|
|
use JMS\Serializer\GraphNavigator; |
10
|
|
|
use JMS\Serializer\JsonDeserializationVisitor; |
11
|
|
|
use JMS\Serializer\JsonSerializationVisitor; |
12
|
|
|
|
13
|
|
|
class TimestampDatetimeHandler implements SubscribingHandlerInterface |
14
|
|
|
{ |
15
|
|
|
protected $timezone; |
16
|
|
|
|
17
|
47 |
|
public function __construct(\DateTimeZone $timezone = null) |
18
|
|
|
{ |
19
|
47 |
|
if (null === $timezone) { |
20
|
47 |
|
$timezone = new \DateTimeZone('UTC'); |
21
|
|
|
} |
22
|
|
|
|
23
|
47 |
|
$this->timezone = $timezone; |
24
|
47 |
|
} |
25
|
|
|
|
26
|
42 |
|
public static function getSubscribingMethods() |
27
|
|
|
{ |
28
|
|
|
return [ |
29
|
|
|
[ |
30
|
42 |
|
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION, |
31
|
42 |
|
'format' => 'json', |
32
|
42 |
|
'type' => 'DateTime', |
33
|
42 |
|
'method' => 'deserializeTimestampToJson', |
34
|
|
|
], |
35
|
|
|
[ |
36
|
42 |
|
'direction' => GraphNavigator::DIRECTION_SERIALIZATION, |
37
|
42 |
|
'format' => 'json', |
38
|
42 |
|
'type' => 'DateTime', |
39
|
42 |
|
'method' => 'serializeTimestampToJson', |
40
|
|
|
], |
41
|
|
|
]; |
42
|
|
|
} |
43
|
|
|
|
44
|
24 |
|
public function deserializeTimestampToJson(JsonDeserializationVisitor $visitor, $data, $type) :? \DateTime |
|
|
|
|
45
|
|
|
{ |
46
|
24 |
|
if (empty($data) || 13 !== strlen((string) $data)) { |
47
|
1 |
|
return null; |
48
|
|
|
} |
49
|
|
|
|
50
|
23 |
|
return $this->convertToDateTime((string) $data); |
51
|
|
|
} |
52
|
|
|
|
53
|
3 |
|
public function serializeTimestampToJson( |
54
|
|
|
JsonSerializationVisitor $visitor, |
55
|
|
|
\DateTime $date, |
56
|
|
|
array $type, |
57
|
|
|
Context $context |
58
|
|
|
): int { |
59
|
3 |
|
$time = (int) substr($date->format('Uu'), 0, 13); |
60
|
|
|
|
61
|
3 |
|
return $visitor->visitInteger($time, $type, $context); |
62
|
|
|
} |
63
|
|
|
|
64
|
23 |
|
protected function convertToDateTime(string $data) |
65
|
|
|
{ |
66
|
23 |
|
$datetime = \DateTime::createFromFormat( |
67
|
23 |
|
'U.u', |
68
|
23 |
|
$this->normalizeKongDateFormat($data), |
69
|
23 |
|
$this->timezone |
70
|
|
|
); |
71
|
|
|
|
72
|
23 |
|
if (false === $datetime) { |
73
|
|
|
throw new \RuntimeException("It was not possible to convert the Kong's date to PHP \DateTime"); |
74
|
|
|
} |
75
|
|
|
|
76
|
23 |
|
return $datetime; |
77
|
|
|
} |
78
|
|
|
|
79
|
23 |
|
protected function normalizeKongDateFormat(string $data) |
80
|
|
|
{ |
81
|
23 |
|
return sprintf( |
82
|
23 |
|
'%s.%s', |
83
|
23 |
|
substr($data, 0, 10), |
84
|
23 |
|
round((int) substr($data, -3, 3)) |
85
|
|
|
); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.