Skip to content

Commit

Permalink
add doc block parser
Browse files Browse the repository at this point in the history
  • Loading branch information
tomirons committed Mar 6, 2024
1 parent 60aeac7 commit de5e7f1
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/Processors/DocBlockProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace AndreasElia\PostmanGenerator\Processors;

use Illuminate\Support\Str;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\ConstExprParser;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;
use PHPStan\PhpDocParser\Parser\TypeParser;
use ReflectionFunction;
use ReflectionMethod;
use Throwable;

class DocBlockProcessor
{
public function __invoke(ReflectionMethod|ReflectionFunction $reflectionMethod): string
{
try {
$lexer = new Lexer;
$constExprParser = new ConstExprParser;
$parser = new PhpDocParser(new TypeParser($constExprParser), $constExprParser);

$description = '';
$comment = $reflectionMethod->getDocComment();
$tokens = new TokenIterator($lexer->tokenize($comment));
$phpDocNode = $parser->parse($tokens);

foreach ($phpDocNode->children as $child) {
if ($child instanceof PhpDocTextNode) {
$description .= ' '.$child->text;
}
}

return Str::squish($description);
} catch (Throwable $e) {
return '';
}
}
}

0 comments on commit de5e7f1

Please sign in to comment.