You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.8 KiB

3 years ago
  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. }