Skip to content

[symfony 7.3] Add InvokableCommandRector - kick off #707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 21, 2025
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
9 changes: 6 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,24 @@
"ext-xml": "*"
},
"require-dev": {
"phpecs/phpecs": "^2.0.1",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.1.8",
"phpstan/phpstan-webmozart-assert": "^2.0",
"phpunit/phpunit": "^11.4",
"rector/rector-src": "dev-main",
"rector/type-perfect": "^2.0",
"symfony/config": "^6.4",
"symfony/dependency-injection": "^6.4",
"symfony/http-kernel": "~6.3",
"symfony/http-kernel": "^6.4",
"symfony/routing": "^6.4",
"symfony/security-core": "^6.4",
"symfony/security-http": "^6.4",
"symfony/validator": "^6.4",
"symplify/easy-coding-standard": "^12.3",
"symplify/vendor-patches": "^11.3",
"tomasvotruba/class-leak": "^1.0",
"tomasvotruba/class-leak": "^2.0",
"tomasvotruba/type-coverage": "^2.0",
"tomasvotruba/unused-public": "^2.0",
"tracy/tracy": "^2.10"
},
"autoload": {
Expand Down
11 changes: 11 additions & 0 deletions config/sets/symfony/symfony73.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Symfony\Symfony73\Rector\Class_\InvokableCommandRector;

// @see https://github.com/symfony/symfony/blame/7.3/UPGRADE-7.3.md

return RectorConfig::configure()
->withRules([InvokableCommandRector::class]);
38 changes: 16 additions & 22 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ parameters:
level: 8

reportUnmatchedIgnoredErrors: false

treatPhpDocTypesAsCertain: false

paths:
Expand All @@ -12,18 +11,17 @@ parameters:
- rules
- rules-tests

# to be enabled later once rector upgraded to use phpstan v2
# # https://github.com/rectorphp/type-perfect/
# type_perfect:
# no_mixed: true
# null_over_false: true
# narrow_param: true
# narrow_return: true
# https://github.com/rectorphp/type-perfect/
type_perfect:
no_mixed: true
null_over_false: true
narrow_param: true
narrow_return: true

# unused_public:
# constants: true
# methods: true
# properties: true
unused_public:
constants: true
methods: true
properties: true

scanDirectories:
- stubs
Expand Down Expand Up @@ -54,16 +52,12 @@ parameters:
- '#Doing instanceof PHPStan\\Type\\.+ is error\-prone and deprecated#'

# phpstan instanceof
-
identifier: phpstanApi.instanceofAssumption

-
identifier: phpstanApi.varTagAssumption
- identifier: argument.type
- identifier: assign.propertyType

-
identifier: argument.type
- '#::provideMinPhpVersion\(\) never returns \d+ so it can be removed from the return type#'

# node finder
-
identifier: assign.propertyType

- '#::provideMinPhpVersion\(\) never returns \d+ so it can be removed from the return type#'
identifier: return.type
path: rules/Symfony73/NodeAnalyzer/CommandArgumentsAndOptionsResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Rector\Symfony\Tests\Symfony73\Rector\Class_\InvokableCommandRector\Fixture;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

#[AsCommand(name: 'some_name')]
final class SomeCommand extends Command
{
public function configure()
{
$this->addArgument('argument', InputArgument::REQUIRED, 'Argument description');
$this->addOption('option', 'o', InputOption::VALUE_NONE, 'Option description');
}

public function execute(InputInterface $input, OutputInterface $output): int
{
$someArgument = $input->getArgument('argument');
$someOption = $input->getOption('option');

// ...

return 1;
}
}

?>
-----
<?php

namespace Rector\Symfony\Tests\Symfony73\Rector\Class_\InvokableCommandRector\Fixture;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

#[AsCommand(name: 'some_name')]
final class SomeCommand
{
public function __invoke(#[\Symfony\Component\Console\Attribute\Command\Argument]
string $argument, #[\Symfony\Component\Console\Attribute\Command\Option]
$option): int
{
$someArgument = $argument;
$someOption = $option;

// ...

return 1;
}
}

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

declare(strict_types=1);

namespace Rector\Symfony\Tests\Symfony73\Rector\Class_\InvokableCommandRector;

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

final class InvokableCommandRectorTest 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\Symfony73\Rector\Class_\InvokableCommandRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(InvokableCommandRector::class);
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
use PHPStan\Type\ObjectType;
use Rector\PhpAttribute\NodeFactory\PhpAttributeGroupFactory;
use Rector\Rector\AbstractRector;
use Rector\Symfony\Enum\SymfonyAnnotation;
use Rector\Symfony\Enum\SymfonyAttribute;
use Rector\Symfony\Enum\SymfonyClass;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @changelog https://symfony.com/doc/current/console.html#registering-the-command
* @see https://symfony.com/doc/current/console.html#registering-the-command
*
* @see \Rector\Symfony\Tests\Symfony61\Rector\Class_\CommandConfigureToAttributeRector\CommandConfigureToAttributeRectorTest
*/
Expand Down Expand Up @@ -102,11 +103,11 @@ public function refactor(Node $node): ?Node
return null;
}

if (! $this->reflectionProvider->hasClass(SymfonyAnnotation::AS_COMMAND)) {
if (! $this->reflectionProvider->hasClass(SymfonyAttribute::AS_COMMAND)) {
return null;
}

if (! $this->isObjectType($node, new ObjectType('Symfony\\Component\\Console\\Command\\Command'))) {
if (! $this->isObjectType($node, new ObjectType(SymfonyClass::COMMAND))) {
return null;
}

Expand All @@ -120,7 +121,7 @@ public function refactor(Node $node): ?Node
$attributeArgs = [];
foreach ($node->attrGroups as $attrGroup) {
foreach ($attrGroup->attrs as $attribute) {
if (! $this->nodeNameResolver->isName($attribute->name, SymfonyAnnotation::AS_COMMAND)) {
if (! $this->nodeNameResolver->isName($attribute->name, SymfonyAttribute::AS_COMMAND)) {
continue;
}

Expand All @@ -139,7 +140,7 @@ public function refactor(Node $node): ?Node
}

if (! $asCommandAttribute instanceof Attribute) {
$asCommandAttributeGroup = $this->phpAttributeGroupFactory->createFromClass(SymfonyAnnotation::AS_COMMAND);
$asCommandAttributeGroup = $this->phpAttributeGroupFactory->createFromClass(SymfonyAttribute::AS_COMMAND);

$asCommandAttribute = $asCommandAttributeGroup->attrs[0];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use Rector\Doctrine\NodeAnalyzer\AttributeFinder;
use Rector\PhpAttribute\NodeFactory\PhpAttributeGroupFactory;
use Rector\Rector\AbstractRector;
use Rector\Symfony\Enum\SymfonyAnnotation;
use Rector\Symfony\Enum\SymfonyAttribute;
use Rector\Symfony\Enum\SymfonyClass;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
Expand Down Expand Up @@ -91,7 +91,7 @@ public function refactor(Node $node): ?Node
}

// does attribute already exist?
if (! $this->reflectionProvider->hasClass(SymfonyAnnotation::AS_COMMAND)) {
if (! $this->reflectionProvider->hasClass(SymfonyAttribute::AS_COMMAND)) {
return null;
}

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

$existingAsCommandAttribute = $this->attributeFinder->findAttributeByClass(
$node,
SymfonyAnnotation::AS_COMMAND
SymfonyAttribute::AS_COMMAND
);

$attributeArgs = $this->createAttributeArgs($defaultNameExpr, $defaultDescriptionExpr);
Expand All @@ -126,7 +126,7 @@ private function createAttributeGroupAsCommand(array $args): AttributeGroup
{
Assert::allIsInstanceOf($args, Arg::class);

$attributeGroup = $this->phpAttributeGroupFactory->createFromClass(SymfonyAnnotation::AS_COMMAND);
$attributeGroup = $this->phpAttributeGroupFactory->createFromClass(SymfonyAttribute::AS_COMMAND);
$attributeGroup->attrs[0]->args = $args;

return $attributeGroup;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

declare(strict_types=1);

namespace Rector\Symfony\Symfony73\NodeAnalyzer;

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\NodeFinder;
use Rector\Exception\ShouldNotHappenException;
use Rector\Symfony\Symfony73\ValueObject\CommandArgument;
use Rector\Symfony\Symfony73\ValueObject\CommandOption;

final class CommandArgumentsAndOptionsResolver
{
/**
* @return CommandArgument[]
*/
public function collectCommandArguments(ClassMethod $configureClassMethod): array
{
$addArgumentMethodCalls = $this->findMethodCallsByName($configureClassMethod, 'addArgument');

$commandArguments = [];
foreach ($addArgumentMethodCalls as $addArgumentMethodCall) {
// @todo extract name, type and requirements
$addArgumentArgs = $addArgumentMethodCall->getArgs();

$nameArgValue = $addArgumentArgs[0]->value;
if (! $nameArgValue instanceof String_) {
// we need string value, otherwise param will not have a name
throw new ShouldNotHappenException('Argument name is required');
}

$optionName = $nameArgValue->value;

$commandArguments[] = new CommandArgument($optionName);
}

return $commandArguments;
}

/**
* @return CommandOption[]
*/
public function collectCommandOptions(ClassMethod $configureClassMethod): array
{
$addOptionMethodCalls = $this->findMethodCallsByName($configureClassMethod, 'addOption');

$commandOptionMetadatas = [];
foreach ($addOptionMethodCalls as $addOptionMethodCall) {
// @todo extract name, type and requirements
$addOptionArgs = $addOptionMethodCall->getArgs();

$nameArgValue = $addOptionArgs[0]->value;
if (! $nameArgValue instanceof String_) {
// we need string value, otherwise param will not have a name
throw new ShouldNotHappenException('Option name is required');
}

$optionName = $nameArgValue->value;

$commandOptionMetadatas[] = new CommandOption($optionName);
}

return $commandOptionMetadatas;
}

/**
* @return MethodCall[]
*/
private function findMethodCallsByName(ClassMethod $classMethod, string $desiredMethodName): array
{
$nodeFinder = new NodeFinder();

return $nodeFinder->find($classMethod, function (Node $node) use ($desiredMethodName): bool {
if (! $node instanceof MethodCall) {
return false;
}

if (! $node->name instanceof Identifier) {
return false;
}

return $node->name->toString() === $desiredMethodName;
});
}
}
Loading
Loading