How to read custom class annotation in extension #4403
-
In custom return type extension i need to read custom annotation from class but I was not able to figure out how to do it. I get called type like this: which references class or interface which should have So I need to get value ("someClass") from this annotation and resolve it to FQN of class so I can create ObjectType. Any help would be appreciated. Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I'd do something like this: $classNames = TypeUtils::getDirectClassNames($calledOnType);
foreach ($classNames as $className) {
if (!$this->reflectionProvider->hasClass($className)) { // inject "PHPStan\Reflection\ReflectionProvider" in the constructor
continue;
}
$classReflection = $this->reflectionProvider->getClass($className);
$phpDoc = $classReflection->getResolvedPhpDoc();
if ($phpDoc === null) {
continue;
}
// there's `$phpDoc->getPhpDocNodes()`, an array of PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode objects
// it's an array because of complexities related to implicit phpDoc inheritance from parent methods etc.
// you should be able to get your tag on PhpDocNode easily, it's gonna be PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode most likely
} This needs dev-master because of these changes: |
Beta Was this translation helpful? Give feedback.
-
I managet to get it to work except last issue. I was not able to figure aut how to translate class name to FQN if Annotation used just short class name. I originally thought $scope->getType would do it (but int needs Expr and I have only string) or that I can use TypeStringResolver but I do not know how to correctly get/ceate NameScope to pass as 2nd argument. |
Beta Was this translation helpful? Give feedback.
I'd do something like this: