@@ 9-45 (lines=37) @@ | ||
6 | use Symfony\Component\Serializer\Encoder\JsonEncoder; |
|
7 | use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
|
8 | ||
9 | class EventSerializer |
|
10 | { |
|
11 | /** @var \Symfony\Component\Serializer\Serializer */ |
|
12 | protected $serializer; |
|
13 | ||
14 | public function __construct() |
|
15 | { |
|
16 | $encoders = [new JsonEncoder()]; |
|
17 | $normalizers = [new ObjectNormalizer()]; |
|
18 | ||
19 | $this->serializer = new Serializer($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 | $event->__sleep(); |
|
29 | ||
30 | $json = $this->serializer->serialize($event, 'json'); |
|
31 | ||
32 | return $json; |
|
33 | } |
|
34 | ||
35 | public function deserialize(string $eventClass, string $json): ShouldBeStored |
|
36 | { |
|
37 | $restoredEvent = $this->serializer->deserialize($json, $eventClass, 'json'); |
|
38 | ||
39 | /* |
|
40 | * We call manually serialize and unserialize to trigger |
|
41 | * `Illuminate\Queue\SerializesModels` model restoring capabilities. |
|
42 | */ |
|
43 | return unserialize(serialize($restoredEvent)); |
|
44 | } |
|
45 | } |
|
46 |
@@ 10-46 (lines=37) @@ | ||
7 | use Symfony\Component\Serializer\Encoder\JsonEncoder; |
|
8 | use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
|
9 | ||
10 | class JsonSerializer implements Serializer |
|
11 | { |
|
12 | /** @var \Symfony\Component\Serializer\Serializer */ |
|
13 | protected $serializer; |
|
14 | ||
15 | public function __construct() |
|
16 | { |
|
17 | $encoders = [new JsonEncoder()]; |
|
18 | $normalizers = [new ObjectNormalizer()]; |
|
19 | ||
20 | $this->serializer = new SymfonySerializer($normalizers, $encoders); |
|
21 | } |
|
22 | ||
23 | public function serialize(ShouldBeStored $event): string |
|
24 | { |
|
25 | /* |
|
26 | * We call __sleep so `Illuminate\Queue\SerializesModels` will |
|
27 | * prepare all models in the event for serialization. |
|
28 | */ |
|
29 | $event->__sleep(); |
|
30 | ||
31 | $json = $this->serializer->serialize($event, 'json'); |
|
32 | ||
33 | return $json; |
|
34 | } |
|
35 | ||
36 | public function deserialize(string $eventClass, string $json): ShouldBeStored |
|
37 | { |
|
38 | $restoredEvent = $this->serializer->deserialize($json, $eventClass, 'json'); |
|
39 | ||
40 | /* |
|
41 | * We call manually serialize and unserialize to trigger |
|
42 | * `Illuminate\Queue\SerializesModels` model restoring capabilities. |
|
43 | */ |
|
44 | return unserialize(serialize($restoredEvent)); |
|
45 | } |
|
46 | } |
|
47 |