Repository navigation
Expand file tree
/
Copy pathReplaceConstantBooleanNotRector.php
More file actions
82 lines (70 loc) · 1.81 KB
/
Copy pathReplaceConstantBooleanNotRector.php
File metadata and controls
82 lines (70 loc) · 1.81 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\BooleanNot;
use PhpParser\Node;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Name;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
use Rector\RuleDoc\CodeSample\CodeSample;
use Rector\RuleDoc\RuleDefinition;
/**
* Replace negated boolean literals with their simplified equivalents
*
* @see \Rector\Tests\CodeQuality\Rector\BooleanNot\ReplaceConstantBooleanNotRector\ReplaceConstantBooleanNotRectorTest
*/
final class ReplaceConstantBooleanNotRector extends AbstractRector
{
public function __construct(
private readonly ValueResolver $valueResolver
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Replace negated boolean literals (!false, !true) with their simplified equivalents (true, false)',
[
new CodeSample(
<<<'CODE_SAMPLE'
if (!false) {
return 'always true';
}
if (!true) {
return 'never reached';
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
if (true) {
return 'always true';
}
if (false) {
return 'never reached';
}
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [BooleanNot::class];
}
/**
* @param BooleanNot $node
*/
public function refactor(Node $node): ?Node
{
if ($this->valueResolver->isFalse($node->expr)) {
return new ConstFetch(new Name('true'));
}
if ($this->valueResolver->isTrue($node->expr)) {
return new ConstFetch(new Name('false'));
}
return null;
}
}