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

nette / utils / 21934836766

12 Feb 2026 05:29AM UTC coverage: 93.429% (+0.01%) from 93.415%
21934836766

push

github

dg
added CLAUDE.md

2076 of 2222 relevant lines covered (93.43%)

0.93 hits per line

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

97.12
/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, 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 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
        /**
44
         * @param  \ReflectionFunction|\ReflectionMethod|\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, $o, 1);
1✔
138
                        $types[] = 'null';
1✔
139
                }
140

141
                $this->types = $types;
1✔
142
                $this->simple = is_string($types[0]) && ($types[1] ?? 'null') === '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->simple) {
1✔
151
                        return ($multi ? '?' : '') . $this->types[0];
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_values(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_values(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->simple
1✔
205
                        ? $this->types[0]
1✔
206
                        : null;
1✔
207
        }
208

209

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

218

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

227

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

236

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

243

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

252

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

261

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

270

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

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

286

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

295

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