ServiceLocator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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\Component\DependencyInjection;
  11. use Psr\Container\ContainerInterface as PsrContainerInterface;
  12. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  13. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  14. /**
  15. * @author Robin Chalas <robin.chalas@gmail.com>
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. class ServiceLocator implements PsrContainerInterface
  19. {
  20. private $factories;
  21. /**
  22. * @param callable[] $factories
  23. */
  24. public function __construct(array $factories)
  25. {
  26. $this->factories = $factories;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function has($id)
  32. {
  33. return isset($this->factories[$id]);
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function get($id)
  39. {
  40. if (!isset($this->factories[$id])) {
  41. throw new ServiceNotFoundException($id, null, null, array_keys($this->factories));
  42. }
  43. if (true === $factory = $this->factories[$id]) {
  44. throw new ServiceCircularReferenceException($id, array($id, $id));
  45. }
  46. $this->factories[$id] = true;
  47. try {
  48. return $factory();
  49. } finally {
  50. $this->factories[$id] = $factory;
  51. }
  52. }
  53. public function __invoke($id)
  54. {
  55. return isset($this->factories[$id]) ? $this->get($id) : null;
  56. }
  57. }