Created
February 10, 2025 09:12
-
-
Save hadl/34f339b3829462cc66aa47472dd90587 to your computer and use it in GitHub Desktop.
Rector rule to remove comments in constructor arguments when using ClassPropertyAssignToConstructorPromotionRector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace Utils\Rector\Rector; | |
use PhpParser\Node; | |
use PhpParser\Node\Param; | |
use PhpParser\Node\Stmt\ClassMethod; | |
use Rector\Rector\AbstractRector; | |
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; | |
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; | |
/** | |
* @see \Rector\Tests\TypeDeclaration\Rector\RemoveCommentFromConstructorPromotionRector\RemoveCommentFromConstructorPromotionRectorTest | |
*/ | |
final class RemoveCommentFromConstructorPromotionRector extends AbstractRector | |
{ | |
/** | |
* @return array<class-string<Node>> | |
*/ | |
public function getNodeTypes(): array | |
{ | |
return [ClassMethod::class]; | |
} | |
/** | |
* @param \PhpParser\Node\Stmt\Class_ $node | |
*/ | |
public function refactor(Node $node): ?Node | |
{ | |
if (!$node instanceof ClassMethod) { | |
return null; | |
} | |
if (!$this->isName($node, '__construct')) { | |
return null; | |
} | |
foreach ($node->params as $param) { | |
if ($param instanceof Param) { | |
$comments = $param->getComments(); | |
if ($comments !== []) { | |
$param->setAttribute('comments', []); | |
} | |
} | |
} | |
return $node; | |
} | |
public function getRuleDefinition(): RuleDefinition | |
{ | |
return new RuleDefinition( | |
'Remove comments from constructor arguments', | |
[ | |
new CodeSample( | |
<<<'CODE_SAMPLE' | |
class SomeClass | |
{ | |
public function __construct( | |
string $name, // This is a comment | |
int $age /* This is a multi-line comment | |
that spans multiple lines */ | |
) { | |
$this->name = $name; | |
$this->age = $age; | |
} | |
} | |
CODE_SAMPLE | |
, | |
<<<'CODE_SAMPLE' | |
class SomeClass | |
{ | |
public function __construct(string $name, int $age) | |
{ | |
$this->name = $name; | |
$this->age = $age; | |
} | |
} | |
CODE_SAMPLE | |
), | |
] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment