1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of PHP Invoker. |
7
|
|
|
* |
8
|
|
|
* PHP version 7.1 and above required |
9
|
|
|
* |
10
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
11
|
|
|
* @copyright 2019 Biurad Group (https://biurad.com/) |
12
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause License |
13
|
|
|
* |
14
|
|
|
* For the full copyright and license information, please view the LICENSE |
15
|
|
|
* file that was distributed with this source code. |
16
|
|
|
*/ |
17
|
|
|
|
18
|
|
|
namespace DivineNii\Invoker\ArgumentResolver; |
19
|
|
|
|
20
|
|
|
use ArgumentCountError; |
21
|
|
|
use DivineNii\Invoker\Interfaces\ArgumentValueResolverInterface; |
22
|
|
|
use Psr\Container\ContainerInterface; |
23
|
|
|
use Psr\Container\NotFoundExceptionInterface; |
24
|
|
|
use ReflectionClass; |
25
|
|
|
use ReflectionParameter; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Inject or create a class instance from a DI container or return existing instance |
29
|
|
|
* from $providedParameters using the type-hints. |
30
|
|
|
* |
31
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
32
|
|
|
*/ |
33
|
|
|
class ClassValueResolver implements ArgumentValueResolverInterface |
34
|
|
|
{ |
35
|
|
|
/** @var ContainerInterface|null */ |
36
|
|
|
private $container; |
37
|
|
|
|
38
|
52 |
|
public function __construct(?ContainerInterface $container = null) |
39
|
|
|
{ |
40
|
52 |
|
$this->container = $container; |
41
|
52 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* {@inheritdoc} |
45
|
|
|
*/ |
46
|
26 |
|
public function resolve(ReflectionParameter $parameter, array $providedParameters) |
47
|
|
|
{ |
48
|
26 |
|
$parameterType = $parameter->getType(); |
49
|
|
|
|
50
|
26 |
|
if (!$parameterType instanceof \ReflectionNamedType || $parameterType->isBuiltin()) { |
51
|
|
|
// No type, Primitive types and Union types are not supported |
52
|
17 |
|
return; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
// Inject entries from a DI container using the type-hints. |
56
|
10 |
|
if (null !== $this->container) { |
57
|
|
|
try { |
58
|
3 |
|
return $this->container->get($parameterType->getName()); |
59
|
1 |
|
} catch (NotFoundExceptionInterface $e) { |
60
|
|
|
// We need no exception thrown here |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
// If an instance is detected |
65
|
8 |
|
foreach ($providedParameters as $key => $value) { |
66
|
4 |
|
if (\is_a($value, $parameterType->getName(), true)) { |
67
|
4 |
|
return $providedParameters[$key]; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
try { |
72
|
4 |
|
$reflectionClass = new ReflectionClass($parameterType->getName()); |
73
|
|
|
|
74
|
4 |
|
if ($reflectionClass->isInstantiable()) { |
75
|
4 |
|
return $reflectionClass->newInstance(); |
76
|
|
|
} |
77
|
|
|
} catch (ArgumentCountError $e) { |
78
|
|
|
// Throw no exception ... |
79
|
|
|
} |
80
|
1 |
|
} |
81
|
|
|
} |
82
|
|
|
|