Completed
Push — master ( d8a1ad...d0379b )
by Dominik
02:06
created

Decoder::decode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 2.0625
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 4
    public function __construct(array $decoders)
18
    {
19 4
        $this->decoders = [];
20 4
        foreach ($decoders as $decoder) {
21 4
            $this->addDecoder($decoder);
22
        }
23 4
    }
24
25
    /**
26
     * @param DecoderTypeInterface $decoder
27
     */
28 4
    private function addDecoder(DecoderTypeInterface $decoder)
29
    {
30 4
        $this->decoders[$decoder->getContentType()] = $decoder;
31 4
    }
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 4
    public function decode(string $data, string $contentType): array
50
    {
51 4
        if (isset($this->decoders[$contentType])) {
52 4
            return $this->decoders[$contentType]->decode($data);
53
        }
54
55
        throw DecoderException::createMissing($contentType);
56
    }
57
}
58