[CodeQuality] Add SimplifyFuncGetArgsCountRector

This commit is contained in:
Tomas Votruba 2018-10-13 17:46:40 +08:00
parent 0b717b001f
commit 336623c70b
5 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,51 @@
<?php declare(strict_types=1);
namespace Rector\Rector\CodeQuality;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class SimplifyFuncGetArgsCountRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition(
'Simplify count of func_get_args() to fun_num_args()',
[new CodeSample('count(func_get_args());', 'func_num_args();')]
);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/**
* @param FuncCall $node
*/
public function refactor(Node $node): ?Node
{
if ((string) $node->name !== 'count') {
return $node;
}
if (! $node->args[0]->value instanceof FuncCall) {
return $node;
}
/** @var FuncCall $innerFuncCall */
$innerFuncCall = $node->args[0]->value;
if ((string) $innerFuncCall->name !== 'func_get_args') {
return $node;
}
return new FuncCall(new Name('func_num_args'));
}
}

View File

@ -0,0 +1,5 @@
<?php declare(strict_types=1);
if (func_num_args() === 5) {
echo 'yes!';
}

View File

@ -0,0 +1,30 @@
<?php declare(strict_types=1);
namespace Rector\Tests\Rector\CodeQuality\SimplifyFuncGetArgsCountRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
/**
* @covers \Rector\Rector\CodeQuality\SimplifyFuncGetArgsCountRector
*/
final class SimplifyFuncGetArgsCountRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideWrongToFixedFiles()
*/
public function test(string $wrong, string $fixed): void
{
$this->doTestFileMatchesExpectedContent($wrong, $fixed);
}
public function provideWrongToFixedFiles(): Iterator
{
yield [__DIR__ . '/Wrong/wrong.php.inc', __DIR__ . '/Correct/correct.php.inc'];
}
protected function provideConfig(): string
{
return __DIR__ . '/config.yml';
}
}

View File

@ -0,0 +1,5 @@
<?php declare(strict_types=1);
if (count(func_get_args()) === 5) {
echo 'yes!';
}

View File

@ -0,0 +1,2 @@
services:
Rector\Rector\CodeQuality\SimplifyFuncGetArgsCountRector: ~