Skip to content

[Console] Add broader support for command "help" definition #59473

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 1 commit into from
Jan 20, 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
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,11 @@ public function load(array $configs, ContainerBuilder $container): void
$container->registerForAutoconfiguration(AssetCompilerInterface::class)
->addTag('asset_mapper.compiler');
$container->registerAttributeForAutoconfiguration(AsCommand::class, static function (ChildDefinition $definition, AsCommand $attribute, \ReflectionClass $reflector): void {
$definition->addTag('console.command', ['command' => $attribute->name, 'description' => $attribute->description]);
$definition->addTag('console.command', [
'command' => $attribute->name,
'description' => $attribute->description,
'help' => $attribute->help,
]);
});
$container->registerForAutoconfiguration(Command::class)
->addTag('console.command');
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Component/Console/Attribute/AsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ class AsCommand
* @param string|null $description The description of the command, displayed with the help page
* @param string[] $aliases The list of aliases of the command. The command will be executed when using one of them (i.e. "cache:clean")
* @param bool $hidden If true, the command won't be shown when listing all the available commands, but it can still be run as any other command
* @param string|null $help The help content of the command, displayed with the help page
*/
public function __construct(
public string $name,
public ?string $description = null,
array $aliases = [],
bool $hidden = false,
public ?string $help = null,
) {
if (!$hidden && !$aliases) {
return;
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Console/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Add support for invokable commands and add `#[Argument]` and `#[Option]` attributes to define input arguments and options
* Deprecate not declaring the parameter type in callable commands defined through `setCode` method
* Add support for help definition via `AsCommand` attribute

7.2
---
Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/Console/Command/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ public function __construct(?string $name = null)
$this->setDescription(static::getDefaultDescription() ?? '');
}

if ('' === $this->help && $attributes = (new \ReflectionClass(static::class))->getAttributes(AsCommand::class)) {
$this->setHelp($attributes[0]->newInstance()->help ?? '');
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should either add addDefaultHelp or deprecate getDefaultName/Description to be consistent

Copy link
Member Author

@yceruto yceruto Jan 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name and description static methods remain useful for lazy commands, but this approach is not necessary for help. Additionally, introducing a new getDefaultHelp() method seems redundant since it's already possible to override getHelp() when customization is needed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would you prefer adding a private static method for getDefaultHelp() purely for the sake of consistency?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name and description static methods remain useful for lazy commands

Are they really? I miss a case where it cannot be found in the tag and #[AsCommand]

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I think I missed the fact that the AsCommand attribute is always auto-configured, so yes! they can now be deprecated. I'll make the changes in another PR, as it's not directly related to the feature proposed here.


if (\is_callable($this)) {
$this->code = new InvokableCommand($this, $this(...));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public function process(ContainerBuilder $container): void
$invokableRef = new Reference($id);
$definition = $container->register($id .= '.command', $class = Command::class)
->addMethodCall('setCode', [$invokableRef]);
} else {
$invokableRef = null;
}

$aliases = $tags[0]['command'] ?? str_replace('%', '%%', $class::getDefaultName() ?? '');
Expand All @@ -75,6 +77,7 @@ public function process(ContainerBuilder $container): void
}

$description = $tags[0]['description'] ?? null;
$help = $tags[0]['help'] ?? null;

unset($tags[0]);
$lazyCommandMap[$commandName] = $id;
Expand All @@ -91,6 +94,7 @@ public function process(ContainerBuilder $container): void
}

$description ??= $tag['description'] ?? null;
$help ??= $tag['help'] ?? null;
}

$definition->addMethodCall('setName', [$commandName]);
Expand All @@ -103,16 +107,12 @@ public function process(ContainerBuilder $container): void
$definition->addMethodCall('setHidden', [true]);
}

if (!$description) {
if (!$r = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(\sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
if (!$r->isSubclassOf(Command::class)) {
throw new InvalidArgumentException(\sprintf('The service "%s" tagged "%s" must be a subclass of "%s".', $id, 'console.command', Command::class));
}
$description = str_replace('%', '%%', $class::getDefaultDescription() ?? '');
if ($help && $invokableRef) {
$definition->addMethodCall('setHelp', [str_replace('%', '%%', $help)]);
}

$description ??= str_replace('%', '%%', $class::getDefaultDescription() ?? '');

if ($description) {
$definition->addMethodCall('setDescription', [$description]);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ public function testCommandAttribute()

$this->assertSame('foo', $command->getName());
$this->assertSame('desc', $command->getDescription());
$this->assertSame('help', $command->getHelp());
$this->assertTrue($command->isHidden());
$this->assertSame(['f'], $command->getAliases());
}
Expand Down Expand Up @@ -473,7 +474,7 @@ function createClosure()
};
}

#[AsCommand(name: 'foo', description: 'desc', hidden: true, aliases: ['f'])]
#[AsCommand(name: 'foo', description: 'desc', hidden: true, aliases: ['f'], help: 'help')]
class Php8Command extends Command
{
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ public function testEscapesDefaultFromPhp()
$this->assertSame('%cmd%', $command->getName());
$this->assertSame(['%cmdalias%'], $command->getAliases());
$this->assertSame('Creates a 80% discount', $command->getDescription());
$this->assertSame('The %command.name% help content.', $command->getHelp());
}

public function testProcessThrowAnExceptionIfTheServiceIsAbstract()
Expand Down Expand Up @@ -310,12 +311,19 @@ public function testProcessInvokableCommand()
$container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING);

$definition = new Definition(InvokableCommand::class);
$definition->addTag('console.command', ['command' => 'invokable', 'description' => 'Just testing']);
$definition->addTag('console.command', [
'command' => 'invokable',
'description' => 'The command description',
'help' => 'The %command.name% command help content.',
]);
$container->setDefinition('invokable_command', $definition);

$container->compile();
$command = $container->get('console.command_loader')->get('invokable');

self::assertTrue($container->has('invokable_command.command'));
self::assertSame('The command description', $command->getDescription());
self::assertSame('The %command.name% command help content.', $command->getHelp());
}
}

Expand All @@ -328,7 +336,7 @@ class NamedCommand extends Command
{
}

#[AsCommand(name: '%cmd%|%cmdalias%', description: 'Creates a 80% discount')]
#[AsCommand(name: '%cmd%|%cmdalias%', description: 'Creates a 80% discount', help: 'The %command.name% help content.')]
class EscapedDefaultsFromPhpCommand extends Command
{
}
Expand All @@ -346,7 +354,7 @@ public function __construct()
}
}

#[AsCommand(name: 'invokable', description: 'Just testing')]
#[AsCommand(name: 'invokable', description: 'Just testing', help: 'The %command.name% help content.')]
class InvokableCommand
{
public function __invoke(): void
Expand Down
Loading