2018-10-12 16:42:12 +00:00
|
|
|
<?php declare(strict_types=1);
|
|
|
|
|
2018-10-17 12:27:22 +00:00
|
|
|
namespace Rector\CodeQuality\Rector\Assign;
|
2018-10-12 16:42:12 +00:00
|
|
|
|
|
|
|
use PhpParser\Node;
|
|
|
|
use PhpParser\Node\Expr\Assign;
|
|
|
|
use PhpParser\Node\Expr\BinaryOp;
|
2018-11-04 01:17:02 +00:00
|
|
|
use Rector\PhpParser\Node\AssignAndBinaryMap;
|
2018-10-12 16:42:12 +00:00
|
|
|
use Rector\Rector\AbstractRector;
|
|
|
|
use Rector\RectorDefinition\CodeSample;
|
|
|
|
use Rector\RectorDefinition\RectorDefinition;
|
|
|
|
|
2019-09-03 09:11:45 +00:00
|
|
|
/**
|
|
|
|
* @see \Rector\CodeQuality\Tests\Rector\Assign\CombinedAssignRector\CombinedAssignRectorTest
|
|
|
|
*/
|
2018-10-12 16:42:12 +00:00
|
|
|
final class CombinedAssignRector extends AbstractRector
|
|
|
|
{
|
|
|
|
/**
|
2018-10-27 14:02:49 +00:00
|
|
|
* @var AssignAndBinaryMap
|
2018-10-12 16:42:12 +00:00
|
|
|
*/
|
2018-10-27 14:02:49 +00:00
|
|
|
private $assignAndBinaryMap;
|
2018-10-25 21:59:19 +00:00
|
|
|
|
2018-10-27 14:02:49 +00:00
|
|
|
public function __construct(AssignAndBinaryMap $assignAndBinaryMap)
|
2018-10-25 21:59:19 +00:00
|
|
|
{
|
2018-10-27 14:02:49 +00:00
|
|
|
$this->assignAndBinaryMap = $assignAndBinaryMap;
|
2018-10-25 21:59:19 +00:00
|
|
|
}
|
2018-10-12 16:42:12 +00:00
|
|
|
|
|
|
|
public function getDefinition(): RectorDefinition
|
|
|
|
{
|
|
|
|
return new RectorDefinition(
|
|
|
|
'Simplify $value = $value + 5; assignments to shorter ones',
|
|
|
|
[new CodeSample('$value = $value + 5;', '$value += 5;')]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return string[]
|
|
|
|
*/
|
|
|
|
public function getNodeTypes(): array
|
|
|
|
{
|
|
|
|
return [Assign::class];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-10-15 04:36:58 +00:00
|
|
|
* @param Assign $node
|
2018-10-12 16:42:12 +00:00
|
|
|
*/
|
2018-10-15 04:36:58 +00:00
|
|
|
public function refactor(Node $node): ?Node
|
2018-10-12 16:42:12 +00:00
|
|
|
{
|
2018-10-15 04:36:58 +00:00
|
|
|
if (! $node->expr instanceof BinaryOp) {
|
2018-10-21 10:19:14 +00:00
|
|
|
return null;
|
2018-10-12 16:42:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/** @var BinaryOp $binaryNode */
|
2018-10-15 04:36:58 +00:00
|
|
|
$binaryNode = $node->expr;
|
2018-10-12 16:42:12 +00:00
|
|
|
|
2018-10-15 04:36:58 +00:00
|
|
|
if (! $this->areNodesEqual($node->var, $binaryNode->left)) {
|
2018-10-21 10:19:14 +00:00
|
|
|
return null;
|
2018-10-12 16:42:12 +00:00
|
|
|
}
|
|
|
|
|
2018-10-27 14:02:49 +00:00
|
|
|
$assignClass = $this->assignAndBinaryMap->getAlternative($binaryNode);
|
2018-10-25 21:59:19 +00:00
|
|
|
if ($assignClass === null) {
|
2018-10-21 10:19:14 +00:00
|
|
|
return null;
|
2018-10-12 16:42:12 +00:00
|
|
|
}
|
|
|
|
|
2018-10-25 21:59:19 +00:00
|
|
|
return new $assignClass($node->var, $binaryNode->right);
|
2018-10-12 16:42:12 +00:00
|
|
|
}
|
|
|
|
}
|