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

nette / utils / 21938400483

12 Feb 2026 08:03AM UTC coverage: 93.193% (-0.2%) from 93.429%
21938400483

push

github

dg
added CLAUDE.md

2081 of 2233 relevant lines covered (93.19%)

0.93 hits per line

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

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

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

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

66

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

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

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

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

91

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

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

108

109
        /**
110
         * Resolves 'self', 'static' and 'parent' to the actual class name.
111
         */
112
        public static function resolve(
1✔
113
                string $type,
114
                \ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $of,
115
        ): string
116
        {
117
                $lower = strtolower($type);
1✔
118
                if ($of instanceof \ReflectionFunction) {
1✔
119
                        return $type;
1✔
120
                } elseif ($lower === 'self') {
1✔
121
                        return $of->getDeclaringClass()->name;
1✔
122
                } elseif ($lower === 'static') {
1✔
123
                        return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $of->getDeclaringClass())->name;
1✔
124
                } elseif ($lower === 'parent' && $of->getDeclaringClass()->getParentClass()) {
1✔
125
                        return $of->getDeclaringClass()->getParentClass()->name;
1✔
126
                } else {
127
                        return $type;
1✔
128
                }
129
        }
130

131

132
        /** @param  array<string|self>  $types */
133
        private function __construct(array $types, string $kind = '|')
1✔
134
        {
135
                $o = array_search('null', $types, strict: true);
1✔
136
                if ($o !== false) { // null as last
1✔
137
                        array_splice($types, (int) $o, 1);
1✔
138
                        $types[] = 'null';
1✔
139
                }
140

141
                $this->types = array_values($types);
1✔
142
                $this->singleName = is_string($types[0]) && ($types[1] ?? 'null') === 'null' ? $types[0] : null;
1✔
143
                $this->kind = count($types) > 1 ? $kind : '';
1✔
144
        }
1✔
145

146

147
        public function __toString(): string
148
        {
149
                $multi = count($this->types) > 1;
1✔
150
                if ($this->singleName !== null) {
1✔
151
                        return ($multi ? '?' : '') . $this->singleName;
1✔
152
                }
153

154
                $res = [];
1✔
155
                foreach ($this->types as $type) {
1✔
156
                        $res[] = $type instanceof self && $multi ? "($type)" : $type;
1✔
157
                }
158
                return implode($this->kind, $res);
1✔
159
        }
160

161

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

178

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

188

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

198

199
        /**
200
         * Returns the type name for simple types, otherwise null.
201
         */
202
        public function getSingleName(): ?string
203
        {
204
                return $this->singleName;
1✔
205
        }
206

207

208
        /**
209
         * Returns true whether it is a union type.
210
         */
211
        public function isUnion(): bool
212
        {
213
                return $this->kind === '|';
1✔
214
        }
215

216

217
        /**
218
         * Returns true whether it is an intersection type.
219
         */
220
        public function isIntersection(): bool
221
        {
222
                return $this->kind === '&';
1✔
223
        }
224

225

226
        /**
227
         * Returns true whether it is a simple type. Single nullable types are also considered to be simple types.
228
         */
229
        public function isSimple(): bool
230
        {
231
                return $this->singleName !== null;
1✔
232
        }
233

234

235
        #[\Deprecated('use isSimple()')]
236
        public function isSingle(): bool
237
        {
238
                return $this->singleName !== null;
×
239
        }
240

241

242
        /**
243
         * Returns true whether the type is both a simple and a PHP built-in type.
244
         */
245
        public function isBuiltin(): bool
246
        {
247
                return $this->singleName !== null && Validators::isBuiltinType($this->singleName);
1✔
248
        }
249

250

251
        /**
252
         * Returns true whether the type is both a simple and a class name.
253
         */
254
        public function isClass(): bool
255
        {
256
                return $this->singleName !== null && !Validators::isBuiltinType($this->singleName);
1✔
257
        }
258

259

260
        /**
261
         * Determines if type is special class name self/parent/static.
262
         */
263
        public function isClassKeyword(): bool
264
        {
265
                return $this->singleName !== null && Validators::isClassKeyword($this->singleName);
1✔
266
        }
267

268

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

278
                $type = is_string($type) ? self::fromString($type) : $type;
1✔
279
                return $type->isUnion()
1✔
280
                        ? Arrays::every($type->types, fn($t) => $this->allowsAny($t instanceof self ? $t->types : [$t]))
1✔
281
                        : $this->allowsAny($type->types);
1✔
282
        }
283

284

285
        /** @param array<string>  $givenTypes */
286
        private function allowsAny(array $givenTypes): bool
1✔
287
        {
288
                return $this->isUnion()
1✔
289
                        ? Arrays::some($this->types, fn($t) => $this->allowsAll($t instanceof self ? $t->types : [$t], $givenTypes))
1✔
290
                        : $this->allowsAll($this->types, $givenTypes);
1✔
291
        }
292

293

294
        /**
295
         * @param array<string>  $ourTypes
296
         * @param array<string>  $givenTypes
297
         */
298
        private function allowsAll(array $ourTypes, array $givenTypes): bool
1✔
299
        {
300
                return Arrays::every(
1✔
301
                        $ourTypes,
1✔
302
                        fn(string $ourType) => Arrays::some(
1✔
303
                                $givenTypes,
1✔
304
                                fn(string $givenType) => Validators::isBuiltinType($ourType)
1✔
305
                                        ? strcasecmp($ourType, $givenType) === 0
1✔
306
                                        : is_a($givenType, $ourType, allow_string: true),
1✔
307
                        ),
1✔
308
                );
309
        }
310
}
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