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