Completed
Push — master ( 00f04e...1d93d6 )
by Freek
03:46
created

JsonEventSerializer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 39
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\EventSourcing\EventSerializers;
4
5
use Spatie\EventSourcing\ShouldBeStored;
6
use Symfony\Component\Serializer\Encoder\JsonEncoder;
7
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
8
use Symfony\Component\Serializer\Serializer as SymfonySerializer;
9
10
final class JsonEventSerializer implements EventSerializer
11
{
12
    private SymfonySerializer $serializer;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
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