|
1
|
|
|
<?php declare(strict_types = 1); |
|
2
|
|
|
/* |
|
3
|
|
|
* This file is part of the KleijnWeb\PhpApi\Hydrator package. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
namespace KleijnWeb\PhpApi\Hydrator; |
|
9
|
|
|
|
|
10
|
|
|
use KleijnWeb\PhpApi\Descriptions\Description\Schema\ScalarSchema; |
|
11
|
|
|
use KleijnWeb\PhpApi\Descriptions\Description\Schema\Schema; |
|
12
|
|
|
use KleijnWeb\PhpApi\Hydrator\Exception\DateTimeNotParsableException; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @author John Kleijn <[email protected]> |
|
16
|
|
|
*/ |
|
17
|
|
|
class DateTimeSerializer |
|
18
|
|
|
{ |
|
19
|
|
|
const DEFAULT_FORMAT = 'Y-m-d\TH:i:s.uP'; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var string |
|
23
|
|
|
*/ |
|
24
|
|
|
private $format; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* DateTimeSerializer constructor. |
|
28
|
|
|
* |
|
29
|
|
|
* @param string $format |
|
30
|
|
|
*/ |
|
31
|
|
|
public function __construct(string $format = null) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->format = $format; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @param \DateTimeInterface $value |
|
38
|
|
|
* @param Schema $schema |
|
39
|
|
|
* |
|
40
|
|
|
* @return string |
|
41
|
|
|
*/ |
|
42
|
|
|
public function serialize(\DateTimeInterface $value, Schema $schema): string |
|
43
|
|
|
{ |
|
44
|
|
|
if ($schema instanceof ScalarSchema && $schema->hasFormat(Schema::FORMAT_DATE)) { |
|
45
|
|
|
return $value->format('Y-m-d'); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $value->format($this->format ?: self::DEFAULT_FORMAT); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param mixed $value |
|
53
|
|
|
* @param Schema $schema |
|
54
|
|
|
* |
|
55
|
|
|
* @return \DateTime |
|
56
|
|
|
* |
|
57
|
|
|
*/ |
|
58
|
|
|
public function deserialize($value, Schema $schema): \DateTime |
|
59
|
|
|
{ |
|
60
|
|
|
if ($schema instanceof ScalarSchema) { |
|
61
|
|
|
if ($this->format) { |
|
62
|
|
|
if (false === $result = \DateTime::createFromFormat($this->format, $value)) { |
|
63
|
|
|
throw new DateTimeNotParsableException( |
|
64
|
|
|
sprintf("Date '%s' not parsable as '%s'", $value, $this->format) |
|
65
|
|
|
); |
|
66
|
|
|
} |
|
67
|
|
|
return $result; |
|
68
|
|
|
} |
|
69
|
|
|
if ($schema->hasFormat(Schema::FORMAT_DATE)) { |
|
70
|
|
|
return new \DateTime("{$value} 00:00:00"); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
return new \DateTime($value); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|