1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\Callback; |
4
|
|
|
|
5
|
|
|
use Zenstruck\Callback\Exception\UnresolveableArgument; |
6
|
|
|
use Zenstruck\Callback\Parameter\TypedParameter; |
7
|
|
|
use Zenstruck\Callback\Parameter\UnionParameter; |
8
|
|
|
use Zenstruck\Callback\Parameter\UntypedParameter; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @author Kevin Bond <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
abstract class Parameter |
14
|
|
|
{ |
15
|
|
|
/** @var bool */ |
16
|
|
|
private $optional = false; |
17
|
|
|
|
18
|
|
|
final public static function union(self ...$parameters): self |
19
|
|
|
{ |
20
|
|
|
return new UnionParameter(...$parameters); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
final public static function typed(string $type, $value): self |
24
|
|
|
{ |
25
|
|
|
return new TypedParameter($type, $value); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
final public static function untyped($value): self |
29
|
|
|
{ |
30
|
|
|
return new UntypedParameter($value); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
final public static function factory(callable $factory): ValueFactory |
34
|
|
|
{ |
35
|
|
|
return new ValueFactory($factory); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
final public function optional(): self |
39
|
|
|
{ |
40
|
|
|
$this->optional = true; |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @internal |
47
|
|
|
* |
48
|
|
|
* @return mixed |
49
|
|
|
* |
50
|
|
|
* @throws UnresolveableArgument |
51
|
|
|
*/ |
52
|
|
|
final public function resolve(\ReflectionParameter $parameter) |
53
|
|
|
{ |
54
|
|
|
$value = $this->valueFor($parameter); |
55
|
|
|
|
56
|
|
|
if (!$value instanceof ValueFactory) { |
57
|
|
|
return $value; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$type = $parameter->getType(); |
61
|
|
|
|
62
|
|
|
if (!$type instanceof \ReflectionNamedType) { |
63
|
|
|
return $value(null); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $value($type->getName()); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @internal |
71
|
|
|
*/ |
72
|
|
|
final public function isOptional(): bool |
73
|
|
|
{ |
74
|
|
|
return $this->optional; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
abstract public function type(): string; |
78
|
|
|
|
79
|
|
|
abstract protected function valueFor(\ReflectionParameter $refParameter); |
80
|
|
|
} |
81
|
|
|
|