MapperContext::addMapper()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace kalanis\Restful\Mapping;
4
5
6
use kalanis\Restful\Exceptions\InvalidStateException;
7
use Nette\Utils\Strings;
8
9
10
/**
11
 * MapperContext
12
 * @package kalanis\Restful\Mapping
13
 */
14
class MapperContext
15
{
16
17
    /** @var array<string, IMapper> */
18
    protected array $services = [];
19
20
    /**
21
     * Add mapper
22
     */
23
    public function addMapper(?string $contentType, IMapper $mapper): void
24
    {
25 1
        $this->services[$this->safeContentType($contentType)] = $mapper;
26 1
    }
27
28
    /**
29
     * Get mapper
30
     * @param string $contentType in format mimeType[; charset=utf8]
31
     * @throws InvalidStateException
32
     * @return IMapper
33
     *
34
     */
35
    public function getMapper(?string $contentType): IMapper
36
    {
37 1
        $contentType = explode(';', strval($contentType));
38 1
        $contentType = $this->safeContentType($contentType[0] ?: null);
39 1
        if (!isset($this->services[$contentType])) {
40 1
            throw new InvalidStateException('There is no mapper for Content-Type: ' . $contentType);
41
        }
42 1
        return $this->services[$contentType];
43
    }
44
45
    protected function safeContentType(?string $contentType): string
46
    {
47 1
        if (is_null($contentType)) {
48
            return 'NULL';
49
        }
50 1
        $contentType = Strings::trim($contentType);
51 1
        return $contentType ?: 'NULL';
52
    }
53
}
54