Skip to content

[Console] Invokable command #[Option] adjustments #60407

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
May 14, 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
74 changes: 53 additions & 21 deletions src/Symfony/Component/Console/Attribute/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
class Option
{
private const ALLOWED_TYPES = ['string', 'bool', 'int', 'float', 'array'];
private const ALLOWED_UNION_TYPES = ['bool|string', 'bool|int', 'bool|float'];

private string|bool|int|float|array|null $default = null;
private array|\Closure $suggestedValues;
Expand Down Expand Up @@ -56,18 +57,8 @@ public static function tryFrom(\ReflectionParameter $parameter): ?self
return null;
}

$type = $parameter->getType();
$name = $parameter->getName();

if (!$type instanceof \ReflectionNamedType) {
throw new LogicException(\sprintf('The parameter "$%s" must have a named type. Untyped, Union or Intersection types are not supported for command options.', $name));
}

$self->typeName = $type->getName();

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

if (!$parameter->isDefaultValueAvailable()) {
throw new LogicException(\sprintf('The option parameter "$%s" must declare a default value.', $name));
Expand All @@ -80,28 +71,37 @@ public static function tryFrom(\ReflectionParameter $parameter): ?self
$self->default = $parameter->getDefaultValue();
$self->allowNull = $parameter->allowsNull();

if ('bool' === $self->typeName && $self->allowNull && \in_array($self->default, [true, false], true)) {
throw new LogicException(\sprintf('The option parameter "$%s" must not be nullable when it has a default boolean value.', $name));
if ($type instanceof \ReflectionUnionType) {
return $self->handleUnion($type);
}

if ('string' === $self->typeName && null === $self->default) {
throw new LogicException(\sprintf('The option parameter "$%s" must not have a default of null.', $name));
if (!$type instanceof \ReflectionNamedType) {
throw new LogicException(\sprintf('The parameter "$%s" must have a named type. Untyped or Intersection types are not supported for command options.', $name));
}

if ('array' === $self->typeName && $self->allowNull) {
throw new LogicException(\sprintf('The option parameter "$%s" must not be nullable.', $name));
$self->typeName = $type->getName();

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

if ('bool' === $self->typeName && $self->allowNull && \in_array($self->default, [true, false], true)) {
throw new LogicException(\sprintf('The option parameter "$%s" must not be nullable when it has a default boolean value.', $name));
}

if ($self->allowNull && null !== $self->default) {
throw new LogicException(\sprintf('The option parameter "$%s" must either be not-nullable or have a default of null.', $name));
}

if ('bool' === $self->typeName) {
$self->mode = InputOption::VALUE_NONE;
if (false !== $self->default) {
$self->mode |= InputOption::VALUE_NEGATABLE;
}
} elseif ('array' === $self->typeName) {
$self->mode = InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY;
} else {
$self->mode = $self->allowNull ? InputOption::VALUE_OPTIONAL : InputOption::VALUE_REQUIRED;
if ('array' === $self->typeName) {
$self->mode |= InputOption::VALUE_IS_ARRAY;
}
$self->mode = InputOption::VALUE_REQUIRED;
}

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]])) {
Expand Down Expand Up @@ -129,6 +129,14 @@ public function resolveValue(InputInterface $input): mixed
{
$value = $input->getOption($this->name);

if (null === $value && \in_array($this->typeName, self::ALLOWED_UNION_TYPES, true)) {
return true;
}

if ('array' === $this->typeName && $this->allowNull && [] === $value) {
return null;
}

if ('bool' !== $this->typeName) {
return $value;
}
Expand All @@ -139,4 +147,28 @@ public function resolveValue(InputInterface $input): mixed

return $value ?? $this->default;
}

private function handleUnion(\ReflectionUnionType $type): self
{
$types = array_map(
static fn(\ReflectionType $t) => $t instanceof \ReflectionNamedType ? $t->getName() : null,
$type->getTypes(),
);

sort($types);

$this->typeName = implode('|', array_filter($types));

if (!\in_array($this->typeName, self::ALLOWED_UNION_TYPES, true)) {
throw new LogicException(\sprintf('The union type for parameter "$%s" is not supported as a command option. Only "%s" types are allowed.', $this->name, implode('", "', self::ALLOWED_UNION_TYPES)));
}

if (false !== $this->default) {
throw new LogicException(\sprintf('The option parameter "$%s" must have a default value of false.', $this->name));
}

$this->mode = InputOption::VALUE_OPTIONAL;

return $this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,16 @@ public function testCommandInputOptionDefinition()
#[Option(shortcut: 'v')] bool $verbose = false,
#[Option(description: 'User groups')] array $groups = [],
#[Option(suggestedValues: [self::class, 'getSuggestedRoles'])] array $roles = ['ROLE_USER'],
#[Option] string|bool $opt = false,
): int {
return 0;
});

$timeoutInputOption = $command->getDefinition()->getOption('idle');
self::assertSame('idle', $timeoutInputOption->getName());
self::assertNull($timeoutInputOption->getShortcut());
self::assertTrue($timeoutInputOption->isValueOptional());
self::assertTrue($timeoutInputOption->isValueRequired());
self::assertFalse($timeoutInputOption->isValueOptional());
self::assertFalse($timeoutInputOption->isNegatable());
self::assertNull($timeoutInputOption->getDefault());

Expand Down Expand Up @@ -120,6 +122,14 @@ public function testCommandInputOptionDefinition()
self::assertTrue($rolesInputOption->hasCompletion());
$rolesInputOption->complete(new CompletionInput(), $suggestions = new CompletionSuggestions());
self::assertSame(['ROLE_ADMIN', 'ROLE_USER'], array_map(static fn (Suggestion $s) => $s->getValue(), $suggestions->getValueSuggestions()));

$optInputOption = $command->getDefinition()->getOption('opt');
self::assertSame('opt', $optInputOption->getName());
self::assertNull($optInputOption->getShortcut());
self::assertFalse($optInputOption->isValueRequired());
self::assertTrue($optInputOption->isValueOptional());
self::assertFalse($optInputOption->isNegatable());
self::assertFalse($optInputOption->getDefault());
}

public function testInvalidArgumentType()
Expand All @@ -136,7 +146,7 @@ public function testInvalidArgumentType()
public function testInvalidOptionType()
{
$command = new Command('foo');
$command->setCode(function (#[Option] object $any) {});
$command->setCode(function (#[Option] ?object $any = null) {});

$this->expectException(LogicException::class);
$this->expectExceptionMessage('The type "object" of parameter "$any" is not supported as a command option. Only "string", "bool", "int", "float", "array" types are allowed.');
Expand Down Expand Up @@ -262,14 +272,30 @@ public function testNonBinaryInputOptions(array $parameters, array $expected)
$command = new Command('foo');
$command->setCode(function (
#[Option] string $a = '',
#[Option] ?string $b = '',
#[Option] array $c = [],
#[Option] array $d = ['a', 'b'],
#[Option] array $b = [],
#[Option] array $c = ['a', 'b'],
#[Option] bool|string $d = false,
#[Option] ?string $e = null,
#[Option] ?array $f = null,
#[Option] int $g = 0,
#[Option] ?int $h = null,
#[Option] float $i = 0.0,
#[Option] ?float $j = null,
#[Option] bool|int $k = false,
#[Option] bool|float $l = false,
) use ($expected): int {
$this->assertSame($expected[0], $a);
$this->assertSame($expected[1], $b);
$this->assertSame($expected[2], $c);
$this->assertSame($expected[3], $d);
$this->assertSame($expected[4], $e);
$this->assertSame($expected[5], $f);
$this->assertSame($expected[6], $g);
$this->assertSame($expected[7], $h);
$this->assertSame($expected[8], $i);
$this->assertSame($expected[9], $j);
$this->assertSame($expected[10], $k);
$this->assertSame($expected[11], $l);

return 0;
});
Expand All @@ -279,9 +305,18 @@ public function testNonBinaryInputOptions(array $parameters, array $expected)

public static function provideNonBinaryInputOptions(): \Generator
{
yield 'defaults' => [[], ['', '', [], ['a', 'b']]];
yield 'with-value' => [['--a' => 'x', '--b' => 'y', '--c' => ['z'], '--d' => ['c', 'd']], ['x', 'y', ['z'], ['c', 'd']]];
yield 'without-value' => [['--b' => null], ['', null, [], ['a', 'b']]];
yield 'defaults' => [
[],
['', [], ['a', 'b'], false, null, null, 0, null, 0.0, null, false, false],
];
yield 'with-value' => [
['--a' => 'x', '--b' => ['z'], '--c' => ['c', 'd'], '--d' => 'v', '--e' => 'w', '--f' => ['q'], '--g' => 1, '--h' => 2, '--i' => 3.1, '--j' => 4.2, '--k' => 5, '--l' => 6.3],
['x', ['z'], ['c', 'd'], 'v', 'w', ['q'], 1, 2, 3.1, 4.2, 5, 6.3],
];
yield 'without-value' => [
['--d' => null, '--k' => null, '--l' => null],
['', [], ['a', 'b'], true, null, null, 0, null, 0.0, null, true, true],
];
}

/**
Expand Down Expand Up @@ -312,13 +347,29 @@ function (#[Option] ?bool $a = true) {},
function (#[Option] ?bool $a = false) {},
'The option parameter "$a" must not be nullable when it has a default boolean value.',
];
yield 'nullable-string' => [
function (#[Option] ?string $a = null) {},
'The option parameter "$a" must not have a default of null.',
yield 'invalid-union-type' => [
function (#[Option] array|bool $a = false) {},
'The union type for parameter "$a" is not supported as a command option. Only "bool|string", "bool|int", "bool|float" types are allowed.',
];
yield 'union-type-cannot-allow-null' => [
function (#[Option] string|bool|null $a = null) {},
'The union type for parameter "$a" is not supported as a command option. Only "bool|string", "bool|int", "bool|float" types are allowed.',
];
yield 'union-type-default-true' => [
function (#[Option] string|bool $a = true) {},
'The option parameter "$a" must have a default value of false.',
];
yield 'union-type-default-string' => [
function (#[Option] string|bool $a = 'foo') {},
'The option parameter "$a" must have a default value of false.',
];
yield 'nullable-string-not-null-default' => [
function (#[Option] ?string $a = 'foo') {},
'The option parameter "$a" must either be not-nullable or have a default of null.',
];
yield 'nullable-array' => [
function (#[Option] ?array $a = null) {},
'The option parameter "$a" must not be nullable.',
yield 'nullable-array-not-null-default' => [
function (#[Option] ?array $a = []) {},
'The option parameter "$a" must either be not-nullable or have a default of null.',
];
}

Expand Down