Skip to content

Support DocComments for properties and methods #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
codeliner opened this issue Oct 28, 2020 · 0 comments
Closed

Support DocComments for properties and methods #9

codeliner opened this issue Oct 28, 2020 · 0 comments

Comments

@codeliner
Copy link
Member

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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant