ServiceSubscriberTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /**
  13. * Implementation of ServiceSubscriberInterface that determines subscribed services from
  14. * private method return types. Service ids are available as "ClassName::methodName".
  15. *
  16. * @author Kevin Bond <kevinbond@gmail.com>
  17. */
  18. trait ServiceSubscriberTrait
  19. {
  20. /** @var ContainerInterface */
  21. protected $container;
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public static function getSubscribedServices(): array
  26. {
  27. static $services;
  28. if (null !== $services) {
  29. return $services;
  30. }
  31. $services = \is_callable(['parent', __FUNCTION__]) ? parent::getSubscribedServices() : [];
  32. foreach ((new \ReflectionClass(self::class))->getMethods() as $method) {
  33. if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) {
  34. continue;
  35. }
  36. if (self::class === $method->getDeclaringClass()->name && ($returnType = $method->getReturnType()) && !$returnType->isBuiltin()) {
  37. $services[self::class.'::'.$method->name] = '?'.($returnType instanceof \ReflectionNamedType ? $returnType->getName() : $returnType);
  38. }
  39. }
  40. return $services;
  41. }
  42. /**
  43. * @required
  44. */
  45. public function setContainer(ContainerInterface $container)
  46. {
  47. $this->container = $container;
  48. if (\is_callable(['parent', __FUNCTION__])) {
  49. return parent::setContainer($container);
  50. }
  51. return null;
  52. }
  53. }