From f41ce8324dc501109c6b839bd6ec9c5a1dc44994 Mon Sep 17 00:00:00 2001 From: Guy Sartorelli Date: Wed, 19 Mar 2025 16:25:56 +1300 Subject: [PATCH] Fix typehint resolution - stop prefixing unions with namespace --- src/Parser/NodeVisitor.php | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/src/Parser/NodeVisitor.php b/src/Parser/NodeVisitor.php index e974b6d7..5d38b720 100644 --- a/src/Parser/NodeVisitor.php +++ b/src/Parser/NodeVisitor.php @@ -165,6 +165,30 @@ protected function addFunction(FunctionNode $node, ?string $namespace = null) } } + /** + * @param \PhpParser\Node\ComplexType|\PhpParser\Node\Identifier|\PhpParser\Node\Name|NullableType|UnionType|IntersectionType|null $type Type declaration + */ + protected function typeToArray($type): array + { + $typeArray = []; + if ($type !== null && ! ($type instanceof NullableType || $type instanceof UnionType || $type instanceof IntersectionType)) { + $typeAsStr = $type->__toString(); + if ($type instanceof FullyQualified && 0 !== strpos($typeAsStr, '\\')) { + $typeAsStr = '\\' . $typeAsStr; + } + $typeArray[] = [$typeAsStr, false]; + } elseif ($type instanceof NullableType) { + $typeArray = array_merge($typeArray, $this->typeToArray($type->type)); + $typeArray[] = ['null', false]; + } elseif ($type instanceof UnionType || $type instanceof IntersectionType) { + foreach ($type->types as $subType) { + $typeArray = array_merge($typeArray, $this->typeToArray($subType)); + } + } + + return $typeArray; + } + /** * @param \PhpParser\Node\ComplexType|\PhpParser\Node\Identifier|\PhpParser\Node\Name|NullableType|UnionType|IntersectionType|null $type Type declaration */ @@ -439,20 +463,14 @@ protected function manageHint($type, Reflection $object): void $typeArr = []; foreach ($type->types as $type) { - $typeStr = $this->typeToString($type); - $typeArr[] = [$typeStr, false]; + $typeArr = array_merge($typeArr, $this->typeToArray($type)); } $object->setHint($this->resolveHint($typeArr)); } else { - $typeStr = $this->typeToString($type); - - if (null !== $typeStr) { - $typeArr = [[$typeStr, false]]; + $typeArr = $this->typeToArray($type); - if ($type instanceof NullableType) { - $typeArr[] = ['null', false]; - } + if (!empty($typeArr)) { $object->setHint($this->resolveHint($typeArr)); } }