Passed
Pull Request — 1.x (#3)
by Kevin
01:31
created

Argument::isUnionType()   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
    /**
11
     * Allow exact type (always enabled).
12
     */
13
    public const EXACT = 0;
14
15
    /**
16
     * If type is class, parent classes are supported.
17
     */
18
    public const COVARIANCE = 2;
19
20
    /**
21
     * If type is class, child classes are supported.
22
     */
23
    public const CONTRAVARIANCE = 4;
24
25
    /**
26
     * If type is string, do not support other scalar types. Follows
27
     * same logic as "declare(strict_types=1)".
28
     */
29
    public const STRICT = 8;
30
31
    /**
32
     * If type is float, do not support int (implies {@see STRICT).
33
     */
34
    public const VERY_STRICT = 16;
35
36
    private const TYPE_NORMALIZE_MAP = [
37
        'boolean' => 'bool',
38
        'integer' => 'int',
39
        'double' => 'float',
40
        'resource (closed)' => 'resource',
41
    ];
42
43
    private const ALLOWED_TYPE_MAP = [
44
        'string' => ['bool', 'int', 'float'],
45
        'bool' => ['string', 'int', 'float'],
46
        'float' => ['string', 'int', 'bool'],
47
        'int' => ['string', 'float', 'bool'],
48
    ];
49
50
    /** @var \ReflectionParameter */
51
    private $parameter;
52
53
    public function __construct(\ReflectionParameter $parameter)
54
    {
55
        $this->parameter = $parameter;
56
    }
57
58
    public function type(): ?string
59
    {
60
        return $this->hasType() ? \implode('|', $this->types()) : null;
61
    }
62
63
    /**
64
     * @return string[]
65
     */
66
    public function types(): array
67
    {
68
        return \array_map(static function(\ReflectionNamedType $type) { return $type->getName(); }, $this->reflectionTypes());
69
    }
70
71
    public function hasType(): bool
72
    {
73
        return !empty($this->types());
74
    }
75
76
    public function isUnionType(): bool
77
    {
78
        return \count($this->types()) > 1;
79
    }
80
81
    /**
82
     * @param string $type    The type to check if this argument supports
83
     * @param int    $options {@see EXACT}, {@see COVARIANCE}, {@see CONTRAVARIANCE}
84
     *                        Bitwise disjunction of above is allowed
85
     */
86
    public function supports(string $type, int $options = self::EXACT|self::COVARIANCE): bool
87
    {
88
        if (!$this->hasType()) {
89
            // no type-hint so any type is supported
90
            return true;
91
        }
92
93
        if ('null' === \mb_strtolower($type) && $this->parameter->allowsNull()) {
94
            return true;
95
        }
96
97
        $type = self::TYPE_NORMALIZE_MAP[$type] ?? $type;
98
99
        foreach ($this->types() as $supportedType) {
100
            if ($supportedType === $type) {
101
                return true;
102
            }
103
104
            if ($options & self::COVARIANCE && \is_a($type, $supportedType, true)) {
105
                return true;
106
            }
107
108
            if ($options & self::CONTRAVARIANCE && \is_a($supportedType, $type, true)) {
109
                return true;
110
            }
111
112
            if ($options & self::VERY_STRICT) {
113
                continue;
114
            }
115
116
            if ('float' === $supportedType && 'int' === $type) {
117
                // strict typing allows int to pass a float validation
118
                return true;
119
            }
120
121
            if ($options & self::STRICT) {
122
                continue;
123
            }
124
125
            if (\in_array($type, self::ALLOWED_TYPE_MAP[$supportedType] ?? [], true)) {
126
                return true;
127
            }
128
129
            if (\method_exists($type, '__toString')) {
130
                return true;
131
            }
132
        }
133
134
        return false;
135
    }
136
137
    /**
138
     * @param mixed $value
139
     * @param bool  $strict {@see STRICT}
140
     */
141
    public function allows($value, bool $strict = false): bool
142
    {
143
        if (!$this->hasType()) {
144
            // no type-hint so any type is supported
145
            return true;
146
        }
147
148
        $type = \is_object($value) ? \get_class($value) : \gettype($value);
149
        $type = self::TYPE_NORMALIZE_MAP[$type] ?? $type;
150
        $options = $strict ? self::EXACT|self::COVARIANCE|self::STRICT : self::EXACT|self::COVARIANCE;
151
        $supports = $this->supports($type, $options);
152
153
        if (!$supports) {
154
            return false;
155
        }
156
157
        if ('string' === $type && !\is_numeric($value) && !\in_array('string', $this->types(), true)) {
158
            // non-numeric strings cannot be used for float/int
159
            return false;
160
        }
161
162
        return true;
163
    }
164
165
    /**
166
     * @return \ReflectionNamedType[]
167
     */
168
    private function reflectionTypes(): array
169
    {
170
        if (!$type = $this->parameter->getType()) {
171
            return [];
172
        }
173
174
        if ($type instanceof \ReflectionNamedType) {
175
            return [$type];
176
        }
177
178
        /** @var \ReflectionUnionType $type */
179
        return $type->getTypes();
180
    }
181
}
182