Completed
Push — master ( c2ba48...1fd225 )
by Markus
14s queued 12s
created

Serializer::serialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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