|
3 | 3 | namespace AndreasElia\PostmanGenerator\Processors; |
4 | 4 |
|
5 | 5 | use Illuminate\Support\Str; |
6 | | -use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode; |
7 | | -use PHPStan\PhpDocParser\Lexer\Lexer; |
8 | | -use PHPStan\PhpDocParser\Parser\ConstExprParser; |
9 | | -use PHPStan\PhpDocParser\Parser\PhpDocParser; |
10 | | -use PHPStan\PhpDocParser\Parser\TokenIterator; |
11 | | -use PHPStan\PhpDocParser\Parser\TypeParser; |
12 | 6 | use ReflectionFunction; |
13 | 7 | use ReflectionMethod; |
14 | | -use Throwable; |
15 | 8 |
|
16 | 9 | class DocBlockProcessor |
17 | 10 | { |
18 | 11 | public function __invoke(ReflectionMethod|ReflectionFunction $reflectionMethod): string |
19 | 12 | { |
20 | | - try { |
21 | | - $lexer = new Lexer; |
22 | | - $constExprParser = new ConstExprParser; |
23 | | - $parser = new PhpDocParser(new TypeParser($constExprParser), $constExprParser); |
24 | | - |
25 | | - $description = ''; |
26 | | - $comment = $reflectionMethod->getDocComment(); |
27 | | - $tokens = new TokenIterator($lexer->tokenize($comment)); |
28 | | - $phpDocNode = $parser->parse($tokens); |
29 | | - |
30 | | - foreach ($phpDocNode->children as $child) { |
31 | | - if ($child instanceof PhpDocTextNode) { |
32 | | - $description .= ' '.$child->text; |
33 | | - } |
34 | | - } |
| 13 | + $comment = $reflectionMethod->getDocComment(); |
35 | 14 |
|
36 | | - return Str::squish($description); |
37 | | - } catch (Throwable $e) { |
| 15 | + if (! $comment) { |
38 | 16 | return ''; |
39 | 17 | } |
| 18 | + |
| 19 | + $description = collect(preg_split('/\R/', $comment) ?: []) |
| 20 | + ->map(function (string $line) { |
| 21 | + $line = trim($line); |
| 22 | + |
| 23 | + if (in_array($line, ['/**', '/*', '*/', '*'], true)) { |
| 24 | + return ''; |
| 25 | + } |
| 26 | + |
| 27 | + if (Str::startsWith($line, ['/**', '/*'])) { |
| 28 | + $line = ltrim(substr($line, 3)); |
| 29 | + } elseif (Str::startsWith($line, '*')) { |
| 30 | + $line = ltrim(substr($line, 1)); |
| 31 | + } |
| 32 | + |
| 33 | + if (Str::endsWith($line, '*/')) { |
| 34 | + $line = rtrim(substr($line, 0, -2)); |
| 35 | + } |
| 36 | + |
| 37 | + return $line; |
| 38 | + }) |
| 39 | + ->reject(fn (string $line) => $line === '') |
| 40 | + ->reject(fn (string $line) => Str::startsWith($line, '@')) |
| 41 | + ->implode(' '); |
| 42 | + |
| 43 | + return Str::squish($description); |
40 | 44 | } |
41 | 45 | } |
0 commit comments