Test Failed
Push — master ( 8a2b60...8e4848 )
by Dominik
03:00
created

Encoder::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Encoder;
6
7
use Chubbyphp\Serialization\SerializerLogicException;
8
9
final class Encoder implements EncoderInterface
10
{
11
    /**
12
     * @var TypeEncoderInterface[]
13
     */
14
    private $encoderTypes;
15
16
    /**
17
     * @param TypeEncoderInterface[] $encoderTypes
18
     */
19
    public function __construct(array $encoderTypes)
20
    {
21
        $this->encoderTypes = [];
22
        foreach ($encoderTypes as $encoderType) {
23
            $this->addTypeEncoder($encoderType);
24
        }
25
    }
26
27
    /**
28
     * @param TypeEncoderInterface $encoderType
29
     */
30
    private function addTypeEncoder(TypeEncoderInterface $encoderType)
31
    {
32
        $this->encoderTypes[$encoderType->getContentType()] = $encoderType;
33
    }
34
35
    /**
36
     * @return array
37
     */
38
    public function getContentTypes(): array
39
    {
40
        return array_keys($this->encoderTypes);
41
    }
42
43
    /**
44
     * @param array  $data
45
     * @param string $contentType
46
     *
47
     * @return string
48
     *
49
     * @throws SerializerLogicException
50
     */
51
    public function encode(array $data, string $contentType): string
52
    {
53
        if (isset($this->encoderTypes[$contentType])) {
54
            return $this->encoderTypes[$contentType]->encode($data);
55
        }
56
57
        throw SerializerLogicException::createMissingContentType($contentType);
58
    }
59
}
60