Interact.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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\Exception\LogicException;
  12. #[\Attribute(\Attribute::TARGET_METHOD)]
  13. class Interact implements InteractiveAttributeInterface
  14. {
  15. private \ReflectionMethod $method;
  16. /**
  17. * @internal
  18. */
  19. public static function tryFrom(\ReflectionMethod $method): ?self
  20. {
  21. /** @var self|null $self */
  22. if (!$self = ($method->getAttributes(self::class)[0] ?? null)?->newInstance()) {
  23. return null;
  24. }
  25. if (!$method->isPublic() || $method->isStatic()) {
  26. throw new LogicException(\sprintf('The interactive method "%s::%s()" must be public and non-static.', $method->getDeclaringClass()->getName(), $method->getName()));
  27. }
  28. if ('__invoke' === $method->getName()) {
  29. throw new LogicException(\sprintf('The "%s::__invoke()" method cannot be used as an interactive method.', $method->getDeclaringClass()->getName()));
  30. }
  31. $self->method = $method;
  32. return $self;
  33. }
  34. /**
  35. * @internal
  36. */
  37. public function getFunction(object $instance): \ReflectionFunction
  38. {
  39. return new \ReflectionFunction($this->method->getClosure($instance));
  40. }
  41. }