Completed
Push — master ( e49a19...58f61d )
by Freek
01:47
created

JsonSerializer::deserialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 3

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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 View Code Duplication
class JsonSerializer implements Serializer
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

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