Encoder::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 2
rs 10
c 1
b 0
f 0
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 3
    public function __construct(array $encoderTypes)
20
    {
21 3
        $this->encoderTypes = [];
22 3
        foreach ($encoderTypes as $encoderType) {
23 3
            $this->addTypeEncoder($encoderType);
24
        }
25 3
    }
26
27
    public function getContentTypes(): array
28
    {
29
        return array_keys($this->encoderTypes);
30 1
    }
31
32 1
    /**
33
     * @throws SerializerLogicException
34
     */
35
    public function encode(array $data, string $contentType): string
36
    {
37
        if (isset($this->encoderTypes[$contentType])) {
38
            return $this->encoderTypes[$contentType]->encode($data);
39
        }
40
41
        throw SerializerLogicException::createMissingContentType($contentType);
42
    }
43 2
44
    private function addTypeEncoder(TypeEncoderInterface $encoderType): void
45 2
    {
46 1
        $this->encoderTypes[$encoderType->getContentType()] = $encoderType;
47
    }
48
}
49