Option.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Attribute;
  11. use Symfony\Component\Console\Attribute\Reflection\ReflectionMember;
  12. use Symfony\Component\Console\Completion\CompletionInput;
  13. use Symfony\Component\Console\Completion\Suggestion;
  14. use Symfony\Component\Console\Exception\InvalidOptionException;
  15. use Symfony\Component\Console\Exception\LogicException;
  16. use Symfony\Component\Console\Input\InputInterface;
  17. use Symfony\Component\Console\Input\InputOption;
  18. use Symfony\Component\String\UnicodeString;
  19. #[\Attribute(\Attribute::TARGET_PARAMETER | \Attribute::TARGET_PROPERTY)]
  20. class Option
  21. {
  22. private const ALLOWED_TYPES = ['string', 'bool', 'int', 'float', 'array'];
  23. private const ALLOWED_UNION_TYPES = ['bool|string', 'bool|int', 'bool|float'];
  24. private string|bool|int|float|array|null $default = null;
  25. private array|\Closure $suggestedValues;
  26. private ?int $mode = null;
  27. /**
  28. * @var string|class-string<\BackedEnum>
  29. */
  30. private string $typeName = '';
  31. private bool $allowNull = false;
  32. private string $memberName = '';
  33. private string $sourceName = '';
  34. /**
  35. * Represents a console command --option definition.
  36. *
  37. * If unset, the `name` value will be inferred from the parameter definition.
  38. *
  39. * @param array|string|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
  40. * @param array<string|Suggestion>|callable(CompletionInput):list<string|Suggestion> $suggestedValues The values used for input completion
  41. */
  42. public function __construct(
  43. public string $description = '',
  44. public string $name = '',
  45. public array|string|null $shortcut = null,
  46. array|callable $suggestedValues = [],
  47. ) {
  48. $this->suggestedValues = \is_callable($suggestedValues) ? $suggestedValues(...) : $suggestedValues;
  49. }
  50. /**
  51. * @internal
  52. */
  53. public static function tryFrom(\ReflectionParameter|\ReflectionProperty $member): ?self
  54. {
  55. $reflection = new ReflectionMember($member);
  56. if (!$self = $reflection->getAttribute(self::class)) {
  57. return null;
  58. }
  59. $self->memberName = $reflection->getMemberName();
  60. $self->sourceName = $reflection->getSourceName();
  61. $name = $reflection->getName();
  62. $type = $reflection->getType();
  63. if (!$reflection->hasDefaultValue()) {
  64. throw new LogicException(\sprintf('The option %s "$%s" of "%s" must declare a default value.', $self->memberName, $name, $self->sourceName));
  65. }
  66. if (!$self->name) {
  67. $self->name = (new UnicodeString($name))->kebab();
  68. }
  69. $self->default = $reflection->getDefaultValue();
  70. $self->allowNull = $reflection->isNullable();
  71. if ($type instanceof \ReflectionUnionType) {
  72. return $self->handleUnion($type);
  73. }
  74. if (!$type instanceof \ReflectionNamedType) {
  75. throw new LogicException(\sprintf('The %s "$%s" of "%s" must have a named type. Untyped or Intersection types are not supported for command options.', $self->memberName, $name, $self->sourceName));
  76. }
  77. $self->typeName = $type->getName();
  78. $isBackedEnum = is_subclass_of($self->typeName, \BackedEnum::class);
  79. if (!\in_array($self->typeName, self::ALLOWED_TYPES, true) && !$isBackedEnum) {
  80. throw new LogicException(\sprintf('The type "%s" on %s "$%s" of "%s" is not supported as a command option. Only "%s" types and BackedEnum are allowed.', $self->typeName, $self->memberName, $name, $self->sourceName, implode('", "', self::ALLOWED_TYPES)));
  81. }
  82. if ('bool' === $self->typeName && $self->allowNull && \in_array($self->default, [true, false], true)) {
  83. throw new LogicException(\sprintf('The option %s "$%s" of "%s" must not be nullable when it has a default boolean value.', $self->memberName, $name, $self->sourceName));
  84. }
  85. if ($self->allowNull && null !== $self->default) {
  86. throw new LogicException(\sprintf('The option %s "$%s" of "%s" must either be not-nullable or have a default of null.', $self->memberName, $name, $self->sourceName));
  87. }
  88. if ('bool' === $self->typeName) {
  89. $self->mode = InputOption::VALUE_NONE;
  90. if (false !== $self->default) {
  91. $self->mode |= InputOption::VALUE_NEGATABLE;
  92. }
  93. } elseif ('array' === $self->typeName) {
  94. $self->mode = InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY;
  95. } else {
  96. $self->mode = InputOption::VALUE_REQUIRED;
  97. }
  98. if (\is_array($self->suggestedValues) && !\is_callable($self->suggestedValues) && 2 === \count($self->suggestedValues) && ($instance = $reflection->getSourceThis()) && $instance::class === $self->suggestedValues[0] && \is_callable([$instance, $self->suggestedValues[1]])) {
  99. $self->suggestedValues = [$instance, $self->suggestedValues[1]];
  100. }
  101. if ($isBackedEnum && !$self->suggestedValues) {
  102. $self->suggestedValues = array_column($self->typeName::cases(), 'value');
  103. }
  104. return $self;
  105. }
  106. /**
  107. * @internal
  108. */
  109. public function toInputOption(): InputOption
  110. {
  111. $default = InputOption::VALUE_NONE === (InputOption::VALUE_NONE & $this->mode) ? null : $this->default;
  112. $suggestedValues = \is_callable($this->suggestedValues) ? ($this->suggestedValues)(...) : $this->suggestedValues;
  113. return new InputOption($this->name, $this->shortcut, $this->mode, $this->description, $default, $suggestedValues);
  114. }
  115. /**
  116. * @internal
  117. */
  118. public function resolveValue(InputInterface $input): mixed
  119. {
  120. $value = $input->getOption($this->name);
  121. if (null === $value && \in_array($this->typeName, self::ALLOWED_UNION_TYPES, true)) {
  122. return true;
  123. }
  124. if (is_subclass_of($this->typeName, \BackedEnum::class) && (\is_string($value) || \is_int($value))) {
  125. return $this->typeName::tryFrom($value) ?? throw InvalidOptionException::fromEnumValue($this->name, $value, $this->suggestedValues);
  126. }
  127. if ('array' === $this->typeName && $this->allowNull && [] === $value) {
  128. return null;
  129. }
  130. if ('bool' !== $this->typeName) {
  131. return $value;
  132. }
  133. if ($this->allowNull && null === $value) {
  134. return null;
  135. }
  136. return $value ?? $this->default;
  137. }
  138. private function handleUnion(\ReflectionUnionType $type): self
  139. {
  140. $types = array_map(
  141. static fn (\ReflectionType $t) => $t instanceof \ReflectionNamedType ? $t->getName() : null,
  142. $type->getTypes(),
  143. );
  144. sort($types);
  145. $this->typeName = implode('|', array_filter($types));
  146. if (!\in_array($this->typeName, self::ALLOWED_UNION_TYPES, true)) {
  147. throw new LogicException(\sprintf('The union type for %s "$%s" of "%s" is not supported as a command option. Only "%s" types are allowed.', $this->memberName, $this->name, $this->sourceName, implode('", "', self::ALLOWED_UNION_TYPES)));
  148. }
  149. if (false !== $this->default) {
  150. throw new LogicException(\sprintf('The option %s "$%s" of "%s" must have a default value of false.', $this->memberName, $this->name, $this->sourceName));
  151. }
  152. $this->mode = InputOption::VALUE_OPTIONAL;
  153. return $this;
  154. }
  155. }