MapperContext   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 90.91%

Importance

Changes 0
Metric Value
wmc 7
eloc 12
dl 0
loc 38
ccs 10
cts 11
cp 0.9091
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addMapper() 0 3 1
A getMapper() 0 8 3
A safeContentType() 0 7 3
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