-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathReverseConditionableMethodCallRector.php
88 lines (73 loc) · 2.29 KB
/
ReverseConditionableMethodCallRector.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
<?php
namespace RectorLaravel\Rector\MethodCall;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PHPStan\Type\ObjectType;
use RectorLaravel\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \RectorLaravel\Tests\Rector\MethodCall\ReverseConditionableMethodCallRector\ReverseConditionableMethodCallRectorTest
*/
class ReverseConditionableMethodCallRector extends AbstractRector
{
private const string CONDITIONABLE_TRAIT = 'Illuminate\Support\Traits\Conditionable';
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Reverse conditionable method calls',
[
new CodeSample(<<<'CODE_SAMPLE'
$conditionable->when(!$condition, function () {});
CODE_SAMPLE,
<<<'CODE_SAMPLE'
$conditionable->unless($condition, function () {});
CODE_SAMPLE
),
new CodeSample(<<<'CODE_SAMPLE'
$conditionable->unless(!$condition, function () {});
CODE_SAMPLE,
<<<'CODE_SAMPLE'
$conditionable->when($condition, function () {});
CODE_SAMPLE
),
]
);
}
public function getNodeTypes(): array
{
return [MethodCall::class];
}
/**
* @param MethodCall $node
*/
public function refactor(Node $node): ?MethodCall
{
if (! $this->isObjectType($node->var, new ObjectType(self::CONDITIONABLE_TRAIT))) {
return null;
}
if (! $this->isNames($node->name, ['when', 'unless'])) {
return null;
}
if ($node->isFirstClassCallable()) {
return null;
}
if ($node->getArgs() === []) {
return null;
}
$arg = $node->getArgs()[0];
if (! $node->name instanceof Identifier) {
return null;
}
if ($arg->value instanceof BooleanNot) {
$node->args[0] = new Arg($arg->value->expr);
$name = $node->name->toString() === 'when' ? 'unless' : 'when';
$node->name = new Identifier($name);
return $node;
}
return null;
}
}