1
|
|
|
<?php |
2
|
|
|
namespace Thunder\Serializard\HydratorContainer; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* @author Tomasz Kowalczyk <[email protected]> |
6
|
|
|
*/ |
7
|
|
|
final class FallbackHydratorContainer implements HydratorContainerInterface |
8
|
|
|
{ |
9
|
|
|
private $handlers = array(); |
10
|
|
|
private $interfaces = array(); |
11
|
|
|
private $aliases = array(); |
12
|
|
|
|
13
|
13 |
|
public function add($class, $handler) |
14
|
|
|
{ |
15
|
13 |
|
if(false === is_callable($handler)) { |
16
|
1 |
|
throw new \RuntimeException(sprintf('Invalid handler for class %s!', $class)); |
17
|
|
|
} |
18
|
|
|
|
19
|
12 |
|
if(class_exists($class)) { |
20
|
9 |
|
$this->aliases[$class] = $class; |
21
|
9 |
|
$this->handlers[$class] = $handler; |
22
|
12 |
|
} elseif(interface_exists($class)) { |
23
|
2 |
|
$this->aliases[$class] = $class; |
24
|
2 |
|
$this->interfaces[$class] = $handler; |
25
|
2 |
|
} else { |
26
|
1 |
|
throw new \RuntimeException(sprintf('Given value %s is neither class nor interface name!', $class)); |
27
|
|
|
} |
28
|
11 |
|
} |
29
|
|
|
|
30
|
2 |
|
public function addAlias($alias, $class) |
31
|
|
|
{ |
32
|
2 |
|
$handler = $this->getHandler($class); |
33
|
|
|
|
34
|
2 |
|
if(null === $handler) { |
35
|
1 |
|
throw new \RuntimeException(sprintf('Handler for class %s does not exist!', $class)); |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
$this->handlers[$alias] = $handler; |
39
|
1 |
|
$this->aliases[$alias] = $this->aliases[$class]; |
40
|
1 |
|
} |
41
|
|
|
|
42
|
10 |
|
public function getHandler($class) |
43
|
|
|
{ |
44
|
10 |
|
if(array_key_exists($class, $this->handlers)) { |
45
|
6 |
|
return $this->handlers[$class]; |
46
|
|
|
} |
47
|
|
|
|
48
|
5 |
|
$parents = array_intersect(array_keys($this->handlers), class_parents($class)); |
49
|
5 |
|
if($parents) { |
|
|
|
|
50
|
1 |
|
return $this->handlers[array_pop($parents)]; |
51
|
|
|
} |
52
|
|
|
|
53
|
4 |
|
$interfaces = array_intersect(array_keys($this->interfaces), array_values(class_implements($class))); |
54
|
4 |
|
if($interfaces) { |
|
|
|
|
55
|
2 |
|
if(count($interfaces) > 1) { |
56
|
1 |
|
throw new \RuntimeException(sprintf('Class %s implements interfaces with colliding handlers!', $class)); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
return $this->interfaces[array_shift($interfaces)]; |
60
|
|
|
} |
61
|
|
|
|
62
|
2 |
|
return null; |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
public function hydrate($class, array $data) |
66
|
|
|
{ |
67
|
1 |
|
return call_user_func($this->getHandler($class), $data, $this); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.