1 | <?php |
||
10 | final class JsonEventSerializer implements EventSerializer |
||
11 | { |
||
12 | private SymfonySerializer $serializer; |
||
|
|||
13 | |||
14 | public function __construct() |
||
15 | { |
||
16 | $encoders = [new JsonEncoder()]; |
||
17 | $normalizers = [new ObjectNormalizer()]; |
||
18 | |||
19 | $this->serializer = new SymfonySerializer($normalizers, $encoders); |
||
20 | } |
||
21 | |||
22 | public function serialize(ShouldBeStored $event): string |
||
23 | { |
||
24 | /* |
||
25 | * We call __sleep so `Illuminate\Queue\SerializesModels` will |
||
26 | * prepare all models in the event for serialization. |
||
27 | */ |
||
28 | if (method_exists($event, '__sleep')) { |
||
29 | $event->__sleep(); |
||
30 | } |
||
31 | |||
32 | $json = $this->serializer->serialize($event, 'json'); |
||
33 | |||
34 | return $json; |
||
35 | } |
||
36 | |||
37 | public function deserialize(string $eventClass, string $json): ShouldBeStored |
||
38 | { |
||
39 | $restoredEvent = $this->serializer->deserialize($json, $eventClass, 'json'); |
||
40 | |||
41 | /* |
||
42 | * We call manually serialize and unserialize to trigger |
||
43 | * `Illuminate\Queue\SerializesModels` model restoring capabilities. |
||
44 | */ |
||
45 | return unserialize(serialize($restoredEvent)); |
||
46 | } |
||
47 | } |
||
48 |