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

nette / utils / 20431395313

22 Dec 2025 12:06PM UTC coverage: 93.164% (+71.8%) from 21.324%
20431395313

push

github

dg
Html::addText() accepts int|null for back compatibility [Closes #332][Closes #333]

1 of 1 new or added line in 1 file covered. (100.0%)

140 existing lines in 15 files now uncovered.

2058 of 2209 relevant lines covered (93.16%)

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
        private static function fromReflectionType(\ReflectionType $type, $of, bool $asObject): self|string
1✔
44
        {
45
                if ($type instanceof \ReflectionNamedType) {
1✔
46
                        $name = self::resolve($type->getName(), $of);
1✔
47
                        return $asObject
1✔
48
                                ? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name])
1✔
49
                                : $name;
1✔
50

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

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

62

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

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

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

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

87

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

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

104

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

127

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

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

141

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

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

156

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

173

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

183

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

193

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

204

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

213

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

222

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

231

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

238

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

247

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

256

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

265

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

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

281

282
        private function allowsAny(array $givenTypes): bool
1✔
283
        {
284
                return $this->isUnion()
1✔
285
                        ? Arrays::some($this->types, fn($t) => $this->allowsAll($t instanceof self ? $t->types : [$t], $givenTypes))
1✔
286
                        : $this->allowsAll($this->types, $givenTypes);
1✔
287
        }
288

289

290
        private function allowsAll(array $ourTypes, array $givenTypes): bool
1✔
291
        {
292
                return Arrays::every(
1✔
293
                        $ourTypes,
1✔
294
                        fn($ourType) => Arrays::some(
1✔
295
                                $givenTypes,
1✔
296
                                fn($givenType) => Validators::isBuiltinType($ourType)
1✔
297
                                        ? strcasecmp($ourType, $givenType) === 0
1✔
298
                                        : is_a($givenType, $ourType, allow_string: true),
1✔
299
                        ),
1✔
300
                );
301
        }
302
}
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

© 2025 Coveralls, Inc