1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace App\Bundle\Example\Service; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Import classes |
7
|
|
|
*/ |
8
|
|
|
use App\Bundle\Example\Entity\Entry; |
9
|
|
|
use DateTime; |
10
|
|
|
use DateTimeInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* EntrySerializer |
14
|
|
|
*/ |
15
|
|
|
final class EntrySerializer |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @OpenApi\Schema( |
20
|
|
|
* refName="Entry", |
21
|
|
|
* type="object", |
22
|
|
|
* properties={ |
23
|
|
|
* "id": @OpenApi\Schema( |
24
|
|
|
* type="string", |
25
|
|
|
* format="uuid", |
26
|
|
|
* nullable=false, |
27
|
|
|
* ), |
28
|
|
|
* "name": @OpenApi\SchemaReference( |
29
|
|
|
* class="App\Bundle\Example\Entity\Entry", |
30
|
|
|
* property="name", |
31
|
|
|
* ), |
32
|
|
|
* "slug": @OpenApi\SchemaReference( |
33
|
|
|
* class="App\Bundle\Example\Entity\Entry", |
34
|
|
|
* property="slug", |
35
|
|
|
* ), |
36
|
|
|
* "createdAt": @OpenApi\Schema( |
37
|
|
|
* type="string", |
38
|
|
|
* format="date-time", |
39
|
|
|
* nullable=false, |
40
|
|
|
* ), |
41
|
|
|
* "updatedAt": @OpenApi\Schema( |
42
|
|
|
* type="string", |
43
|
|
|
* format="date-time", |
44
|
|
|
* nullable=true, |
45
|
|
|
* ), |
46
|
|
|
* }, |
47
|
|
|
* ) |
48
|
|
|
* |
49
|
|
|
* @param Entry $entry |
50
|
|
|
* |
51
|
|
|
* @return array |
52
|
|
|
*/ |
53
|
8 |
|
public function serialize(Entry $entry) : array |
54
|
|
|
{ |
55
|
|
|
return [ |
56
|
8 |
|
'id' => (string) $entry->getId(), |
57
|
8 |
|
'name' => $entry->getName(), |
58
|
8 |
|
'slug' => $entry->getSlug(), |
59
|
8 |
|
'createdAt' => $this->dateTimeSerialize($entry->getCreatedAt()), |
60
|
8 |
|
'updatedAt' => $this->dateTimeSerialize($entry->getUpdatedAt()), |
61
|
|
|
]; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @OpenApi\Schema( |
66
|
|
|
* refName="EntryList", |
67
|
|
|
* type="array", |
68
|
|
|
* items=@OpenApi\SchemaReference( |
69
|
|
|
* class="App\Bundle\Example\Service\EntrySerializer", |
70
|
|
|
* method="serialize", |
71
|
|
|
* ), |
72
|
|
|
* ) |
73
|
|
|
* |
74
|
|
|
* @param Entry ...$entries |
75
|
|
|
* |
76
|
|
|
* @return array |
77
|
|
|
*/ |
78
|
3 |
|
public function serializeList(Entry ...$entries) : array |
79
|
|
|
{ |
80
|
3 |
|
$result = []; |
81
|
3 |
|
foreach ($entries as $entry) { |
82
|
2 |
|
$result[] = $this->serialize($entry); |
83
|
|
|
} |
84
|
|
|
|
85
|
3 |
|
return $result; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* Use the nullable operator if the application runned on PHP8 (see below) |
90
|
|
|
* |
91
|
|
|
* @param null|DateTimeInterface $dateTime |
92
|
|
|
* |
93
|
|
|
* @return null|string |
94
|
|
|
*/ |
95
|
8 |
|
public function dateTimeSerialize(?DateTimeInterface $dateTime) : ?string |
96
|
|
|
{ |
97
|
8 |
|
if (null === $dateTime) { |
98
|
6 |
|
return null; |
99
|
|
|
} |
100
|
|
|
|
101
|
6 |
|
return $dateTime->format(DateTime::W3C); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|