forked from rectorphp/rector-symfony
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstraintUrlOptionRector.php
103 lines (86 loc) · 2.75 KB
/
ConstraintUrlOptionRector.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\Symfony\Symfony40\Rector\ConstFetch;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Expr\New_;
use PHPStan\Type\ObjectType;
use Rector\PhpParser\Node\Value\ValueResolver;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* Ref: https://github.com/symfony/symfony/blob/master/UPGRADE-4.0.md#validator
*
* @see \Rector\Symfony\Tests\Symfony40\Rector\ConstFetch\ConstraintUrlOptionRector\ConstraintUrlOptionRectorTest
*/
final class ConstraintUrlOptionRector extends AbstractRector
{
/**
* @var string
*/
private const URL_CONSTRAINT_CLASS = 'Symfony\Component\Validator\Constraints\Url';
public function __construct(
private readonly ValueResolver $valueResolver
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Turns true value to `Url::CHECK_DNS_TYPE_ANY` in Validator in Symfony.',
[
new CodeSample(
'$constraint = new Url(["checkDNS" => true]);',
'$constraint = new Url(["checkDNS" => Url::CHECK_DNS_TYPE_ANY]);'
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [New_::class];
}
/**
* @param New_ $node
*/
public function refactor(Node $node): ?New_
{
if (! $this->isObjectType($node, new ObjectType('Symfony\Component\Validator\Constraints\Url'))) {
return null;
}
foreach ($node->getArgs() as $arg) {
if (! $arg->value instanceof Array_) {
continue;
}
foreach ($arg->value->items as $arrayItem) {
if (! $arrayItem instanceof ArrayItem) {
continue;
}
if (! $this->isCheckDNSKey($arrayItem)) {
continue;
}
if (! $this->valueResolver->isTrue($arrayItem->value)) {
return null;
}
$arrayItem->value = $this->nodeFactory->createClassConstFetch(
self::URL_CONSTRAINT_CLASS,
'CHECK_DNS_TYPE_ANY'
);
return $node;
}
}
return null;
}
private function isCheckDNSKey(ArrayItem $arrayItem): bool
{
if (! $arrayItem->key instanceof Expr) {
return false;
}
return $this->valueResolver->isValue($arrayItem->key, 'checkDNS');
}
}