Debian Codegraph @

vendor/symfony/type-info/TypeResolver/StringTypeResolver.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\TypeInfo\TypeResolver;
13
14 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprArrayNode;
15 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFalseNode;
16 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprFloatNode;
17 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprIntegerNode;
18 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNullNode;
19 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
20 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprTrueNode;
21 use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode;
22 use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
23 use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
24 use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
25 use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
26 use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
27 use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
28 use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
29 use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
30 use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
31 use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
32 use PHPStan\PhpDocParser\Ast\Type\TypeNode;
33 use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
34 use PHPStan\PhpDocParser\Lexer\Lexer;
35 use PHPStan\PhpDocParser\Parser\ConstExprParser;
36 use PHPStan\PhpDocParser\Parser\TokenIterator;
37 use PHPStan\PhpDocParser\Parser\TypeParser;
38 use PHPStan\PhpDocParser\ParserConfig;
39 use Symfony\Component\TypeInfo\Exception\InvalidArgumentException;
40 use Symfony\Component\TypeInfo\Exception\UnsupportedException;
41 use Symfony\Component\TypeInfo\Type;
42 use Symfony\Component\TypeInfo\Type\BackedEnumType;
43 use Symfony\Component\TypeInfo\Type\BuiltinType;
44 use Symfony\Component\TypeInfo\Type\CollectionType;
45 use Symfony\Component\TypeInfo\Type\GenericType;
46 use Symfony\Component\TypeInfo\Type\ObjectType;
47 use Symfony\Component\TypeInfo\TypeContext\TypeContext;
48 use Symfony\Component\TypeInfo\TypeIdentifier;
49
50 /**
51 * Resolves type for a given string.
52 *
53 * @author Mathias Arlaud <[email protected]>
54 * @author Baptiste Leduc <[email protected]>
55 */
56 final class StringTypeResolver implements TypeResolverInterface
57 {
58 /**
59 * @var array<string, bool>
60 */
61 private static array $classExistCache = [];
62
63 private readonly Lexer $lexer;
64 private readonly TypeParser $parser;
65
66 /**
67 * @param array<string, string> $extraTypeAliases
68 */
69 public function __construct(
70 ?Lexer $lexer = null,
71 ?TypeParser $parser = null,
72 private readonly array $extraTypeAliases = [],
73 ) {
74 if (class_exists(ParserConfig::class)) {
75 $this->lexer = $lexer ?? new Lexer(new ParserConfig([]));
76 $this->parser = $parser ?? new TypeParser($config = new ParserConfig([]), new ConstExprParser($config));
77 } else {
78 $this->lexer = $lexer ?? new Lexer();
79 $this->parser = $parser ?? new TypeParser(new ConstExprParser());
80 }
81 }
82
83 public function resolve(mixed $subject, ?TypeContext $typeContext = null): Type
84 {
85 if ($subject instanceof \Stringable) {
86 $subject = (string) $subject;
87 } elseif (!\is_string($subject)) {
88 throw new UnsupportedException(\sprintf('Expected subject to be a "string", "%s" given.', get_debug_type($subject)), $subject);
89 }
90
91 try {
92 $tokens = new TokenIterator($this->lexer->tokenize($subject));
93 $node = $this->parser->parse($tokens);
94
95 return $this->getTypeFromNode($node, $typeContext);
96 } catch (\DomainException $e) {
97 throw new UnsupportedException(\sprintf('Cannot resolve "%s".', $subject), $subject, previous: $e);
98 }
99 }
100
101 private function getTypeFromNode(TypeNode $node, ?TypeContext $typeContext): Type
102 {
103 $typeIsCollectionObject = static fn (Type $type): bool => $type->isIdentifiedBy(\Traversable::class) || $type->isIdentifiedBy(\ArrayAccess::class);
104
105 if ($node instanceof CallableTypeNode) {
106 return Type::callable();
107 }
108
109 if ($node instanceof ArrayTypeNode) {
110 return Type::array($this->getTypeFromNode($node->type, $typeContext));
111 }
112
113 if ($node instanceof ArrayShapeNode) {
114 $shape = [];
115 foreach ($node->items as $item) {
116 $shape[(string) $item->keyName] = [
117 'type' => $this->getTypeFromNode($item->valueType, $typeContext),
118 'optional' => $item->optional,
119 ];
120 }
121
122 return Type::arrayShape(
123 $shape,
124 $node->sealed,
125 $node->unsealedType?->keyType ? $this->getTypeFromNode($node->unsealedType->keyType, $typeContext) : null,
126 $node->unsealedType?->valueType ? $this->getTypeFromNode($node->unsealedType->valueType, $typeContext) : null,
127 );
128 }
129
130 if ($node instanceof ObjectShapeNode) {
131 return Type::object();
132 }
133
134 if ($node instanceof ThisTypeNode) {
135 if (null === $typeContext) {
136 throw new InvalidArgumentException(\sprintf('A "%s" must be provided to resolve "$this".', TypeContext::class));
137 }
138
139 return Type::object($typeContext->getCalledClass());
140 }
141
142 if ($node instanceof ConstTypeNode) {
143 if ($node->constExpr instanceof ConstFetchNode) {
144 $className = match (strtolower($node->constExpr->className)) {
145 'self' => $typeContext->getDeclaringClass(),
146 'static' => $typeContext->getCalledClass(),
147 'parent' => $typeContext->getParentClass(),
148 default => null,
149 };
150
151 if (null === $className) {
152 $classType = $this->resolveCustomIdentifier($node->constExpr->className, $typeContext);
153 if (!$classType instanceof ObjectType) {
154 return Type::mixed();
155 }
156
157 $className = $classType->getClassName();
158 }
159
160 if (!class_exists($className)) {
161 return Type::mixed();
162 }
163
164 $types = [];
165
166 foreach ((new \ReflectionClass($className))->getReflectionConstants() as $const) {
167 if (preg_match('/^'.str_replace('\*', '.*', preg_quote($node->constExpr->name, '/')).'$/', $const->getName())) {
168 $types[] = Type::fromValue($const->getValue());
169 }
170 }
171
172 return CollectionType::mergeCollectionValueTypes($types);
173 }
174
175 return match ($node->constExpr::class) {
176 ConstExprArrayNode::class => Type::array(),
177 ConstExprFalseNode::class => Type::false(),
178 ConstExprFloatNode::class => Type::float(),
179 ConstExprIntegerNode::class => Type::int(),
180 ConstExprNullNode::class => Type::null(),
181 ConstExprStringNode::class => Type::string(),
182 ConstExprTrueNode::class => Type::true(),
183 default => throw new \DomainException(\sprintf('Unhandled "%s" constant expression.', $node->constExpr::class)),
184 };
185 }
186
187 if ($node instanceof IdentifierTypeNode) {
188 $type = match ($node->name) {
189 'bool', 'boolean' => Type::bool(),
190 'true' => Type::true(),
191 'false' => Type::false(),
192 'int', 'integer', 'positive-int', 'negative-int', 'non-positive-int', 'non-negative-int', 'non-zero-int' => Type::int(),
193 'float', 'double' => Type::float(),
194 'string',
195 'class-string',
196 'trait-string',
197 'interface-string',
198 'callable-string',
199 'numeric-string',
200 'lowercase-string',
201 'non-empty-lowercase-string',
202 'non-empty-string',
203 'non-falsy-string',
204 'truthy-string',
205 'literal-string',
206 'html-escaped-string' => Type::string(),
207 'resource' => Type::resource(),
208 'object' => Type::object(),
209 'callable' => Type::callable(),
210 'array', 'non-empty-array' => Type::array(),
211 'list', 'non-empty-list' => Type::list(),
212 'iterable' => Type::iterable(),
213 'mixed' => Type::mixed(),
214 'null' => Type::null(),
215 'array-key' => Type::arrayKey(),
216 'scalar' => Type::union(Type::int(), Type::float(), Type::string(), Type::bool()),
217 'number' => Type::union(Type::int(), Type::float()),
218 'numeric' => Type::union(Type::int(), Type::float(), Type::string()),
219 'self' => $typeContext ? Type::object($typeContext->getDeclaringClass()) : throw new InvalidArgumentException(\sprintf('A "%s" must be provided to resolve "self".', TypeContext::class)),
220 'static' => $typeContext ? Type::object($typeContext->getCalledClass()) : throw new InvalidArgumentException(\sprintf('A "%s" must be provided to resolve "static".', TypeContext::class)),
221 'parent' => $typeContext ? Type::object($typeContext->getParentClass()) : throw new InvalidArgumentException(\sprintf('A "%s" must be provided to resolve "parent".', TypeContext::class)),
222 'void' => Type::void(),
223 'never', 'never-return', 'never-returns', 'no-return' => Type::never(),
224 default => $this->resolveCustomIdentifier($node->name, $typeContext),
225 };
226
227 if ($typeIsCollectionObject($type)) {
228 return Type::collection($type);
229 }
230
231 return $type;
232 }
233
234 if ($node instanceof NullableTypeNode) {
235 return Type::nullable($this->getTypeFromNode($node->type, $typeContext));
236 }
237
238 if ($node instanceof GenericTypeNode) {
239 if ($node->type instanceof IdentifierTypeNode && 'value-of' === $node->type->name) {
240 $type = $this->getTypeFromNode($node->genericTypes[0], $typeContext);
241 if ($type instanceof BackedEnumType) {
242 return $type->getBackingType();
243 }
244
245 if ($type instanceof CollectionType) {
246 return $type->getCollectionValueType();
247 }
248
249 throw new \DomainException(\sprintf('"%s" is not a valid type for "value-of".', $node->genericTypes[0]));
250 }
251
252 if ($node->type instanceof IdentifierTypeNode && 'key-of' === $node->type->name) {
253 $type = $this->getTypeFromNode($node->genericTypes[0], $typeContext);
254 if ($type instanceof CollectionType) {
255 return $type->getCollectionKeyType();
256 }
257
258 throw new \DomainException(\sprintf('"%s" is not a valid type for "key-of".', $node->genericTypes[0]));
259 }
260
261 $type = $this->getTypeFromNode($node->type, $typeContext);
262
263 // handle integer ranges as simple integers
264 if ($type->isIdentifiedBy(TypeIdentifier::INT)) {
265 return $type;
266 }
267
268 $variableTypes = array_map(fn (TypeNode $t): Type => $this->getTypeFromNode($t, $typeContext), $node->genericTypes);
269
270 if ($type instanceof CollectionType) {
271 $asList = $type->isList();
272 $keyType = $type->getCollectionKeyType();
273 $type = $type->getWrappedType();
274
275 if ($type instanceof GenericType) {
276 $type = $type->getWrappedType();
277 }
278
279 if (1 === \count($variableTypes)) {
280 return new CollectionType(Type::generic($type, $keyType, $variableTypes[0]), $asList);
281 } elseif (2 === \count($variableTypes)) {
282 if ($asList) {
283 throw new \DomainException(\sprintf('"%s" type cannot have a key type defined.', $node->type));
284 }
285
286 return Type::collection($type, $variableTypes[1], $variableTypes[0], $asList);
287 }
288 }
289
290 if ($typeIsCollectionObject($type)) {
291 return match (\count($variableTypes)) {
292 1 => Type::collection($type, $variableTypes[0]),
293 2 => Type::collection($type, $variableTypes[1], $variableTypes[0]),
294 default => Type::collection($type),
295 };
296 }
297
298 if ($type instanceof BuiltinType && TypeIdentifier::ARRAY !== $type->getTypeIdentifier() && TypeIdentifier::ITERABLE !== $type->getTypeIdentifier()) {
299 return $type;
300 }
301
302 return Type::generic($type, ...$variableTypes);
303 }
304
305 if ($node instanceof UnionTypeNode) {
306 $types = [];
307
308 foreach ($node->types as $nodeType) {
309 $type = $this->getTypeFromNode($nodeType, $typeContext);
310
311 if ($type instanceof BuiltinType && TypeIdentifier::MIXED === $type->getTypeIdentifier()) {
312 return Type::mixed();
313 }
314
315 $types[] = $type;
316 }
317
318 return Type::union(...$types);
319 }
320
321 if ($node instanceof IntersectionTypeNode) {
322 return Type::intersection(...array_map(fn (TypeNode $t): Type => $this->getTypeFromNode($t, $typeContext), $node->types));
323 }
324
325 throw new \DomainException(\sprintf('Unhandled "%s" node.', $node::class));
326 }
327
328 private function resolveCustomIdentifier(string $identifier, ?TypeContext $typeContext): Type
329 {
330 $className = $typeContext ? $typeContext->normalize($identifier) : $identifier;
331
332 if (!isset(self::$classExistCache[$className])) {
333 self::$classExistCache[$className] = false;
334
335 if (class_exists($className) || interface_exists($className)) {
336 self::$classExistCache[$className] = true;
337 } else {
338 try {
339 new \ReflectionClass($className);
340 self::$classExistCache[$className] = true;
341 } catch (\Throwable) {
342 }
343 }
344 }
345
346 if (self::$classExistCache[$className]) {
347 if (is_subclass_of($className, \UnitEnum::class) && !interface_exists($className)) {
348 return Type::enum($className);
349 }
350
351 return Type::object($className);
352 }
353
354 if (isset($typeContext?->templates[$identifier])) {
355 return Type::template($identifier, $typeContext->templates[$identifier]);
356 }
357
358 if (isset($typeContext?->typeAliases[$identifier])) {
359 return $typeContext->typeAliases[$identifier];
360 }
361
362 if (isset($this->extraTypeAliases[$identifier])) {
363 return $this->resolve($this->extraTypeAliases[$identifier]);
364 }
365
366 throw new \DomainException(\sprintf('Unhandled "%s" identifier.', $identifier));
367 }
368 }