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="EntryList", |
21
|
|
|
* type="array", |
22
|
|
|
* items=@OpenApi\SchemaReference( |
23
|
|
|
* class="App\Bundle\Example\Service\EntrySerializer", |
24
|
|
|
* method="serialize", |
25
|
|
|
* ), |
26
|
|
|
* ) |
27
|
|
|
* |
28
|
|
|
* @param Entry ...$entries |
29
|
|
|
* |
30
|
|
|
* @return array |
31
|
|
|
*/ |
32
|
|
|
public function listSerialize(Entry ...$entries) : array |
33
|
|
|
{ |
34
|
|
|
$result = []; |
35
|
|
|
foreach ($entries as $entry) { |
36
|
|
|
$result[] = $this->serialize($entry); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return $result; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @OpenApi\Schema( |
44
|
|
|
* refName="Entry", |
45
|
|
|
* type="object", |
46
|
|
|
* properties={ |
47
|
|
|
* "id": @OpenApi\Schema( |
48
|
|
|
* type="string", |
49
|
|
|
* format="uuid", |
50
|
|
|
* nullable=false, |
51
|
|
|
* ), |
52
|
|
|
* "name": @OpenApi\SchemaReference( |
53
|
|
|
* class="App\Bundle\Example\Entity\Entry", |
54
|
|
|
* property="name", |
55
|
|
|
* ), |
56
|
|
|
* "slug": @OpenApi\SchemaReference( |
57
|
|
|
* class="App\Bundle\Example\Entity\Entry", |
58
|
|
|
* property="slug", |
59
|
|
|
* ), |
60
|
|
|
* "createdAt": @OpenApi\Schema( |
61
|
|
|
* type="string", |
62
|
|
|
* format="date-time", |
63
|
|
|
* nullable=false, |
64
|
|
|
* ), |
65
|
|
|
* "updatedAt": @OpenApi\Schema( |
66
|
|
|
* type="string", |
67
|
|
|
* format="date-time", |
68
|
|
|
* nullable=true, |
69
|
|
|
* ), |
70
|
|
|
* }, |
71
|
|
|
* ) |
72
|
|
|
* |
73
|
|
|
* @param Entry $entry |
74
|
|
|
* |
75
|
|
|
* @return array |
76
|
|
|
*/ |
77
|
|
|
public function serialize(Entry $entry) : array |
78
|
|
|
{ |
79
|
|
|
return [ |
80
|
|
|
'id' => $entry->getId(), |
81
|
|
|
'name' => $entry->getName(), |
82
|
|
|
'slug' => $entry->getSlug(), |
83
|
|
|
'createdAt' => $this->dateTimeSerialize($entry->getCreatedAt()), |
84
|
|
|
'updatedAt' => $this->dateTimeSerialize($entry->getUpdatedAt()), |
85
|
|
|
]; |
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
|
|
|
public function dateTimeSerialize(?DateTimeInterface $dateTime) : ?string |
96
|
|
|
{ |
97
|
|
|
if (null === $dateTime) { |
98
|
|
|
return null; |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
return $dateTime->format(DateTime::W3C); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|