ServiceLocatorTrait.php 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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\ContainerExceptionInterface;
  12. use Psr\Container\NotFoundExceptionInterface;
  13. // Help opcache.preload discover always-needed symbols
  14. class_exists(ContainerExceptionInterface::class);
  15. class_exists(NotFoundExceptionInterface::class);
  16. /**
  17. * A trait to help implement ServiceProviderInterface.
  18. *
  19. * @author Robin Chalas <robin.chalas@gmail.com>
  20. * @author Nicolas Grekas <p@tchwork.com>
  21. */
  22. trait ServiceLocatorTrait
  23. {
  24. private array $loading = [];
  25. private array $providedTypes;
  26. /**
  27. * @param array<string, callable> $factories
  28. */
  29. public function __construct(
  30. private array $factories,
  31. ) {
  32. }
  33. public function has(string $id): bool
  34. {
  35. return isset($this->factories[$id]);
  36. }
  37. public function get(string $id): mixed
  38. {
  39. if (!isset($this->factories[$id])) {
  40. throw $this->createNotFoundException($id);
  41. }
  42. if (isset($this->loading[$id])) {
  43. $ids = array_values($this->loading);
  44. $ids = \array_slice($this->loading, array_search($id, $ids));
  45. $ids[] = $id;
  46. throw $this->createCircularReferenceException($id, $ids);
  47. }
  48. $this->loading[$id] = $id;
  49. try {
  50. return $this->factories[$id]($this);
  51. } finally {
  52. unset($this->loading[$id]);
  53. }
  54. }
  55. public function getProvidedServices(): array
  56. {
  57. if (!isset($this->providedTypes)) {
  58. $this->providedTypes = [];
  59. foreach ($this->factories as $name => $factory) {
  60. if (!\is_callable($factory)) {
  61. $this->providedTypes[$name] = '?';
  62. } else {
  63. $type = (new \ReflectionFunction($factory))->getReturnType();
  64. $this->providedTypes[$name] = $type ? ($type->allowsNull() ? '?' : '').($type instanceof \ReflectionNamedType ? $type->getName() : $type) : '?';
  65. }
  66. }
  67. }
  68. return $this->providedTypes;
  69. }
  70. private function createNotFoundException(string $id): NotFoundExceptionInterface
  71. {
  72. if (!$alternatives = array_keys($this->factories)) {
  73. $message = 'is empty...';
  74. } else {
  75. $last = array_pop($alternatives);
  76. if ($alternatives) {
  77. $message = \sprintf('only knows about the "%s" and "%s" services.', implode('", "', $alternatives), $last);
  78. } else {
  79. $message = \sprintf('only knows about the "%s" service.', $last);
  80. }
  81. }
  82. if ($this->loading) {
  83. $message = \sprintf('The service "%s" has a dependency on a non-existent service "%s". This locator %s', end($this->loading), $id, $message);
  84. } else {
  85. $message = \sprintf('Service "%s" not found: the current service locator %s', $id, $message);
  86. }
  87. return new class($message) extends \InvalidArgumentException implements NotFoundExceptionInterface {
  88. };
  89. }
  90. private function createCircularReferenceException(string $id, array $path): ContainerExceptionInterface
  91. {
  92. return new class(\sprintf('Circular reference detected for service "%s", path: "%s".', $id, implode(' -> ', $path))) extends \RuntimeException implements ContainerExceptionInterface {
  93. };
  94. }
  95. }