Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active March 11, 2026 22:05
Show Gist options
  • Select an option

  • Save MrPunyapal/d74f8df54d96e177d264721c987d9101 to your computer and use it in GitHub Desktop.

Select an option

Save MrPunyapal/d74f8df54d96e177d264721c987d9101 to your computer and use it in GitHub Desktop.
Rector rule to remove all comments other than important phpdoc like `@param`
<?php
use PhpParser\Comment;
use PhpParser\Comment\Doc;
use PhpParser\Node;
use Rector\Core\Rector\AbstractRector;
final class RemoveUnnecessaryCommentsRector extends AbstractRector
{
private const ALLOWED = [
// others
];
public function getNodeTypes(): array
{
return [Node::class];
}
public function refactor(Node $node)
{
$comments = $node->getComments();
if ($comments === []) {
return null;
}
$filtered = [];
$changed = false;
foreach ($comments as $comment) {
if ($comment instanceof Doc) {
$new = $this->cleanDoc($comment);
if ($new !== $comment->getText()) {
$filtered[] = new Doc($new);
$changed = true;
} else {
$filtered[] = $comment;
}
continue;
}
if ($this->allowed($comment->getText())) {
$filtered[] = $comment;
} else {
$changed = true;
}
}
if (! $changed) {
return null;
}
$node->setAttribute('comments', $filtered);
return $node;
}
private function cleanDoc(Doc $doc): string
{
$lines = preg_split('/\R/', $doc->getText());
$tags = [];
foreach ($lines as $line) {
$line = trim(preg_replace('/^\s*\*\s?/', '', $line));
if ($line === '') {
continue;
}
if (str_starts_with($line, '@')) {
$tags[] = $line;
}
}
if ($tags === []) {
return $doc->getText();
}
return "/**\n * " . implode("\n * ", $tags) . "\n */";
}
private function allowed(string $text): bool
{
foreach (self::ALLOWED as $allowed) {
if (str_contains($text, $allowed)) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment