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

nette / utils / 21636962765

03 Feb 2026 03:39PM UTC coverage: 93.312% (+0.05%) from 93.264%
21636962765

push

github

dg
added CLAUDE.md

2065 of 2213 relevant lines covered (93.31%)

0.93 hits per line

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

97.09
/src/Utils/Type.php
1
<?php
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, 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 array<int, string|self> */
22
        private array $types;
23
        private bool $simple;
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
        /** @param  \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty  $of */
44
        private static function fromReflectionType(\ReflectionType $type, $of, bool $asObject): self|string
1✔
45
        {
46
                if ($type instanceof \ReflectionNamedType) {
1✔
47
                        $name = self::resolve($type->getName(), $of);
1✔
48
                        return $asObject
1✔
49
                                ? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name])
1✔
50
                                : $name;
1✔
51

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

58
                } else {
59
                        throw new Nette\InvalidStateException('Unexpected type of ' . Reflection::toString($of));
×
60
                }
61
        }
62

63

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

73
                if ($type[0] === '?') {
1✔
74
                        return new self([substr($type, 1), 'null']);
1✔
75
                }
76

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

83
                return count($unions) === 1 && $unions[0] instanceof self
1✔
84
                        ? $unions[0]
1✔
85
                        : new self($unions);
1✔
86
        }
87

88

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

102
                return new self([$type]);
1✔
103
        }
104

105

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

128

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

138
                $this->types = $types;
1✔
139
                $this->simple = is_string($types[0]) && ($types[1] ?? 'null') === 'null';
1✔
140
                $this->kind = count($types) > 1 ? $kind : '';
1✔
141
        }
1✔
142

143

144
        public function __toString(): string
145
        {
146
                $multi = count($this->types) > 1;
1✔
147
                if ($this->simple) {
1✔
148
                        return ($multi ? '?' : '') . $this->types[0];
1✔
149
                }
150

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

158

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

175

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

185

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

195

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

206

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

215

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

224

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

233

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

240

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

249

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

258

259
        /**
260
         * Determines if type is special class name self/parent/static.
261
         */
262
        public function isClassKeyword(): bool
263
        {
264
                return $this->simple && Validators::isClassKeyword($this->types[0]);
1✔
265
        }
266

267

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

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

283

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

292

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