Test Setup Failed
Push — master ( b50703...9d91c5 )
by Dominik
06:16
created

Decoder::__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\Deserialization\Decoder;
6
7
final class Decoder implements DecoderInterface
8
{
9
    /**
10
     * @var DecoderTypeInterface[]
11
     */
12
    private $decoders;
13
14
    /**
15
     * @param DecoderTypeInterface[] $decoders
16
     */
17
    public function __construct(array $decoders)
18
    {
19
        $this->decoders = [];
20
        foreach ($decoders as $decoder) {
21
            $this->addDecoder($decoder);
22
        }
23
    }
24
25
    /**
26
     * @param DecoderTypeInterface $decoder
27
     */
28
    private function addDecoder(DecoderTypeInterface $decoder)
29
    {
30
        $this->decoders[$decoder->getContentType()] = $decoder;
31
    }
32
33
    /**
34
     * @return array
35
     */
36
    public function getContentTypes(): array
37
    {
38
        return array_keys($this->decoders);
39
    }
40
41
    /**
42
     * @param string $data
43
     * @param string $contentType
44
     *
45
     * @return array
46
     *
47
     * @throws DecoderException
48
     */
49
    public function decode(string $data, string $contentType): array
50
    {
51
        if (isset($this->decoders[$contentType])) {
52
            return $this->decoders[$contentType]->decode($data);
53
        }
54
55
        throw DecoderException::createMissing($contentType);
56
    }
57
}
58