Passed
Push — master ( 502a73...9f4d43 )
by Dominik
01:58
created

Transformer::transform()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization;
6
7
use Chubbyphp\Serialization\Transformer\TransformerInterface as ContenTypeTransformerInterface;
8
9
final class Transformer implements TransformerInterface
10
{
11
    /**
12
     * @var ContenTypeTransformerInterface[]
13
     */
14
    private $transformers;
15
16
    /**
17
     * @param ContenTypeTransformerInterface[] $transformers
18
     */
19 3
    public function __construct(array $transformers)
20
    {
21 3
        $this->transformers = [];
22 3
        foreach ($transformers as $transformer) {
23 2
            $this->addTransformer($transformer);
24
        }
25 3
    }
26
27
    /**
28
     * @param ContenTypeTransformerInterface $transformer
29
     */
30 2
    private function addTransformer(ContenTypeTransformerInterface $transformer)
31
    {
32 2
        $this->transformers[$transformer->getContentType()] = $transformer;
33 2
    }
34
35
    /**
36
     * @return array
37
     */
38 1
    public function getContentTypes(): array
39
    {
40 1
        return array_keys($this->transformers);
41
    }
42
43
    /**
44
     * @param array  $data
45
     * @param string $contentType
46
     *
47
     * @return string
48
     *
49
     * @throws \InvalidArgumentException
50
     */
51 2
    public function transform(array $data, string $contentType): string
52
    {
53 2
        if (isset($this->transformers[$contentType])) {
54 1
            return $this->transformers[$contentType]->transform($data);
55
        }
56
57 1
        throw new \InvalidArgumentException(sprintf('There is no transformer for content-type: %s', $contentType));
58
    }
59
}
60