1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Fixable\PhpDoc;
4:
5: use PhpParser\Comment\Doc;
6: use PHPStan\DependencyInjection\AutowiredService;
7: use PHPStan\PhpDocParser\Ast\Node;
8: use PHPStan\PhpDocParser\Ast\NodeTraverser;
9: use PHPStan\PhpDocParser\Ast\NodeVisitor\CloningVisitor;
10: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
11: use PHPStan\PhpDocParser\Lexer\Lexer;
12: use PHPStan\PhpDocParser\Parser\ConstExprParser;
13: use PHPStan\PhpDocParser\Parser\PhpDocParser;
14: use PHPStan\PhpDocParser\Parser\TokenIterator;
15: use PHPStan\PhpDocParser\Parser\TypeParser;
16: use PHPStan\PhpDocParser\ParserConfig;
17: use PHPStan\PhpDocParser\Printer\Printer;
18: use function count;
19:
20: /**
21: * @api
22: */
23: #[AutowiredService]
24: final class PhpDocEditor
25: {
26:
27: private Lexer $lexer;
28:
29: private PhpDocParser $phpDocParser;
30:
31: public function __construct(private Printer $printer)
32: {
33: // format-preserving printing needs token indexes, which the parser used by analysis does not collect
34: $config = new ParserConfig(['lines' => true, 'indexes' => true]);
35: $constExprParser = new ConstExprParser($config);
36: $this->lexer = new Lexer($config);
37: $this->phpDocParser = new PhpDocParser($config, new TypeParser($config, $constExprParser), $constExprParser);
38: }
39:
40: /**
41: * @param callable(Node): (Node|Node[]|null) $callback
42: */
43: public function edit(\PhpParser\Node $node, callable $callback): void
44: {
45: $doc = $node->getDocComment();
46: $phpDoc = $this->editText($doc === null ? '/** */' : $doc->getText(), $callback);
47: if ($phpDoc === null) {
48: $node->setAttribute('comments', []);
49: return;
50: }
51:
52: $node->setDocComment(new Doc($phpDoc));
53: }
54:
55: /**
56: * Edits the text of a PHPDoc with format-preserving printing.
57: *
58: * @param callable(Node): (Node|Node[]|null) $callback
59: * @return string|null null when the PHPDoc is left without contents
60: */
61: public function editText(string $phpDoc, callable $callback): ?string
62: {
63: $tokens = new TokenIterator($this->lexer->tokenize($phpDoc));
64: $phpDocNode = $this->phpDocParser->parse($tokens);
65:
66: $cloningTraverser = new NodeTraverser([new CloningVisitor()]);
67:
68: /** @var PhpDocNode $newPhpDocNode */
69: [$newPhpDocNode] = $cloningTraverser->traverse([$phpDocNode]);
70:
71: $traverser = new NodeTraverser([new CallbackVisitor($callback)]);
72:
73: /** @var PhpDocNode $newPhpDocNode */
74: [$newPhpDocNode] = $traverser->traverse([$newPhpDocNode]);
75:
76: if (count($newPhpDocNode->children) === 0) {
77: return null;
78: }
79:
80: return $this->printer->printFormatPreserving($newPhpDocNode, $phpDocNode, $tokens);
81: }
82:
83: }
84: