Serializer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jellyfish\SerializerSymfony;
6
7
use ArrayObject;
8
use Jellyfish\Serializer\SerializerInterface;
9
use Symfony\Component\Serializer\SerializerInterface as SymfonySerializerInterface;
10
11
use function is_array;
12
13
class Serializer implements SerializerInterface
14
{
15
    /**
16
     * @var \Symfony\Component\Serializer\SerializerInterface
17
     */
18
    protected $symfonySerializer;
19
20
    /**
21
     * @param \Symfony\Component\Serializer\SerializerInterface $symfonySerializer
22
     */
23
    public function __construct(SymfonySerializerInterface $symfonySerializer)
24
    {
25
        $this->symfonySerializer = $symfonySerializer;
26
    }
27
28
    /**
29
     * @param object $data
30
     * @param string $format
31
     *
32
     * @return string
33
     */
34
    public function serialize(object $data, string $format): string
35
    {
36
        if (!($data instanceof ArrayObject)) {
37
            return $this->symfonySerializer->serialize($data, $format, [
38
                'skip_null_values' => true
39
            ]);
40
        }
41
42
        $dataAsArray = $data->getArrayCopy();
43
44
        return $this->symfonySerializer->serialize($dataAsArray, $format, [
45
            'skip_null_values' => true
46
        ]);
47
    }
48
49
    /**
50
     * @param string $data
51
     * @param string $type
52
     * @param string $format
53
     *
54
     * @return object
55
     */
56
    public function deserialize(string $data, string $type, string $format): object
57
    {
58
        $deserializedData = $this->symfonySerializer->deserialize($data, $type, $format);
59
60
        if (is_array($deserializedData)) {
61
            return new ArrayObject($deserializedData);
62
        }
63
64
        return $deserializedData;
65
    }
66
}
67