Test Failed
Push — master ( 8a2b60...8e4848 )
by Dominik
03:00
created

Encoder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 51
c 0
b 0
f 0
wmc 6
lcom 1
cbo 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A addTypeEncoder() 0 4 1
A getContentTypes() 0 4 1
A encode() 0 8 2
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
    public function __construct(array $encoderTypes)
20
    {
21
        $this->encoderTypes = [];
22
        foreach ($encoderTypes as $encoderType) {
23
            $this->addTypeEncoder($encoderType);
24
        }
25
    }
26
27
    /**
28
     * @param TypeEncoderInterface $encoderType
29
     */
30
    private function addTypeEncoder(TypeEncoderInterface $encoderType)
31
    {
32
        $this->encoderTypes[$encoderType->getContentType()] = $encoderType;
33
    }
34
35
    /**
36
     * @return array
37
     */
38
    public function getContentTypes(): array
39
    {
40
        return array_keys($this->encoderTypes);
41
    }
42
43
    /**
44
     * @param array  $data
45
     * @param string $contentType
46
     *
47
     * @return string
48
     *
49
     * @throws SerializerLogicException
50
     */
51
    public function encode(array $data, string $contentType): string
52
    {
53
        if (isset($this->encoderTypes[$contentType])) {
54
            return $this->encoderTypes[$contentType]->encode($data);
55
        }
56
57
        throw SerializerLogicException::createMissingContentType($contentType);
58
    }
59
}
60