8000 [Console] Support `BackedEnum` in invokable commands by GromNaN · Pull Request #60586 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Console] Support BackedEnum in invokable commands #60586

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
Jun 11, 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
27 changes: 21 additions & 6 deletions src/Symfony/Component/Console/Attribute/Argument.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\Suggestion;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Excepti 8000 on\LogicException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -27,6 +28,7 @@ class Argument
private array|\Closure $suggestedValues;
private ?int $mode = null;
private string $function = '';
private string $typeName = '';
Copy link
Member Author

Choose a reason for hiding this comment

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

The Option attribute already has this same property.


/**
* Represents a console command <argument> definition.
Expand Down Expand Up @@ -66,27 +68,34 @@ public static function tryFrom(\ReflectionParameter $parameter): ?self
throw new LogicException(\sprintf('The parameter "$%s" of "%s()" must have a named type. Untyped, Union or Intersection types are not supported for command arguments.', $name, $self->function));
}

$parameterTypeName = $type->getName();
$self->typeName = $type->getName();
$isBackedEnum = is_subclass_of($self->typeName, \BackedEnum::class);

if (!\in_array($parameterTypeName, self::ALLOWED_TYPES, true)) {
throw new LogicException(\sprintf('The type "%s" on parameter "$%s" of "%s()" is not supported as a command argument. Only "%s" types are allowed.', $parameterTypeName, $name, $self->function, implode('", "', self::ALLOWED_TYPES)));
if (!\in_array($self->typeName, self::ALLOWED_TYPES, true) && ! 8000 $isBackedEnum) {
throw new LogicException(\sprintf('The type "%s" on parameter "$%s" of "%s()" is not supported as a command argument. Only "%s" types and backed enums are allowed.', $self->typeName, $name, $self->function, implode('", "', self::ALLOWED_TYPES)));
}

if (!$self->name) {
$self->name = (new UnicodeString($name))->kebab();
}

$self->default = $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null;
if ($parameter->isDefaultValueAvailable()) {
$self->default = $parameter->getDefaultValue() instanceof \BackedEnum ? $parameter->getDefaultValue()->value : $parameter->getDefaultValue();
}

$self->mode = $parameter->isDefaultValueAvailable() || $parameter->allowsNull() ? InputArgument::OPTIONAL : InputArgument::REQUIRED;
if ('array' === $parameterTypeName) {
if ('array' === $self->typeName) {
$self->mode |= InputArgument::IS_ARRAY;
}

if (\is_array($self->suggestedValues) && !\is_callable($self->suggestedValues) && 2 === \count($self->suggestedValues) && ($instance = $parameter->getDeclaringFunction()->getClosureThis()) && $instance::class === $self->suggestedValues[0] && \is_callable([$instance, $self->suggestedValues[1]])) {
$self->suggestedValues = [$instance, $self->suggestedValues[1]];
}

if ($isBackedEnum && !$self->suggestedValues) {
$self->suggestedValues = array_column(($self->typeName)::cases(), 'value');
}

return $self;
}

Expand All @@ -105,6 +114,12 @@ public function toInputArgument(): InputArgument
*/
public function resolveValue(InputInterface $input): mixed
{
return $input->getArgument($this->name);
$value = $input->getArgument($this->name);

if (is_subclass_of($this->typeName, \BackedEnum::class) && (is_string($value) || is_int($value))) {
return ($this->typeName)::tryFrom($value) ?? throw InvalidArgumentException::fromEnumValue($this->name, $value, $this->suggestedValues);
}

return $value;
}
}
16 changes: 13 additions & 3 deletions src/Symfony/Component/Console/Attribute/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\Suggestion;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
Expand Down Expand Up @@ -75,7 +76,7 @@ public static function tryFrom(\ReflectionParameter $parameter): ?self
$self->name = (new UnicodeString($name))->kebab();
}

$self->default = $parameter->getDefaultValue();
$self->default = $parameter->getDefaultValue() instanceof \BackedEnum ? $parameter->getDefaultValue()->value : $parameter->getDefaultValue();
$self->allowNull = $parameter->allowsNull();

if ($type instanceof \ReflectionUnionType) {
Expand All @@ -87,9 +88,10 @@ public static function tryFrom(\ReflectionParameter $parameter): ?self
}

$self->typeName = $type->getName();
$isBackedEnum = is_subclass_of($self->typeName, \BackedEnum::class);

if (!\in_array($self->typeName, self::ALLOWED_TYPES, true)) {
throw new LogicException(\sprintf('The type "%s" on parameter "$%s" of "%s()" is not supported as a command option. Only "%s" types are allowed.', $self->typeName, $name, $self->function, implode('", "', self::ALLOWED_TYPES)));
if (!\in_array($self->typeName, self::ALLOWED_TYPES, true) && !$isBackedEnum) {
throw new LogicException(\sprintf('The type "%s" on parameter "$%s" of "%s()" is not supported as a command option. Only "%s" types and BackedEnum are allowed.', $self->typeName, $name, $self->function, implode('", "', self::ALLOWED_TYPES)));
}

if ('bool' === $self->typeName && $self->allowNull && \in_array($self->default, [true, false], true)) {
Expand All @@ -115,6 +117,10 @@ public static function tryFrom(\ReflectionParameter $parameter): ?self
$self->suggestedValues = [$instance, $self->suggestedValues[1]];
}

if ($isBackedEnum && !$self->suggestedValues) {
$self->suggestedValues = array_column(($self->typeName)::cases(), 'value');
}

return $self;
}

Expand All @@ -140,6 +146,10 @@ public function resolveValue(InputInterface $input): mixed
return true;
}

if (is_subclass_of($this->typeName, \BackedEnum::class) && (is_string($value) || is_int($value))) {
return ($this->typeName)::tryFrom($value) ?? throw InvalidOptionException::fromEnumValue($this->name, $value, $this->suggestedValues);
}

if ('array' === $this->typeName && $this->allowNull && [] === $value) {
return null;
}
8000 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 @@ -7,6 +7,7 @@ CHANGELOG
* Allow setting aliases and the hidden flag via the command name passed to the constructor
* Introduce `Symfony\Component\Console\Application::addCommand()` to simplify using invokable commands when the component is used standalone
* Deprecate `Symfony\Component\Console\Application::add()` in favor of `Symfony\Component\Console\Application::addCommand()`
* Add `BackedEnum` support with `#[Argument]` and `#[Option]` inputs in invokable commands

7.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,17 @@
*/
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
/**
* @internal
*/
public static function fromEnumValue(string $name, string $value, array|\Closure $suggestedValues): self
{
$error = \sprintf('The value "%s" is not valid for the "%s" argument.', $value, $name);

if (\is_array($suggestedValues)) {
$error .= \sprintf(' Supported values are "%s".', implode('", "', $suggestedValues));
}

return new self($error);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,17 @@
*/
class InvalidOptionException extends \InvalidArgumentException implements ExceptionInterface
{
/**
* @internal
*/
public static function fromEnumValue(string $name, string $value, array|\Closure $suggestedValues): self
{
$error = \sprintf('The value "%s" is not valid for the "%s" option.', $value, $name);

if (\is_array($suggestedValues)) {
$error .= \sprintf(' Supported values are "%s".', implode('", "', $suggestedValues));
}

return new self($error);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@

namespace Symfony\Component\Console\Tests\Command;

use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\Option;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\CompletionSuggestions;
use Symfony\Component\Console\Completion\Suggestion;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Input\ArrayInput;
Expand Down Expand Up @@ -132,6 +134,88 @@ public function testCommandInputOptionDefinition()
self::assertFalse($optInputOption->getDefault());
}

public function testEnumArgument()
{
$command = new Command('foo');
$command->setCode(function (
#[Argument] StringEnum $enum,
#[Argument] StringEnum $enumWithDefault = StringEnum::Image,
#[Argument] ?StringEnum $nullableEnum = null,
): int {
Assert::assertSame(StringEnum::Image, $enum);
Assert::assertSame(StringEnum::Image, $enumWithDefault);
Assert::assertNull($nullableEnum);

return 0;
});

$enumInputArgument = $command->getDefinition()->getArgument('enum');
self::assertTrue($enumInputArgument->isRequired());
self::assertNull($enumInputArgument->getDefault());
self::assertTrue($enumInputArgument->hasCompletion());

$enumWithDefaultInputArgument = $command->getDefinition()->getArgument('enum-with-default');
self::assertFalse($enumWithDefaultInputArgument->isRequired());
self::assertSame('image', $enumWithDefaultInputArgument->getDefault());
self::assertTrue($enumWithDefaultInputArgument->hasCompletion());

$nullableEnumInputArgument = $command->getDefinition()->getArgument('nullable-enum');
self::assertFalse($nullableEnumInputArgument->isRequired());
self::assertNull($nullableEnumInputArgument->getDefault());
self::assertTrue($nullableEnumInputArgument->hasCompletion());

$enumInputArgument->complete(CompletionInput::fromTokens([], 0), $suggestions = new CompletionSuggestions());
self::assertEquals([new Suggestion('image'), new Suggestion('video')], $suggestions->getValueSuggestions());

$command->run(new ArrayInput(['enum' => 'image']), new NullOutput());

self::expectException(InvalidArgumentException::class);
self::expectExceptionMessage('The value "incorrect" is not valid for the "enum" argument. Supported values are "image", "video".');

$command->run(new ArrayInput(['enum' => 'incorrect']), new NullOutput());
}

public function testEnumOption()
{
$command = new Command('foo');
$command->setCode(function (
#[Option] StringEnum $enum = StringEnum::Video,
#[Option] StringEnum $enumWithDefault = StringEnum::Image,
#[Option] ?StringEnum $nullableEnum = null,
): int {
Assert::assertSame(StringEnum::Image, $enum);
Assert::assertSame(StringEnum::Image, $enumWithDefault);
Assert::assertNull($nullableEnum);

return 0;
});

$enumInputOption = $command->getDefinition()->getOption('enum');
self::assertTrue($enumInputOption->isValueRequired());
self::assertSame('video', $enumInputOption->getDefault());
self::assertTrue($enumInputOption->hasCompletion());

$enumWithDefaultInputOption = $command->getDefinition()->getOption('enum-with-default');
self::assertTrue($enumWithDefaultInputOption->isValueRequired());
self::assertSame('image', $enumWithDefaultInputOption->getDefault());
self::assertTrue($enumWithDefaultInputOption->hasCompletion());

$nullableEnumInputOption = $command->getDefinition()->getOption('nullable-enum');
self::assertTrue($nullableEnumInputOption->isValueRequired());
self::assertNull($nullableEnumInputOption->getDefault());
self::assertTrue($nullableEnumInputOption->hasCompletion());

$enumInputOption->complete(CompletionInput::fromTokens([], 0), $suggestions = new CompletionSuggestions());
self::assertEquals([new Suggestion('image'), new Suggestion('video')], $suggestions->getValueSuggestions());

$command->run(new ArrayInput(['--enum' => 'image']), new NullOutput());

self::expectException(InvalidOptionException::class);
self::expectExceptionMessage('The value "incorrect" is not valid for the "enum" option. Supported values are "image", "video".');

$command->run(new ArrayInput(['--enum' => 'incorrect']), new NullOutput());
}

public function testInvalidArgumentType()
{
$command = new Command('foo');
Expand Down Expand Up @@ -377,3 +461,9 @@ public function getSuggestedRoles(CompletionInput $input): array
return ['ROLE_ADMIN', 'ROLE_USER'];
}
}

enum StringEnum: string
{
case Image = 'image';
case Video = 'video';
}
0