Passed
Pull Request — 1.x (#2)
by Kevin
01:11
created

Argument::types()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Zenstruck\Callback;
4
5
/**
6
 * @author Kevin Bond <[email protected]>
7
 */
8
final class Argument
9
{
10
    /** @var \ReflectionNamedType[] */
11
    private $types = [];
12
13
    public function __construct(\ReflectionParameter $parameter)
14
    {
15
        if (!$type = $parameter->getType()) {
16
            return;
17
        }
18
19
        if ($type instanceof \ReflectionNamedType) {
20
            $this->types = [$type];
21
22
            return;
23
        }
24
25
        /** @var \ReflectionUnionType $type */
26
        $this->types = $type->getTypes();
27
    }
28
29
    public function type(): ?string
30
    {
31
        return $this->hasType() ? \implode('|', $this->types()) : null;
32
    }
33
34
    /**
35
     * @return string[]
36
     */
37
    public function types(): array
38
    {
39
        return \array_map(static function(\ReflectionNamedType $type) { return $type->getName(); }, $this->types);
40
    }
41
42
    public function hasType(): bool
43
    {
44
        return !empty($this->types);
45
    }
46
47
    public function isUnionType(): bool
48
    {
49
        return \count($this->types) > 1;
50
    }
51
52
    public function supports(string $type): bool
53
    {
54
        if (!$this->hasType()) {
55
            // no type-hint so any type is supported
56
            return true;
57
        }
58
59
        foreach ($this->types() as $t) {
60
            if ($t === $type || \is_a($t, $type, true)) {
61
                return true;
62
            }
63
        }
64
65
        return false;
66
    }
67
}
68