add SetLineRector

This commit is contained in:
TomasVotruba 2017-10-22 01:10:53 +02:00
parent 2144a87380
commit 8e82b9ca9d
5 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,48 @@
<?php declare(strict_types=1);
namespace Rector\Rector\Contrib\PhpParser;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Scalar\String_;
use Rector\NodeAnalyzer\MethodCallAnalyzer;
use Rector\Rector\AbstractRector;
/**
* Before:
* - $node->setLine(5);
*
* After:
* - $node->setAttribute('line', 5);
*/
final class SetLineRector extends AbstractRector
{
/**
* @var MethodCallAnalyzer
*/
private $methodCallAnalyzer;
public function __construct(MethodCallAnalyzer $methodCallAnalyzer)
{
$this->methodCallAnalyzer = $methodCallAnalyzer;
}
public function isCandidate(Node $node): bool
{
return $this->methodCallAnalyzer->isTypeAndMethod($node, 'PhpParser\Node', 'setLine');
}
/**
* @param MethodCall $methodCallNode
*/
public function refactor(Node $methodCallNode): ?Node
{
$methodCallNode->name = 'setAttribute';
$methodCallNode->args[1] = $methodCallNode->args[0];
$methodCallNode->args[0] = new Arg(new String_('line'));
return $methodCallNode;
}
}

View File

@ -1,6 +1,7 @@
rectors:
Rector\Rector\Contrib\PhpParser\IdentifierRector: ~
Rector\Rector\Contrib\PhpParser\ParamAndStaticVarNameRector: ~
Rector\Rector\Contrib\PhpParser\SetLineRector: ~
Rector\Rector\Dynamic\ClassConstantReplacerRector:
'PhpParser\Node\Stmt\Class_':

View File

@ -0,0 +1,4 @@
<?php declare(strict_types=1);
$node = new PhpParser\Node;
$node->setAttribute('line', 5);

View File

@ -0,0 +1,25 @@
<?php declare(strict_types=1);
namespace Rector\Tests\Rector\Contrib\PhpParser\SetLineRector;
use Rector\Rector\Contrib\PhpParser\SetLineRector;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
final class Test extends AbstractRectorTestCase
{
public function test(): void
{
$this->doTestFileMatchesExpectedContent(
__DIR__ . '/Wrong/wrong.php.inc',
__DIR__ . '/Correct/correct.php.inc'
);
}
/**
* @return string[]
*/
protected function getRectorClasses(): array
{
return [SetLineRector::class];
}
}

View File

@ -0,0 +1,4 @@
<?php declare(strict_types=1);
$node = new PhpParser\Node;
$node->setLine(5);