ServiceSubscriberTrait.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. private $container;
  22. public static function getSubscribedServices(): array
  23. {
  24. static $services;
  25. if (null !== $services) {
  26. return $services;
  27. }
  28. $services = \is_callable(['parent', __FUNCTION__]) ? parent::getSubscribedServices() : [];
  29. foreach ((new \ReflectionClass(self::class))->getMethods() as $method) {
  30. if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) {
  31. continue;
  32. }
  33. if (self::class === $method->getDeclaringClass()->name && ($returnType = $method->getReturnType()) && !$returnType->isBuiltin()) {
  34. $services[self::class.'::'.$method->name] = '?'.$returnType->getName();
  35. }
  36. }
  37. return $services;
  38. }
  39. /**
  40. * @required
  41. */
  42. public function setContainer(ContainerInterface $container)
  43. {
  44. $this->container = $container;
  45. if (\is_callable(['parent', __FUNCTION__])) {
  46. return parent::setContainer($container);
  47. }
  48. }
  49. }