|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Innmind\Reflection\InjectionStrategy; |
|
4
|
|
|
|
|
5
|
|
|
use Innmind\Reflection\{ |
|
6
|
|
|
Cache\StrategyCachingCapabilities, |
|
7
|
|
|
Exception\LogicException, |
|
8
|
|
|
Exception\InvalidArgumentException |
|
9
|
|
|
}; |
|
10
|
|
|
use Innmind\Immutable\{ |
|
11
|
|
|
TypedCollection, |
|
12
|
|
|
TypedCollectionInterface |
|
13
|
|
|
}; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* DefaultInjectionStrategies |
|
17
|
|
|
* |
|
18
|
|
|
* @author Hugues Maignol <[email protected]> |
|
19
|
|
|
*/ |
|
20
|
|
|
final class InjectionStrategies implements InjectionStrategiesInterface |
|
21
|
|
|
{ |
|
22
|
|
|
use StrategyCachingCapabilities; |
|
23
|
|
|
|
|
24
|
|
|
private $strategies; |
|
25
|
|
|
|
|
26
|
|
View Code Duplication |
public function __construct(TypedCollectionInterface $strategies = null) |
|
|
|
|
|
|
27
|
|
|
{ |
|
28
|
|
|
$this->strategies = $strategies ?? $this->all(); |
|
29
|
|
|
|
|
30
|
|
|
if ($this->strategies->getType() !== InjectionStrategyInterface::class) { |
|
31
|
|
|
throw new InvalidArgumentException; |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function all(): TypedCollectionInterface |
|
36
|
|
|
{ |
|
37
|
|
|
if ($this->strategies === null) { |
|
38
|
|
|
return $this->strategies = new TypedCollection( |
|
|
|
|
|
|
39
|
|
|
InjectionStrategyInterface::class, |
|
40
|
|
|
[ |
|
41
|
|
|
new SetterStrategy, |
|
42
|
|
|
new NamedMethodStrategy, |
|
43
|
|
|
new ReflectionStrategy, |
|
44
|
|
|
] |
|
45
|
|
|
); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $this->strategies; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
View Code Duplication |
public function get($object, string $key, $value): InjectionStrategyInterface |
|
|
|
|
|
|
52
|
|
|
{ |
|
53
|
|
|
$strategy = $this->getCachedStrategy(get_class($object), $key); |
|
54
|
|
|
if (null !== $strategy) { |
|
55
|
|
|
return $strategy; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
foreach ($this->all() as $strategy) { |
|
59
|
|
|
if ($strategy->supports($object, $key, $value)) { |
|
60
|
|
|
|
|
61
|
|
|
$this->setCachedStrategy(get_class($object), $key, $strategy); |
|
62
|
|
|
|
|
63
|
|
|
return $strategy; |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
throw new LogicException( |
|
68
|
|
|
sprintf( |
|
69
|
|
|
'Property "%s" cannot be injected', |
|
70
|
|
|
$key |
|
71
|
|
|
) |
|
72
|
|
|
); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|
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.