Decoder::addTypeDecoder()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Deserialization\Decoder;
6
7
use Chubbyphp\Deserialization\DeserializerLogicException;
8
use Chubbyphp\Deserialization\DeserializerRuntimeException;
9
10
final class Decoder implements DecoderInterface
11
{
12
    /**
13
     * @var TypeDecoderInterface[]
14
     */
15
    private $decoderTypes;
16
17
    /**
18
     * @param TypeDecoderInterface[] $decoderTypes
19
     */
20 3
    public function __construct(array $decoderTypes)
21
    {
22 3
        $this->decoderTypes = [];
23 3
        foreach ($decoderTypes as $decoderType) {
24 3
            $this->addTypeDecoder($decoderType);
25
        }
26 3
    }
27
28
    public function getContentTypes(): array
29
    {
30
        return array_keys($this->decoderTypes);
31 1
    }
32
33 1
    /**
34
     * @throws DeserializerLogicException
35
     * @throws DeserializerRuntimeException
36
     */
37
    public function decode(string $data, string $contentType): array
38
    {
39
        if (isset($this->decoderTypes[$contentType])) {
40
            return $this->decoderTypes[$contentType]->decode($data);
41
        }
42
43
        throw DeserializerLogicException::createMissingContentType($contentType);
44
    }
45 2
46
    private function addTypeDecoder(TypeDecoderInterface $decoderType): void
47 2
    {
48 1
        $this->decoderTypes[$decoderType->getContentType()] = $decoderType;
49
    }
50
}
51