rector/rules/Removing/Rector/Class_/RemoveTraitUseRector.php

82 lines
2.2 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\Removing\Rector\Class_;
2019-03-09 17:36:27 +00:00
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\Node\Stmt\TraitUse;
use Rector\Contract\Rector\ConfigurableRectorInterface;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\ConfiguredCodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use RectorPrefix202403\Webmozart\Assert\Assert;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\Removing\Rector\Class_\RemoveTraitUseRector\RemoveTraitUseRectorTest
2019-09-03 09:11:45 +00:00
*/
final class RemoveTraitUseRector extends AbstractRector implements ConfigurableRectorInterface
2019-03-09 17:36:27 +00:00
{
/**
* @var string[]
*/
private $traitsToRemove = [];
public function getRuleDefinition() : RuleDefinition
2019-03-09 17:36:27 +00:00
{
return new RuleDefinition('Remove specific traits from code', [new ConfiguredCodeSample(<<<'CODE_SAMPLE'
2019-03-09 17:36:27 +00:00
class SomeClass
{
use SomeTrait;
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2019-03-09 17:36:27 +00:00
class SomeClass
{
}
CODE_SAMPLE
, ['TraitNameToRemove'])]);
2019-03-09 17:36:27 +00:00
}
/**
* @return array<class-string<Node>>
2019-03-09 17:36:27 +00:00
*/
public function getNodeTypes() : array
2019-03-09 17:36:27 +00:00
{
return [Class_::class, Trait_::class];
2019-03-09 17:36:27 +00:00
}
/**
* @param Class_|Trait_ $node
2019-03-09 17:36:27 +00:00
*/
public function refactor(Node $node) : ?Node
2019-03-09 17:36:27 +00:00
{
$hasChanged = \false;
foreach ($node->stmts as $key => $stmt) {
if (!$stmt instanceof TraitUse) {
continue;
}
foreach ($stmt->traits as $traitKey => $trait) {
if (!$this->isNames($trait, $this->traitsToRemove)) {
continue;
}
unset($stmt->traits[$traitKey]);
$hasChanged = \true;
}
// remove empty trait uses
if ($stmt->traits === []) {
unset($node->stmts[$key]);
}
}
if ($hasChanged) {
return $node;
2019-03-09 17:36:27 +00:00
}
return null;
2019-03-09 17:36:27 +00:00
}
/**
* @param mixed[] $configuration
*/
public function configure(array $configuration) : void
2020-07-29 23:39:41 +00:00
{
Assert::allString($configuration);
$this->traitsToRemove = $configuration;
2020-07-29 23:39:41 +00:00
}
2019-03-09 17:36:27 +00:00
}