Completed
Push — master ( 8bfaf6...ca95b3 )
by Freek
07:02
created

JsonEventSerializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace Spatie\EventProjector\EventSerializers;
4
5
use Spatie\EventProjector\ShouldBeStored;
6
use Symfony\Component\Serializer\Serializer as SymfonySerializer;
7
use Symfony\Component\Serializer\Encoder\JsonEncoder;
8
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
9
10
class JsonEventSerializer implements EventSerializer
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();
0 ignored issues
show
Bug introduced by
The method __sleep() does not seem to exist on object<Spatie\EventProjector\ShouldBeStored>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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