1
|
|
|
<?php |
2
|
|
|
namespace Thunder\Serializard\HydratorContainer; |
3
|
|
|
|
4
|
|
|
use Thunder\Serializard\Exception\HydratorConflictException; |
5
|
|
|
use Thunder\Serializard\Exception\HydratorNotFoundException; |
6
|
|
|
use Thunder\Serializard\Exception\ClassNotFoundException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @author Tomasz Kowalczyk <[email protected]> |
10
|
|
|
*/ |
11
|
|
|
final class FallbackHydratorContainer implements HydratorContainerInterface |
12
|
|
|
{ |
13
|
|
|
private $handlers = []; |
14
|
|
|
private $interfaces = []; |
15
|
|
|
private $aliases = []; |
16
|
|
|
|
17
|
12 |
View Code Duplication |
public function add($class, callable $handler) |
|
|
|
|
18
|
|
|
{ |
19
|
12 |
|
if(class_exists($class)) { |
20
|
9 |
|
$this->aliases[$class] = $class; |
21
|
9 |
|
$this->handlers[$class] = $handler; |
22
|
3 |
|
} elseif(interface_exists($class)) { |
23
|
2 |
|
$this->aliases[$class] = $class; |
24
|
2 |
|
$this->interfaces[$class] = $handler; |
25
|
|
|
} else { |
26
|
1 |
|
throw ClassNotFoundException::fromClass($class); |
27
|
|
|
} |
28
|
11 |
|
} |
29
|
|
|
|
30
|
2 |
View Code Duplication |
public function addAlias($alias, $class) |
|
|
|
|
31
|
|
|
{ |
32
|
2 |
|
$handler = $this->getHandler($class); |
33
|
|
|
|
34
|
1 |
|
$this->handlers[$alias] = $handler; |
35
|
1 |
|
$this->aliases[$alias] = $this->aliases[$class]; |
36
|
1 |
|
} |
37
|
|
|
|
38
|
10 |
|
public function getHandler($class) |
39
|
|
|
{ |
40
|
10 |
|
if(array_key_exists($class, $this->handlers)) { |
41
|
6 |
|
return $this->handlers[$class]; |
42
|
|
|
} |
43
|
|
|
|
44
|
5 |
|
$parents = array_intersect(array_keys($this->handlers), class_parents($class)); |
45
|
5 |
|
if($parents) { |
|
|
|
|
46
|
1 |
|
return $this->handlers[array_pop($parents)]; |
47
|
|
|
} |
48
|
|
|
|
49
|
4 |
|
$interfaces = array_intersect(array_keys($this->interfaces), array_values(class_implements($class))); |
50
|
4 |
View Code Duplication |
if($interfaces) { |
|
|
|
|
51
|
2 |
|
if(\count($interfaces) > 1) { |
52
|
1 |
|
throw HydratorConflictException::fromClass($class, $interfaces); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
return $this->interfaces[array_shift($interfaces)]; |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
throw HydratorNotFoundException::fromClass($class); |
59
|
|
|
} |
60
|
|
|
|
61
|
1 |
|
public function hydrate($class, array $data) |
62
|
|
|
{ |
63
|
1 |
|
return \call_user_func($this->getHandler($class), $data, $this); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.