JsonEventSerializer::deserialize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Spatie\EventProjector\EventSerializers;
4
5
use Spatie\EventProjector\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
    /** @var \Symfony\Component\Serializer\Serializer */
13
    private $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
        if (method_exists($event, '__sleep')) {
30
            $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...
31
        }
32
33
        $json = $this->serializer->serialize($event, 'json');
34
35
        return $json;
36
    }
37
38
    public function deserialize(string $eventClass, string $json): ShouldBeStored
39
    {
40
        $restoredEvent = $this->serializer->deserialize($json, $eventClass, 'json');
41
42
        /*
43
         *  We call manually serialize and unserialize to trigger
44
         * `Illuminate\Queue\SerializesModels` model restoring capabilities.
45
         */
46
        return unserialize(serialize($restoredEvent));
47
    }
48
}
49