-
-
Notifications
You must be signed in to change notification settings - Fork 336
/
AddFalseDefaultToBoolPropertyRector.php
103 lines (89 loc) · 2.57 KB
/
AddFalseDefaultToBoolPropertyRector.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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Rector\Property;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Trait_;
use PHPStan\Type\BooleanType;
use Rector\Core\Rector\AbstractRector;
use Rector\TypeDeclaration\AlreadyAssignDetector\ConstructorAssignDetector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodingStyle\Rector\Property\AddFalseDefaultToBoolPropertyRector\AddFalseDefaultToBoolPropertyRectorTest
*/
final class AddFalseDefaultToBoolPropertyRector extends AbstractRector
{
public function __construct(private readonly ConstructorAssignDetector $constructorAssignDetector)
{
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Add false default to bool properties, to prevent null compare errors',
[
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
/**
* @var bool
*/
private $isDisabled;
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
/**
* @var bool
*/
private $isDisabled = false;
}
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Property::class];
}
/**
* @param Property $node
*/
public function refactor(Node $node): ?Node
{
if (count($node->props) !== 1) {
return null;
}
$onlyProperty = $node->props[0];
if ($onlyProperty->default !== null) {
return null;
}
if (! $this->isBoolDocType($node)) {
return null;
}
$classLike = $this->betterNodeFinder->findParentByTypes($node, [Class_::class, Trait_::class]);
if (! $classLike instanceof ClassLike) {
return null;
}
$propertyName = $this->nodeNameResolver->getName($onlyProperty);
if ($this->constructorAssignDetector->isPropertyAssigned($classLike, $propertyName)) {
return null;
}
$onlyProperty->default = $this->nodeFactory->createFalse();
return $node;
}
private function isBoolDocType(Property $property): bool
{
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($property);
return $phpDocInfo->getVarType() instanceof BooleanType;
}
}