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
|
|
|
} |