Unfortunately, we still need doc comments for certain types like arrays to provide better hints for IDEs and static code analysis tools like PHPStan. Therefor it would be useful to pass a string containing a DocComment to MethodGenerator
and PropertyGenerator
.
As a workaround I added the functionality using a custom node visitor like this one:
final class ClassMethodWithDocComment extends NodeVisitorAbstract
{
/**
* @var MethodGenerator
**/
private $methodGenerator;
private string $docComment;
public function __construct(MethodGenerator $methodGenerator, string $docComment)
{
$this->methodGenerator = $methodGenerator;
$this->docComment = $docComment;
}
public function afterTraverse(array $nodes): ?array
{
$newNodes = [];
foreach ($nodes as $node) {
$newNodes[] = $node;
if ($node instanceof Namespace_) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Stmt\Class_) {
if ($this->checkMethodExists($stmt)) {
return null;
}
$stmt->stmts[] = $this->addDocComment($this->methodGenerator->generate());
}
}
} elseif ($node instanceof Stmt\Class_) {
if ($this->checkMethodExists($node)) {
return null;
}
$node->stmts[] = $this->addDocComment($this->methodGenerator->generate());
}
}
return $newNodes;
}
private function checkMethodExists(Class_ $node): bool
{
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Node\Stmt\ClassMethod
&& $stmt->name->name === $this->methodGenerator->getName()
) {
return true;
}
}
return false;
}
private function addDocComment(Stmt\ClassMethod $method): Stmt\ClassMethod
{
$method->setDocComment(new Doc($this->docComment));
return $method;
}
}