ServiceSubscriberTrait.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Contracts\Service;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Contracts\Service\Attribute\SubscribedService;
  13. /**
  14. * Implementation of ServiceSubscriberInterface that determines subscribed services from
  15. * method return types. Service ids are available as "ClassName::methodName".
  16. *
  17. * @author Kevin Bond <kevinbond@gmail.com>
  18. */
  19. trait ServiceSubscriberTrait
  20. {
  21. /** @var ContainerInterface */
  22. protected $container;
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public static function getSubscribedServices(): array
  27. {
  28. $services = method_exists(get_parent_class(self::class) ?: '', __FUNCTION__) ? parent::getSubscribedServices() : [];
  29. foreach ((new \ReflectionClass(self::class))->getMethods() as $method) {
  30. if (self::class !== $method->getDeclaringClass()->name) {
  31. continue;
  32. }
  33. if (!$attribute = $method->getAttributes(SubscribedService::class)[0] ?? null) {
  34. continue;
  35. }
  36. if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) {
  37. throw new \LogicException(sprintf('Cannot use "%s" on method "%s::%s()" (can only be used on non-static, non-abstract methods with no parameters).', SubscribedService::class, self::class, $method->name));
  38. }
  39. if (!$returnType = $method->getReturnType()) {
  40. throw new \LogicException(sprintf('Cannot use "%s" on methods without a return type in "%s::%s()".', SubscribedService::class, $method->name, self::class));
  41. }
  42. $serviceId = $returnType instanceof \ReflectionNamedType ? $returnType->getName() : (string) $returnType;
  43. if ($returnType->allowsNull()) {
  44. $serviceId = '?'.$serviceId;
  45. }
  46. $services[$attribute->newInstance()->key ?? self::class.'::'.$method->name] = $serviceId;
  47. }
  48. return $services;
  49. }
  50. /**
  51. * @required
  52. */
  53. public function setContainer(ContainerInterface $container): ?ContainerInterface
  54. {
  55. $this->container = $container;
  56. if (method_exists(get_parent_class(self::class) ?: '', __FUNCTION__)) {
  57. return parent::setContainer($container);
  58. }
  59. return null;
  60. }
  61. }