• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / utils / 21973085139

13 Feb 2026 03:05AM UTC coverage: 93.128% (+0.003%) from 93.125%
21973085139

push

github

dg
made static analysis mandatory

2087 of 2241 relevant lines covered (93.13%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.14
/src/Utils/Type.php
1
<?php
1✔
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\Utils;
11

12
use Nette;
13
use function array_map, array_search, array_splice, array_values, count, explode, implode, is_a, is_resource, is_string, strcasecmp, strtolower, substr, trim;
14

15

16
/**
17
 * PHP type reflection.
18
 */
19
final readonly class Type
20
{
21
        /** @var list<string|self> */
22
        private array $types;
23
        private ?string $singleName;
24
        private string $kind; // | &
25

26

27
        /**
28
         * Creates a Type object based on reflection. Resolves self, static and parent to the actual class name.
29
         * If the subject has no type, it returns null.
30
         */
31
        public static function fromReflection(
1✔
32
                \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $reflection,
33
        ): ?self
34
        {
35
                $type = $reflection instanceof \ReflectionFunctionAbstract
1✔
36
                        ? $reflection->getReturnType() ?? ($reflection instanceof \ReflectionMethod ? $reflection->getTentativeReturnType() : null)
1✔
37
                        : $reflection->getType();
1✔
38

39
                return $type ? self::fromReflectionType($type, $reflection, asObject: true) : null;
1✔
40
        }
41

42

43
        /** @return ($asObject is true ? self : self|string) */
44
        private static function fromReflectionType(
1✔
45
                \ReflectionType $type,
46
                \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $of,
47
                bool $asObject,
48
        ): self|string
49
        {
50
                if ($type instanceof \ReflectionNamedType) {
1✔
51
                        $name = self::resolve($type->getName(), $of);
1✔
52
                        return $asObject
1✔
53
                                ? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name])
1✔
54
                                : $name;
1✔
55

56
                } elseif ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) {
1✔
57
                        return new self(
1✔
58
                                array_map(fn($t) => self::fromReflectionType($t, $of, asObject: false), $type->getTypes()),
1✔
59
                                $type instanceof \ReflectionUnionType ? '|' : '&',
1✔
60
                        );
61

62
                } else {
63
                        throw new Nette\InvalidStateException('Unexpected type of ' . Reflection::toString($of));
×
64
                }
65
        }
66

67

68
        /**
69
         * Creates the Type object according to the text notation.
70
         */
71
        public static function fromString(string $type): self
1✔
72
        {
73
                if (!Validators::isTypeDeclaration($type)) {
1✔
74
                        throw new Nette\InvalidArgumentException("Invalid type '$type'.");
×
75
                }
76

77
                if ($type[0] === '?') {
1✔
78
                        return new self([substr($type, 1), 'null']);
1✔
79
                }
80

81
                $unions = [];
1✔
82
                foreach (explode('|', $type) as $part) {
1✔
83
                        $part = explode('&', trim($part, '()'));
1✔
84
                        $unions[] = count($part) === 1 ? $part[0] : new self($part, '&');
1✔
85
                }
86

87
                return count($unions) === 1 && $unions[0] instanceof self
1✔
88
                        ? $unions[0]
1✔
89
                        : new self($unions);
1✔
90
        }
91

92

93
        /**
94
         * Creates a Type object based on the actual type of value.
95
         */
96
        public static function fromValue(mixed $value): self
1✔
97
        {
98
                $type = get_debug_type($value);
1✔
99
                if (is_resource($value)) {
1✔
100
                        $type = 'mixed';
1✔
101
                } elseif (str_ends_with($type, '@anonymous')) {
1✔
102
                        $parent = substr($type, 0, -10);
1✔
103
                        $type = $parent === 'class' ? 'object' : $parent;
1✔
104
                }
105

106
                return new self([$type]);
1✔
107
        }
108

109

110
        /**
111
         * Resolves 'self', 'static' and 'parent' to the actual class name.
112
         */
113
        public static function resolve(
1✔
114
                string $type,
115
                \ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $of,
116
        ): string
117
        {
118
                $lower = strtolower($type);
1✔
119
                if ($of instanceof \ReflectionFunction) {
1✔
120
                        return $type;
1✔
121
                }
122

123
                $class = $of->getDeclaringClass();
1✔
124
                if ($class === null) {
1✔
125
                        return $type;
1✔
126
                } elseif ($lower === 'self') {
1✔
127
                        return $class->name;
1✔
128
                } elseif ($lower === 'static') {
1✔
129
                        return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $class)->name;
1✔
130
                } elseif ($lower === 'parent' && $class->getParentClass()) {
1✔
131
                        return $class->getParentClass()->name;
1✔
132
                } else {
133
                        return $type;
1✔
134
                }
135
        }
136

137

138
        /** @param  array<string|self>  $types */
139
        private function __construct(array $types, string $kind = '|')
1✔
140
        {
141
                $o = array_search('null', $types, strict: true);
1✔
142
                if ($o !== false) { // null as last
1✔
143
                        array_splice($types, (int) $o, 1);
1✔
144
                        $types[] = 'null';
1✔
145
                }
146

147
                $this->types = array_values($types);
1✔
148
                $this->singleName = is_string($types[0]) && ($types[1] ?? 'null') === 'null' ? $types[0] : null;
1✔
149
                $this->kind = count($types) > 1 ? $kind : '';
1✔
150
        }
1✔
151

152

153
        public function __toString(): string
154
        {
155
                $multi = count($this->types) > 1;
1✔
156
                if ($this->singleName !== null) {
1✔
157
                        return ($multi ? '?' : '') . $this->singleName;
1✔
158
                }
159

160
                $res = [];
1✔
161
                foreach ($this->types as $type) {
1✔
162
                        $res[] = $type instanceof self && $multi ? "($type)" : $type;
1✔
163
                }
164
                return implode($this->kind, $res);
1✔
165
        }
166

167

168
        /**
169
         * Returns a type that accepts both the current type and the given type.
170
         */
171
        public function with(string|self $type): self
1✔
172
        {
173
                $type = is_string($type) ? self::fromString($type) : $type;
1✔
174
                return match (true) {
175
                        $this->allows($type) => $this,
1✔
176
                        $type->allows($this) => $type,
1✔
177
                        default => new self(array_unique(
1✔
178
                                array_merge($this->isIntersection() ? [$this] : $this->types, $type->isIntersection() ? [$type] : $type->types),
1✔
179
                                SORT_REGULAR,
1✔
180
                        ), '|'),
1✔
181
                };
182
        }
183

184

185
        /**
186
         * Returns the array of subtypes that make up the compound type as strings.
187
         * @return list<string|array<string|array<mixed>>>
188
         */
189
        public function getNames(): array
190
        {
191
                return array_map(fn($t) => $t instanceof self ? $t->getNames() : $t, $this->types);
1✔
192
        }
193

194

195
        /**
196
         * Returns the array of subtypes that make up the compound type as Type objects.
197
         * @return list<self>
198
         */
199
        public function getTypes(): array
200
        {
201
                return array_map(fn($t) => $t instanceof self ? $t : new self([$t]), $this->types);
1✔
202
        }
203

204

205
        /**
206
         * Returns the type name for simple types, otherwise null.
207
         */
208
        public function getSingleName(): ?string
209
        {
210
                return $this->singleName;
1✔
211
        }
212

213

214
        /**
215
         * Returns true whether it is a union type.
216
         */
217
        public function isUnion(): bool
218
        {
219
                return $this->kind === '|';
1✔
220
        }
221

222

223
        /**
224
         * Returns true whether it is an intersection type.
225
         */
226
        public function isIntersection(): bool
227
        {
228
                return $this->kind === '&';
1✔
229
        }
230

231

232
        /**
233
         * Returns true whether it is a simple type. Single nullable types are also considered to be simple types.
234
         */
235
        public function isSimple(): bool
236
        {
237
                return $this->singleName !== null;
1✔
238
        }
239

240

241
        #[\Deprecated('use isSimple()')]
242
        public function isSingle(): bool
243
        {
244
                return $this->singleName !== null;
×
245
        }
246

247

248
        /**
249
         * Returns true whether the type is both a simple and a PHP built-in type.
250
         */
251
        public function isBuiltin(): bool
252
        {
253
                return $this->singleName !== null && Validators::isBuiltinType($this->singleName);
1✔
254
        }
255

256

257
        /**
258
         * Returns true whether the type is both a simple and a class name.
259
         */
260
        public function isClass(): bool
261
        {
262
                return $this->singleName !== null && !Validators::isBuiltinType($this->singleName);
1✔
263
        }
264

265

266
        /**
267
         * Determines if type is special class name self/parent/static.
268
         */
269
        public function isClassKeyword(): bool
270
        {
271
                return $this->singleName !== null && Validators::isClassKeyword($this->singleName);
1✔
272
        }
273

274

275
        /**
276
         * Verifies type compatibility. For example, it checks if a value of a certain type could be passed as a parameter.
277
         */
278
        public function allows(string|self $type): bool
1✔
279
        {
280
                if ($this->types === ['mixed']) {
1✔
281
                        return true;
1✔
282
                }
283

284
                $type = is_string($type) ? self::fromString($type) : $type;
1✔
285
                return $type->isUnion()
1✔
286
                        ? Arrays::every($type->types, fn($t) => $this->allowsAny($t instanceof self ? $t->types : [$t]))
1✔
287
                        : $this->allowsAny($type->types);
1✔
288
        }
289

290

291
        /** @param array<string>  $givenTypes */
292
        private function allowsAny(array $givenTypes): bool
1✔
293
        {
294
                return $this->isUnion()
1✔
295
                        ? Arrays::some($this->types, fn($t) => $this->allowsAll($t instanceof self ? $t->types : [$t], $givenTypes))
1✔
296
                        : $this->allowsAll($this->types, $givenTypes);
1✔
297
        }
298

299

300
        /**
301
         * @param array<string>  $ourTypes
302
         * @param array<string>  $givenTypes
303
         */
304
        private function allowsAll(array $ourTypes, array $givenTypes): bool
1✔
305
        {
306
                return Arrays::every(
1✔
307
                        $ourTypes,
1✔
308
                        fn(string $ourType) => Arrays::some(
1✔
309
                                $givenTypes,
1✔
310
                                fn(string $givenType) => Validators::isBuiltinType($ourType)
1✔
311
                                        ? strcasecmp($ourType, $givenType) === 0
1✔
312
                                        : is_a($givenType, $ourType, allow_string: true),
1✔
313
                        ),
1✔
314
                );
315
        }
316
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc