Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions config/sets/symfony/symfony-code-quality.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

declare(strict_types=1);

use Rector\Symfony\Symfony62\Rector\Class_\SecurityAttributeToIsGrantedAttributeRector;
use Rector\Config\RectorConfig;
use Rector\Symfony\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector;
use Rector\Symfony\CodeQuality\Rector\BinaryOp\RequestIsMainRector;
use Rector\Symfony\CodeQuality\Rector\BinaryOp\ResponseStatusCodeRector;
use Rector\Symfony\CodeQuality\Rector\Class_\EventListenerToEventSubscriberRector;
Expand All @@ -16,6 +16,7 @@
use Rector\Symfony\CodeQuality\Rector\MethodCall\AssertSameResponseCodeWithDebugContentsRector;
use Rector\Symfony\CodeQuality\Rector\MethodCall\LiteralGetToRequestClassConstantRector;
use Rector\Symfony\Symfony26\Rector\MethodCall\RedirectToRouteRector;
use Rector\Symfony\Symfony62\Rector\Class_\SecurityAttributeToIsGrantedAttributeRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rules([
Expand All @@ -41,6 +42,6 @@
InlineClassRoutePrefixRector::class,

// narrow attributes
SecurityAttributeToIsGrantedAttributeRector::class,
SingleConditionSecurityAttributeToIsGrantedRector::class,
]);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector\Fixture;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

final class ControllerWithSecurityAttribute
{
#[Security("has_role('SOME_USER')")]
public function index()
{
}
}

?>
-----
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector\Fixture;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

final class ControllerWithSecurityAttribute
{
#[\Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted('SOME_USER')]
public function index()
{
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector\Fixture;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

final class SkipMultiples
{
#[Security("has_role('SOME_USER') or has_role('SOME_USER2')")]
public function index()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector\Fixture;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

final class WithIsGranted
{
#[Security("is_granted('SOME_USER')")]
public function index()
{
}
}

?>
-----
<?php

namespace Rector\Symfony\Tests\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector\Fixture;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

final class WithIsGranted
{
#[\Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted('SOME_USER')]
public function index()
{
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Symfony\Tests\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class SingleConditionSecurityAttributeToIsGrantedRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Symfony\CodeQuality\Rector\AttributeGroup\SingleConditionSecurityAttributeToIsGrantedRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(SingleConditionSecurityAttributeToIsGrantedRector::class);
};
28 changes: 28 additions & 0 deletions rules/CodeQuality/NodeAnalyzer/AttributePresenceDetector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Symfony\CodeQuality\NodeAnalyzer;

use PHPStan\Reflection\ReflectionProvider;

final readonly class AttributePresenceDetector
{
public function __construct(
private ReflectionProvider $reflectionProvider,
) {
}

public function detect(string $attributeClass): bool
{
// run only if the sensio attribute is available
if (! $this->reflectionProvider->hasClass($attributeClass)) {
return false;
}

// must be attribute, not just annotation
$securityClassReflection = $this->reflectionProvider->getClass($attributeClass);

return $securityClassReflection->isAttributeClass();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,7 @@ private function hasAsListenerAttribute(Class_ $class): bool
continue;
}

if ($this->phpAttributeAnalyzer->hasPhpAttribute(
$classMethod,
SymfonyAttribute::AS_EVENT_LISTENER
)) {
if ($this->phpAttributeAnalyzer->hasPhpAttribute($classMethod, SymfonyAttribute::AS_EVENT_LISTENER)) {
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Reflection\ReflectionProvider;
use Rector\Rector\AbstractRector;
use Rector\Symfony\CodeQuality\NodeAnalyzer\AttributePresenceDetector;
use Rector\Symfony\Enum\SensioAttribute;
use Rector\Symfony\Enum\SymfonyAttribute;
use Rector\ValueObject\PhpVersionFeature;
Expand All @@ -31,7 +32,6 @@
*/
final class SecurityAttributeToIsGrantedAttributeRector extends AbstractRector implements MinPhpVersionInterface
{

/**
* @var string
* @see https://regex101.com/r/Si1sDz/1
Expand All @@ -45,7 +45,8 @@ final class SecurityAttributeToIsGrantedAttributeRector extends AbstractRector i
private const IS_GRANTED_AND_SUBJECT_REGEX = '#^is_granted\((\"|\')(?<role>[\w]+)(\"|\'),\s+(?<subject>\w+)\)$#';

public function __construct(
private readonly ReflectionProvider $reflectionProvider
private readonly ReflectionProvider $reflectionProvider,
private readonly AttributePresenceDetector $attributePresenceDetector,
) {
}

Expand Down Expand Up @@ -83,12 +84,12 @@ public function list()

class PostController extends Controller
{
#[IsGranted('ROLE_ADMIN')]
#[IsGranted(attribute: 'ROLE_ADMIN')]
public function index()
{
}

#[IsGranted(new Expression("is_granted('ROLE_ADMIN') and is_granted('ROLE_FRIENDLY_USER')"))]
#[IsGranted(attribute: new Expression("is_granted('ROLE_ADMIN') and is_granted('ROLE_FRIENDLY_USER')"))]
public function list()
{
}
Expand All @@ -112,7 +113,7 @@ public function getNodeTypes(): array
*/
public function refactor(Node $node): ?Node
{
if (! $this->hasSymfonySecurityAttribute()) {
if (! $this->attributePresenceDetector->detect(SensioAttribute::SECURITY)) {
return null;
}

Expand All @@ -126,7 +127,6 @@ public function refactor(Node $node): ?Node

// 1. resolve closest existing name of IsGranted
$isGrantedName = $this->resolveIsGrantedAttributeName();

$attribute->name = new FullyQualified($isGrantedName);

$firstArg = $attribute->args[0];
Expand Down Expand Up @@ -192,19 +192,7 @@ private function resolveIsGrantedAttributeName(): string
return SymfonyAttribute::IS_GRANTED;
}

// fallback to sensio, if available
// fallback to "sensio"
return SensioAttribute::IS_GRANTED;
}

private function hasSymfonySecurityAttribute(): bool
{
// run only if the sensio attribute is available
if (! $this->reflectionProvider->hasClass(SensioAttribute::SECURITY)) {
return false;
}

// must be attribute, not just annotation
$securityClassReflection = $this->reflectionProvider->getClass(SensioAttribute::SECURITY);
return $securityClassReflection->isAttributeClass();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@
#[\Attribute]
class Security
{
public function __construct(string $expression)
{
}
}
Loading