[NodeTraverser] add ParentClassToTrait refactor

This commit is contained in:
TomasVotruba 2017-08-06 19:49:19 +02:00
parent 63bbfb3efc
commit 58f638d104
6 changed files with 105 additions and 0 deletions

View File

@ -0,0 +1,65 @@
<?php declare(strict_types=1);
namespace Rector\NodeVisitor\UpgradeDeprecation;
use PhpParser\Node;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\TraitUse;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
/**
* Reflects @link https://doc.nette.org/en/2.4/migration-2-4#toc-nette-smartobject
*/
final class DeprecatedParentClassToTraitNodeVisitor extends NodeVisitorAbstract
{
public function getParentClassName(): string
{
return 'Nette\Object';
}
public function getTraitName(): string
{
return 'Nette\SmartObject';
}
public function enterNode(Node $node): ?int
{
if ($this->isCandidate($node)) {
$this->refactor($node);
return NodeTraverser::DONT_TRAVERSE_CHILDREN;
}
return null;
}
private function isCandidate(Node $node): bool
{
if ($node instanceof Node\Stmt\Class_) {
if (! $node->extends) {
return false;
}
$parentClassName = (string) $node->extends;
if ($parentClassName !== $this->getParentClassName()) {
return false;
}
return true;
}
return false;
}
private function refactor(Node\Stmt\Class_ $classNode)
{
// remove parent class
$classNode->extends = null;
// add new trait
$nameParts = explode('\\', $this->getTraitName());
$classNode->stmts[] = new TraitUse([
new FullyQualified($nameParts)
]);
}
}

View File

@ -0,0 +1,16 @@
<?php declare(strict_types=1);
namespace Rector\Tests\NodeVisitor\UpgradeDeprecation\DeprecatedParentClassToTraitNodeVisitor;
use Rector\Testing\PHPUnit\AbstractReconstructorTestCase;
final class Test extends AbstractReconstructorTestCase
{
public function test(): void
{
$this->doTestFileMatchesExpectedContent(
__DIR__ . '/wrong/wrong.php.inc',
__DIR__ . '/correct/correct.php.inc'
);
}
}

View File

@ -0,0 +1,6 @@
<?php declare (strict_types=1);
class ClassWithExternalConstant
{
use \Nette\SmartObject;
}

View File

@ -0,0 +1,7 @@
<?php declare (strict_types=1);
class ClassWithExternalConstant
{
use \Nette\SmartObject;
use AnotherTrait;
}

View File

@ -0,0 +1,5 @@
<?php declare (strict_types=1);
class ClassWithExternalConstant extends Nette\Object
{
}

View File

@ -0,0 +1,6 @@
<?php declare (strict_types=1);
class ClassWithExternalConstant extends Nette\Object
{
use AnotherTrait;
}