|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Innmind\Reflection\InjectionStrategy; |
|
5
|
|
|
|
|
6
|
|
|
use Innmind\Reflection\{ |
|
7
|
|
|
InjectionStrategy, |
|
8
|
|
|
Exception\InvalidArgumentException, |
|
9
|
|
|
Exception\PropertyCannotBeInjected, |
|
10
|
|
|
}; |
|
11
|
|
|
use Innmind\Immutable\{ |
|
12
|
|
|
Stream, |
|
13
|
|
|
Map, |
|
14
|
|
|
}; |
|
15
|
|
|
|
|
16
|
|
|
final class DelegationStrategy implements InjectionStrategy |
|
17
|
|
|
{ |
|
18
|
|
|
private $strategies; |
|
19
|
|
|
private $cache; |
|
20
|
|
|
|
|
21
|
7 |
|
public function __construct(InjectionStrategy ...$strategies) |
|
22
|
|
|
{ |
|
23
|
7 |
|
$this->strategies = Stream::of(InjectionStrategy::class, ...$strategies); |
|
24
|
7 |
|
$this->cache = new Map('string', InjectionStrategy::class); |
|
25
|
7 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* {@inheritdoc} |
|
29
|
|
|
*/ |
|
30
|
1 |
|
public function supports(object $object, string $property, $value): bool |
|
31
|
|
|
{ |
|
32
|
|
|
return $this |
|
33
|
1 |
|
->strategies |
|
34
|
1 |
|
->reduce( |
|
35
|
1 |
|
false, |
|
36
|
|
|
function(bool $supports, InjectionStrategy $strategy) use ($object, $property, $value): bool { |
|
37
|
1 |
|
return $supports || $strategy->supports($object, $property, $value); |
|
38
|
1 |
|
} |
|
39
|
|
|
); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* {@inheritdoc} |
|
44
|
|
|
*/ |
|
45
|
9 |
|
public function inject(object $object, string $property, $value): object |
|
46
|
|
|
{ |
|
47
|
9 |
|
$key = $this->generateKey($object, $property); |
|
48
|
|
|
|
|
49
|
9 |
|
if ($this->cache->contains($key)) { |
|
50
|
|
|
return $this |
|
51
|
1 |
|
->cache |
|
52
|
1 |
|
->get($key) |
|
53
|
1 |
|
->inject($object, $property, $value); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
9 |
|
$strategy = $this->strategies->reduce( |
|
57
|
9 |
|
null, |
|
58
|
|
|
function(?InjectionStrategy $target, InjectionStrategy $strategy) use ($object, $property, $value): ?InjectionStrategy { |
|
59
|
9 |
|
return $target ?? ($strategy->supports($object, $property, $value) ? $strategy : null); |
|
60
|
9 |
|
} |
|
61
|
|
|
); |
|
62
|
|
|
|
|
63
|
9 |
|
if (!$strategy instanceof InjectionStrategy) { |
|
64
|
3 |
|
throw new PropertyCannotBeInjected($property); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
6 |
|
$this->cache = $this->cache->put($key, $strategy); |
|
68
|
|
|
|
|
69
|
6 |
|
return $strategy->inject($object, $property, $value); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
9 |
|
private function generateKey(object $object, string $property): string |
|
73
|
|
|
{ |
|
74
|
9 |
|
return get_class($object).'::'.$property; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|