Completed
Push — master ( 6d7069...dad925 )
by
unknown
04:22
created

ChainSerializer::getDefaultFormat()   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 implements SerializerInterface
11
{
12
    use SerializerTrait;
13
14
    /**
15
     * @var SerializerInterface[]
16
     */
17
    private $serializers;
18
19
    /**
20
     * @var array
21
     */
22
    private $formats = [];
23
24
    /**
25
     * @param SerializerInterface $serializer
26
     */
27 3
    public function addSerializer(SerializerInterface $serializer)
28
    {
29 3
        $this->serializers[] = $serializer;
30 3
        $this->formats = array_merge($this->formats, $serializer->getSupportedFormats());
31 3
    }
32
33
    /**
34
     * @param $data
35
     * @param $format
36
     * @return mixed
37
     * @throws SerializerException
38
     */
39 3
    public function serialize($data, $format)
40
    {
41 3
        $this->assertHasSerializer();
42
43 2
        foreach ($this->serializers as $serializer) {
44 2
            if ($serializer->supportsFormat($format)) {
45 1
                return $serializer->serialize($data, $format);
46
            }
47 2
        }
48
49 1
        throw new SerializerException(sprintf('No serializer found to support format "%s"', $format));
50
    }
51
52
    /**
53
     * @return array
54
     */
55 2
    public function getSupportedFormats()
56
    {
57 2
        $this->assertHasSerializer();
58
59 1
        return $this->formats;
60
    }
61
62
    /**
63
     * @return string
64
     */
65 2
    public function getDefaultFormat()
66
    {
67 2
        $this->assertHasSerializer();
68
69 1
        return $this->serializers[0]->getDefaultFormat();
70
    }
71
72
    /**
73
     * @throws SerializerException
74
     */
75 6
    private function assertHasSerializer()
76
    {
77 6
        if (count($this->serializers) === 0) {
78 3
            throw new SerializerException('No serializer was configured');
79
        }
80 3
    }
81
}
82