TypeMapper::hasMapping()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Swis\JsonApi\Client;
6
7
use Swis\JsonApi\Client\Exceptions\TypeMappingException;
8
use Swis\JsonApi\Client\Interfaces\ItemInterface;
9
use Swis\JsonApi\Client\Interfaces\TypeMapperInterface;
10
11
class TypeMapper implements TypeMapperInterface
12
{
13
    /**
14
     * @var array
15
     */
16
    protected $typeMappings = [];
17
18
    /**
19
     * @throws \Swis\JsonApi\Client\Exceptions\TypeMappingException
20
     */
21 172
    public function setMapping(string $type, string $class): void
22
    {
23 172
        if (! class_exists($class)) {
24 4
            throw new TypeMappingException(sprintf('Class %s not found.', $class));
25
        }
26
27 168
        if (! is_subclass_of($class, ItemInterface::class)) {
28 4
            throw new TypeMappingException(sprintf('Class %s must implement %s.', $class, ItemInterface::class));
29
        }
30
31 164
        $this->typeMappings[$type] = $class;
32 82
    }
33
34 128
    public function hasMapping(string $type): bool
35
    {
36 128
        return array_key_exists($type, $this->typeMappings);
37
    }
38
39 4
    public function removeMapping(string $type): void
40
    {
41 4
        unset($this->typeMappings[$type]);
42 2
    }
43
44
    /**
45
     * @throws \Swis\JsonApi\Client\Exceptions\TypeMappingException
46
     */
47 96
    public function getMapping(string $type): ItemInterface
48
    {
49 96
        if (! array_key_exists($type, $this->typeMappings)) {
50 4
            throw new TypeMappingException(sprintf('No mapping for type %s', $type));
51
        }
52
53 92
        return new $this->typeMappings[$type];
54
    }
55
}
56