-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathSingleConditionSecurityAttributeToIsGrantedRector.php
More file actions
96 lines (80 loc) · 2.51 KB
/
SingleConditionSecurityAttributeToIsGrantedRector.php
File metadata and controls
96 lines (80 loc) · 2.51 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
namespace Rector\Symfony\CodeQuality\Rector\AttributeGroup;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Scalar\String_;
use Rector\Rector\AbstractRector;
use Rector\Symfony\CodeQuality\NodeAnalyzer\AttributePresenceDetector;
use Rector\Symfony\Enum\SensioAttribute;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
final class SingleConditionSecurityAttributeToIsGrantedRector extends AbstractRector
{
public function __construct(
private readonly AttributePresenceDetector $attributePresenceDetector,
) {
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Narrow #[Security] attribute with inner sigle "is_granted/has_role" condition string to #[IsGranted] attribute',
[
new CodeSample(
<<<'CODE_SAMPLE'
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
#[Security("is_granted('ROLE_USER')")]
class SomeClass
{
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[IsGranted('ROLE_USER')]
class SomeClass
{
}
CODE_SAMPLE
,
),
]
);
}
public function getNodeTypes(): array
{
return [AttributeGroup::class];
}
/**
* @param AttributeGroup $node
*/
public function refactor(Node $node): ?AttributeGroup
{
if (! $this->attributePresenceDetector->detect(SensioAttribute::SECURITY)) {
return null;
}
foreach ($node->attrs as $attr) {
if (! $this->isName($attr->name, SensioAttribute::SECURITY)) {
continue;
}
$firstArgValue = $attr->args[0]->value;
if (! $firstArgValue instanceof String_) {
continue;
}
$matches = Strings::match(
$firstArgValue->value,
'#^(is_granted|has_role)\(\'(?<access_right>[A-Za-z_]+)\'\)$#'
);
if (! isset($matches['access_right'])) {
continue;
}
$attr->name = new FullyQualified(SensioAttribute::IS_GRANTED);
$attr->args = [new Arg(new String_($matches['access_right']))];
return $node;
}
return null;
}
}