Passed
Push — 1.x ( ac6076...be1e2f )
by Kevin
01:10
created

Parameter::isOptional()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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