Completed
Push — master ( 58d973...681a3d )
by
unknown
05:43
created

ChainSerializer::getDefaultFormat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace MediaMonks\RestApiBundle\Serializer;
4
5
use JMS\Serializer\Serializer;
6
use JMS\Serializer\SerializationContext;
7
use MediaMonks\RestApiBundle\Exception\SerializerException;
8
use MediaMonks\RestApiBundle\Request\Format;
9
10
class ChainSerializer extends AbstractSerializer implements SerializerInterface
11
{
12
    /**
13
     * @var SerializerInterface[]
14
     */
15
    private $serializers;
16
17
    /**
18
     * @var array
19
     */
20
    private $formats = [];
21
22
    /**
23
     * @param SerializerInterface $serializer
24
     */
25
    public function addSerializer(SerializerInterface $serializer)
26
    {
27
        $this->serializers[] = $serializer;
28
        $this->formats = array_merge($this->formats, $serializer->getSupportedFormats());
29
    }
30
31
    /**
32
     * @param $data
33
     * @param $format
34
     * @return mixed
35
     * @throws SerializerException
36
     */
37
    public function serialize($data, $format)
38
    {
39
        $this->assertHasSerializer();
40
41
        foreach($this->serializers as $serializer) {
42
            if ($serializer->supportsFormat($format)) {
43
                return $serializer->serialize($data, $format);
44
            }
45
        }
46
47
        throw new SerializerException(sprintf('No serializer found to support format "%s"', $format));
48
    }
49
50
    /**
51
     * @return array
52
     */
53
    public function getSupportedFormats()
54
    {
55
        return $this->formats;
56
    }
57
58
    /**
59
     * @return string
60
     */
61
    public function getDefaultFormat()
62
    {
63
        $this->assertHasSerializer();
64
65
        return $this->serializers[0]->getDefaultFormat();
66
    }
67
68
    /**
69
     * @throws SerializerException
70
     */
71
    private function assertHasSerializer()
72
    {
73
        if (count($this->serializers) === 0) {
74
            throw new SerializerException('No serializer was configured');
75
        }
76
    }
77
}
78