Decoder::decode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 3
c 2
b 1
f 0
nc 2
nop 2
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
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