-
-
Notifications
You must be signed in to change notification settings - Fork 688
/
ReplaceMultipleBooleanNotRector.php
54 lines (52 loc) · 1.4 KB
/
ReplaceMultipleBooleanNotRector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\Rector\BooleanNot;
use PhpParser\Node;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\Cast\Bool_;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodeQuality\Rector\BooleanNot\ReplaceMultipleBooleanNotRector\ReplaceMultipleBooleanNotRectorTest
*/
final class ReplaceMultipleBooleanNotRector extends AbstractRector
{
public function getRuleDefinition() : RuleDefinition
{
return new RuleDefinition('Replace the Double not operator (!!) by type-casting to boolean', [new CodeSample(<<<'CODE_SAMPLE'
$bool = !!$var;
CODE_SAMPLE
, <<<'CODE_SAMPLE'
$bool = (bool) $var;
CODE_SAMPLE
)]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [BooleanNot::class];
}
/**
* @param BooleanNot $node
*/
public function refactor(Node $node) : ?Node
{
$depth = 0;
$expr = $node->expr;
while ($expr instanceof BooleanNot) {
++$depth;
$expr = $expr->expr;
}
if ($depth === 0) {
return null;
}
if ($depth % 2 === 0) {
$node->expr = $expr;
return $node;
}
return new Bool_($expr);
}
}