generated from yiisoft/package-template
/
ParameterDefinition.php
111 lines (92 loc) · 3.15 KB
/
ParameterDefinition.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
declare(strict_types=1);
namespace Yiisoft\Definitions;
use Psr\Container\ContainerInterface;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionUnionType;
use Yiisoft\Definitions\Contract\DefinitionInterface;
use Yiisoft\Definitions\Exception\NotInstantiableException;
/**
* Parameter definition resolves an object based on information from `ReflectionParameter` instance.
*/
final class ParameterDefinition implements DefinitionInterface
{
private ReflectionParameter $parameter;
public function __construct(ReflectionParameter $parameter)
{
$this->parameter = $parameter;
}
public function isVariadic(): bool
{
return $this->parameter->isVariadic();
}
public function isOptional(): bool
{
return $this->parameter->isOptional();
}
public function hasValue(): bool
{
return $this->parameter->isDefaultValueAvailable() || $this->parameter->allowsNull();
}
public function resolve(ContainerInterface $container)
{
if ($this->parameter->isDefaultValueAvailable()) {
return $this->parameter->getDefaultValue();
}
if ($this->parameter->allowsNull()) {
return null;
}
if ($this->isOptional()) {
throw new NotInstantiableException(
sprintf(
'Can not determine default value of parameter "%s" when instantiating "%s" ' .
'because it is PHP internal. Please specify argument explicitly.',
$this->parameter->getName(),
$this->getCallable(),
)
);
}
throw new NotInstantiableException(
sprintf(
'Can not determine value of the "%s" parameter of type "%s" when instantiating "%s". ' .
'Please specify argument explicitly.',
$this->parameter->getName(),
$this->getType(),
$this->getCallable(),
)
);
}
private function getType(): string
{
/**
* @psalm-suppress UndefinedDocblockClass
*
* @var ReflectionNamedType|ReflectionUnionType $type Could not be `null`
* because in self::resolve() checked `$this->parameter->allowsNull()`.
*/
$type = $this->parameter->getType();
/** @psalm-suppress UndefinedClass, TypeDoesNotContainType */
if ($type instanceof ReflectionUnionType) {
/** @var ReflectionNamedType[] */
$namedTypes = $type->getTypes();
$names = array_map(
static fn (ReflectionNamedType $t) => $t->getName(),
$namedTypes
);
return implode('|', $names);
}
/** @var ReflectionNamedType $type */
return $type->getName();
}
private function getCallable(): string
{
$callable = [];
$class = $this->parameter->getDeclaringClass();
if ($class !== null) {
$callable[] = $class->getName();
}
$callable[] = $this->parameter->getDeclaringFunction()->getName() . '()';
return implode('::', $callable);
}
}