ClassBasedTypeHandler   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 94.12%

Importance

Changes 0
Metric Value
dl 0
loc 73
c 0
b 0
f 0
wmc 6
lcom 1
cbo 0
ccs 16
cts 17
cp 0.9412
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getType() 0 10 2
A resolveType() 0 16 3
1
<?php
2
declare(strict_types = 1);
3
4
namespace Mikemirten\Component\JsonApi\Mapper\Handler\TypeHandler;
5
6
use Mikemirten\Component\JsonApi\Mapper\MappingContext;
7
8
/**
9
 * Type handler based on class of object
10
 *
11
 * @package Mikemirten\Component\JsonApi\ObjectTransformer\TypeHandler
12
 */
13
class ClassBasedTypeHandler implements TypeHandlerInterface
14
{
15
    /**
16
     * Full class name as a type
17
     *
18
     * @var bool
19
     */
20
    protected $fullName;
21
22
    /**
23
     * Type parts delimiter
24
     * Works only for "full-name" mode enabled
25
     *
26
     * @var string
27
     */
28
    protected $delimiter;
29
30
    /**
31
     * Cache of resolved types
32
     *
33
     * @var array
34
     */
35
    protected $resolvedCache = [];
36
37
    /**
38
     * ClassBasedTypeHandler constructor.
39
     *
40
     * @param bool   $fullName  Use full class name as a type
41
     * @param string $delimiter Type parts delimiter (only for enable "full-name" mode)
42
     */
43 2
    public function __construct(bool $fullName = true, string $delimiter = '.')
44
    {
45 2
        $this->fullName  = $fullName;
46 2
        $this->delimiter = $delimiter;
47 2
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 2
    public function getType($object, MappingContext $context): string
53
    {
54 2
        $class = get_class($object);
55
56 2
        if (! isset($this->resolvedCache[$class])) {
57 2
            $this->resolvedCache[$class] = $this->resolveType($class);
58
        }
59
60 2
        return $this->resolvedCache[$class];
61
    }
62
63
    /**
64
     * Resolve type by class
65
     *
66
     * @param  string $class
67
     * @return string
68
     */
69 2
    protected function resolveType(string $class): string
70
    {
71 2
        $name = str_replace(['\\', '_'], $this->delimiter, ucwords($class, '\\_'));
72
73 2
        if ($this->fullName) {
74 1
            return $name;
75
        }
76
77 1
        $pos = strrpos($name, $this->delimiter);
78
79 1
        if ($pos === false) {
80
            return $name;
81
        }
82
83 1
        return substr($name, $pos + 1);
84
    }
85
}