[PHP] Add pow to exp Rector [ref #638]

This commit is contained in:
Tomas Votruba 2018-10-04 16:11:54 +08:00
parent db41cf66ff
commit 39b5c0826f
6 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,2 @@
services:
Rector\Php\Rector\PowToExpRector: ~

View File

@ -0,0 +1,48 @@
<?php declare(strict_types=1);
namespace Rector\Php\Rector;
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Pow;
use PhpParser\Node\Expr\FuncCall;
use Rector\Rector\AbstractRector;
use Rector\RectorDefinition\CodeSample;
use Rector\RectorDefinition\RectorDefinition;
final class PowToExpRector extends AbstractRector
{
public function getDefinition(): RectorDefinition
{
return new RectorDefinition(
'Changes pow(val, val2) to ** (exp) parameter',
[new CodeSample('pow(1, 2);', '1**2;')]
);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [FuncCall::class];
}
/**
* @param FuncCall $funcCallNode
*/
public function refactor(Node $funcCallNode): ?Node
{
if ((string) $funcCallNode->name !== 'pow') {
return $funcCallNode;
}
if (count($funcCallNode->args) !== 2) {
return $funcCallNode;
}
$firstArgument = $funcCallNode->args[0]->value;
$secondArgument = $funcCallNode->args[1]->value;
return new Pow($firstArgument, $secondArgument);
}
}

View File

@ -0,0 +1,21 @@
<?php declare(strict_types=1);
$result = 1 ** 2;
$result = 1.2 ** 2.3;
echo (-2) ** 3;
($a--) ** (++$b);
\a\pow(5,6);7 ** 8;
(9 ** 10) ** 11 ** 12;
(1 + 2) ** (3 * 4);
($b = 4) ** 3;
13 ** 14;
$$a ** $$b;

View File

@ -0,0 +1,32 @@
<?php declare(strict_types=1);
namespace Rector\Php\Tests\Rector\PowToExpRector;
use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
/**
* @covers \Rector\Php\Rector\PowToExpRector
*
* Few tests copied from https://github.com/FriendsOfPHP/PHP-CS-Fixer/commit/14660432d9d0b66bf65135d793b52872cc6eccbc#diff-b412676c923661ef450f4a0903c5442a
*/
final class PowToExpRectorTest 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,21 @@
<?php declare(strict_types=1);
$result = pow(1, 2);
$result = pow(1.2, 2.3);
echo pow(-2, 3);
pow($a--,++$b);
\a\pow(5,6);pow(7,8);
pow(pow(9,10),pow(11,12));
pow(1 + 2, 3 * 4);
pow($b = 4, 3);
\pow(13,14);
pow($$a, $$b);

View File

@ -0,0 +1,2 @@
services:
Rector\Php\Rector\PowToExpRector: ~