2019-10-13 05:59:52 +00:00
|
|
|
<?php
|
|
|
|
|
2021-05-09 20:15:43 +00:00
|
|
|
declare (strict_types=1);
|
2022-06-06 17:12:56 +00:00
|
|
|
namespace Rector\CodingStyle\Rector\Plus;
|
2019-10-04 09:22:58 +00:00
|
|
|
|
2022-06-06 17:12:56 +00:00
|
|
|
use PhpParser\Node;
|
|
|
|
use PhpParser\Node\Expr\AssignOp\Minus;
|
|
|
|
use PhpParser\Node\Expr\AssignOp\Plus;
|
|
|
|
use PhpParser\Node\Expr\PreDec;
|
|
|
|
use PhpParser\Node\Expr\PreInc;
|
|
|
|
use PhpParser\Node\Scalar\LNumber;
|
2024-01-02 02:40:38 +00:00
|
|
|
use Rector\Rector\AbstractRector;
|
2022-06-07 09:18:30 +00:00
|
|
|
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
|
|
|
|
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
|
2019-10-04 09:22:58 +00:00
|
|
|
/**
|
2021-03-12 22:20:25 +00:00
|
|
|
* @see \Rector\Tests\CodingStyle\Rector\Plus\UseIncrementAssignRector\UseIncrementAssignRectorTest
|
2019-10-04 09:22:58 +00:00
|
|
|
*/
|
2022-06-07 08:22:29 +00:00
|
|
|
final class UseIncrementAssignRector extends AbstractRector
|
2019-10-04 09:22:58 +00:00
|
|
|
{
|
2022-06-07 08:22:29 +00:00
|
|
|
public function getRuleDefinition() : RuleDefinition
|
2019-10-04 09:22:58 +00:00
|
|
|
{
|
2022-06-07 08:22:29 +00:00
|
|
|
return new RuleDefinition('Use ++ increment instead of `$var += 1`', [new CodeSample(<<<'CODE_SAMPLE'
|
2019-10-04 09:22:58 +00:00
|
|
|
class SomeClass
|
|
|
|
{
|
|
|
|
public function run()
|
|
|
|
{
|
|
|
|
$style += 1;
|
|
|
|
}
|
|
|
|
}
|
2020-09-15 08:23:13 +00:00
|
|
|
CODE_SAMPLE
|
2021-05-09 20:15:43 +00:00
|
|
|
, <<<'CODE_SAMPLE'
|
2019-10-04 09:22:58 +00:00
|
|
|
class SomeClass
|
|
|
|
{
|
|
|
|
public function run()
|
|
|
|
{
|
2020-12-12 11:10:48 +00:00
|
|
|
++$style;
|
2019-10-04 09:22:58 +00:00
|
|
|
}
|
|
|
|
}
|
2020-09-15 08:23:13 +00:00
|
|
|
CODE_SAMPLE
|
2021-05-09 20:15:43 +00:00
|
|
|
)]);
|
2019-10-04 09:22:58 +00:00
|
|
|
}
|
|
|
|
/**
|
2021-02-27 00:06:15 +00:00
|
|
|
* @return array<class-string<Node>>
|
2019-10-04 09:22:58 +00:00
|
|
|
*/
|
2021-05-09 20:15:43 +00:00
|
|
|
public function getNodeTypes() : array
|
2019-10-04 09:22:58 +00:00
|
|
|
{
|
2022-06-07 08:22:29 +00:00
|
|
|
return [Plus::class, Minus::class];
|
2019-10-04 09:22:58 +00:00
|
|
|
}
|
|
|
|
/**
|
2021-12-10 10:22:23 +00:00
|
|
|
* @param Plus|Minus $node
|
2019-10-04 09:22:58 +00:00
|
|
|
*/
|
2022-06-07 08:22:29 +00:00
|
|
|
public function refactor(Node $node) : ?Node
|
2019-10-04 09:22:58 +00:00
|
|
|
{
|
2022-06-07 08:22:29 +00:00
|
|
|
if (!$node->expr instanceof LNumber) {
|
2019-10-04 11:39:43 +00:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
if ($node->expr->value !== 1) {
|
2019-10-04 09:22:58 +00:00
|
|
|
return null;
|
|
|
|
}
|
2022-06-07 08:22:29 +00:00
|
|
|
if ($node instanceof Plus) {
|
|
|
|
return new PreInc($node->var);
|
2019-10-04 09:22:58 +00:00
|
|
|
}
|
2022-06-07 08:22:29 +00:00
|
|
|
return new PreDec($node->var);
|
2019-10-04 09:22:58 +00:00
|
|
|
}
|
|
|
|
}
|