Completed
Push — master ( a15a3c...decc90 )
by
unknown
04:44
created

ChainSerializer::getSupportedFormats()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
crap 1
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 2
    public function addSerializer(SerializerInterface $serializer)
26
    {
27 2
        $this->serializers[] = $serializer;
28 2
        $this->formats = array_merge($this->formats, $serializer->getSupportedFormats());
29 2
    }
30
31
    /**
32
     * @param $data
33
     * @param $format
34
     * @return mixed
35
     * @throws SerializerException
36
     */
37 2
    public function serialize($data, $format)
38
    {
39 2
        $this->assertHasSerializer();
40
41 1
        foreach($this->serializers as $serializer) {
42 1
            if ($serializer->supportsFormat($format)) {
43 1
                return $serializer->serialize($data, $format);
44
            }
45 1
        }
46
47
        throw new SerializerException(sprintf('No serializer found to support format "%s"', $format));
48
    }
49
50
    /**
51
     * @return array
52
     */
53 2
    public function getSupportedFormats()
54
    {
55 2
        $this->assertHasSerializer();
56
57 1
        return $this->formats;
58
    }
59
60
    /**
61
     * @return string
62
     */
63 2
    public function getDefaultFormat()
64
    {
65 2
        $this->assertHasSerializer();
66
67 1
        return $this->serializers[0]->getDefaultFormat();
68
    }
69
70
    /**
71
     * @throws SerializerException
72
     */
73 5
    private function assertHasSerializer()
74
    {
75 5
        if (count($this->serializers) === 0) {
76 3
            throw new SerializerException('No serializer was configured');
77
        }
78 2
    }
79
}
80