vendor/symfony/dependency-injection/Container.php line 410

  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 Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
  12. use Symfony\Component\DependencyInjection\Argument\ServiceLocator as ArgumentServiceLocator;
  13. use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
  14. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  15. use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
  16. use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
  17. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  18. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  19. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  20. use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
  21. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  22. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  23. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  24. use Symfony\Contracts\Service\ResetInterface;
  25. // Help opcache.preload discover always-needed symbols
  26. class_exists(RewindableGenerator::class);
  27. class_exists(ArgumentServiceLocator::class);
  28. /**
  29.  * Container is a dependency injection container.
  30.  *
  31.  * It gives access to object instances (services).
  32.  * Services and parameters are simple key/pair stores.
  33.  * The container can have four possible behaviors when a service
  34.  * does not exist (or is not initialized for the last case):
  35.  *
  36.  *  * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception at compilation time (the default)
  37.  *  * NULL_ON_INVALID_REFERENCE:      Returns null
  38.  *  * IGNORE_ON_INVALID_REFERENCE:    Ignores the wrapping command asking for the reference
  39.  *                                    (for instance, ignore a setter if the service does not exist)
  40.  *  * IGNORE_ON_UNINITIALIZED_REFERENCE: Ignores/returns null for uninitialized services or invalid references
  41.  *  * RUNTIME_EXCEPTION_ON_INVALID_REFERENCE: Throws an exception at runtime
  42.  *
  43.  * @author Fabien Potencier <fabien@symfony.com>
  44.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  45.  */
  46. class Container implements ContainerInterfaceResetInterface
  47. {
  48.     protected $parameterBag;
  49.     protected $services = [];
  50.     protected $privates = [];
  51.     protected $fileMap = [];
  52.     protected $methodMap = [];
  53.     protected $factories = [];
  54.     protected $aliases = [];
  55.     protected $loading = [];
  56.     protected $resolving = [];
  57.     protected $syntheticIds = [];
  58.     private array $envCache = [];
  59.     private bool $compiled false;
  60.     private \Closure $getEnv;
  61.     private static \Closure $make;
  62.     public function __construct(?ParameterBagInterface $parameterBag null)
  63.     {
  64.         $this->parameterBag $parameterBag ?? new EnvPlaceholderParameterBag();
  65.     }
  66.     /**
  67.      * Compiles the container.
  68.      *
  69.      * This method does two things:
  70.      *
  71.      *  * Parameter values are resolved;
  72.      *  * The parameter bag is frozen.
  73.      *
  74.      * @return void
  75.      */
  76.     public function compile()
  77.     {
  78.         $this->parameterBag->resolve();
  79.         $this->parameterBag = new FrozenParameterBag(
  80.             $this->parameterBag->all(),
  81.             $this->parameterBag instanceof ParameterBag $this->parameterBag->allDeprecated() : []
  82.         );
  83.         $this->compiled true;
  84.     }
  85.     /**
  86.      * Returns true if the container is compiled.
  87.      */
  88.     public function isCompiled(): bool
  89.     {
  90.         return $this->compiled;
  91.     }
  92.     /**
  93.      * Gets the service container parameter bag.
  94.      */
  95.     public function getParameterBag(): ParameterBagInterface
  96.     {
  97.         return $this->parameterBag;
  98.     }
  99.     /**
  100.      * Gets a parameter.
  101.      *
  102.      * @return array|bool|string|int|float|\UnitEnum|null
  103.      *
  104.      * @throws ParameterNotFoundException if the parameter is not defined
  105.      */
  106.     public function getParameter(string $name)
  107.     {
  108.         return $this->parameterBag->get($name);
  109.     }
  110.     public function hasParameter(string $name): bool
  111.     {
  112.         return $this->parameterBag->has($name);
  113.     }
  114.     /**
  115.      * @return void
  116.      */
  117.     public function setParameter(string $name, array|bool|string|int|float|\UnitEnum|null $value)
  118.     {
  119.         $this->parameterBag->set($name$value);
  120.     }
  121.     /**
  122.      * Sets a service.
  123.      *
  124.      * Setting a synthetic service to null resets it: has() returns false and get()
  125.      * behaves in the same way as if the service was never created.
  126.      *
  127.      * @return void
  128.      */
  129.     public function set(string $id, ?object $service)
  130.     {
  131.         // Runs the internal initializer; used by the dumped container to include always-needed files
  132.         if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
  133.             $initialize $this->privates['service_container'];
  134.             unset($this->privates['service_container']);
  135.             $initialize($this);
  136.         }
  137.         if ('service_container' === $id) {
  138.             throw new InvalidArgumentException('You cannot set service "service_container".');
  139.         }
  140.         if (!(isset($this->fileMap[$id]) || isset($this->methodMap[$id]))) {
  141.             if (isset($this->syntheticIds[$id]) || !isset($this->getRemovedIds()[$id])) {
  142.                 // no-op
  143.             } elseif (null === $service) {
  144.                 throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot unset it.'$id));
  145.             } else {
  146.                 throw new InvalidArgumentException(sprintf('The "%s" service is private, you cannot replace it.'$id));
  147.             }
  148.         } elseif (isset($this->services[$id])) {
  149.             throw new InvalidArgumentException(sprintf('The "%s" service is already initialized, you cannot replace it.'$id));
  150.         }
  151.         if (isset($this->aliases[$id])) {
  152.             unset($this->aliases[$id]);
  153.         }
  154.         if (null === $service) {
  155.             unset($this->services[$id]);
  156.             return;
  157.         }
  158.         $this->services[$id] = $service;
  159.     }
  160.     public function has(string $id): bool
  161.     {
  162.         if (isset($this->aliases[$id])) {
  163.             $id $this->aliases[$id];
  164.         }
  165.         if (isset($this->services[$id])) {
  166.             return true;
  167.         }
  168.         if ('service_container' === $id) {
  169.             return true;
  170.         }
  171.         return isset($this->fileMap[$id]) || isset($this->methodMap[$id]);
  172.     }
  173.     /**
  174.      * Gets a service.
  175.      *
  176.      * @throws ServiceCircularReferenceException When a circular reference is detected
  177.      * @throws ServiceNotFoundException          When the service is not defined
  178.      *
  179.      * @see Reference
  180.      */
  181.     public function get(string $idint $invalidBehavior self::EXCEPTION_ON_INVALID_REFERENCE): ?object
  182.     {
  183.         return $this->services[$id]
  184.             ?? $this->services[$id $this->aliases[$id] ?? $id]
  185.             ?? ('service_container' === $id $this : ($this->factories[$id] ?? self::$make ??= self::make(...))($this$id$invalidBehavior));
  186.     }
  187.     /**
  188.      * Creates a service.
  189.      *
  190.      * As a separate method to allow "get()" to use the really fast `??` operator.
  191.      */
  192.     private static function make(self $containerstring $idint $invalidBehavior): ?object
  193.     {
  194.         if (isset($container->loading[$id])) {
  195.             throw new ServiceCircularReferenceException($idarray_merge(array_keys($container->loading), [$id]));
  196.         }
  197.         $container->loading[$id] = true;
  198.         try {
  199.             if (isset($container->fileMap[$id])) {
  200.                 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $container->load($container->fileMap[$id]);
  201.             } elseif (isset($container->methodMap[$id])) {
  202.                 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $container->{$container->methodMap[$id]}($container);
  203.             }
  204.         } catch (\Exception $e) {
  205.             unset($container->services[$id]);
  206.             throw $e;
  207.         } finally {
  208.             unset($container->loading[$id]);
  209.         }
  210.         if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  211.             if (!$id) {
  212.                 throw new ServiceNotFoundException($id);
  213.             }
  214.             if (isset($container->syntheticIds[$id])) {
  215.                 throw new ServiceNotFoundException($idnullnull, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.'$id));
  216.             }
  217.             if (isset($container->getRemovedIds()[$id])) {
  218.                 throw new ServiceNotFoundException($idnullnull, [], sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.'$id));
  219.             }
  220.             $alternatives = [];
  221.             foreach ($container->getServiceIds() as $knownId) {
  222.                 if ('' === $knownId || '.' === $knownId[0]) {
  223.                     continue;
  224.                 }
  225.                 $lev levenshtein($id$knownId);
  226.                 if ($lev <= \strlen($id) / || str_contains($knownId$id)) {
  227.                     $alternatives[] = $knownId;
  228.                 }
  229.             }
  230.             throw new ServiceNotFoundException($idnullnull$alternatives);
  231.         }
  232.         return null;
  233.     }
  234.     /**
  235.      * Returns true if the given service has actually been initialized.
  236.      */
  237.     public function initialized(string $id): bool
  238.     {
  239.         if (isset($this->aliases[$id])) {
  240.             $id $this->aliases[$id];
  241.         }
  242.         if ('service_container' === $id) {
  243.             return false;
  244.         }
  245.         return isset($this->services[$id]);
  246.     }
  247.     /**
  248.      * @return void
  249.      */
  250.     public function reset()
  251.     {
  252.         $services $this->services $this->privates;
  253.         $this->services $this->factories $this->privates = [];
  254.         foreach ($services as $service) {
  255.             try {
  256.                 if ($service instanceof ResetInterface) {
  257.                     $service->reset();
  258.                 }
  259.             } catch (\Throwable) {
  260.                 continue;
  261.             }
  262.         }
  263.     }
  264.     /**
  265.      * Gets all service ids.
  266.      *
  267.      * @return string[]
  268.      */
  269.     public function getServiceIds(): array
  270.     {
  271.         return array_map('strval'array_unique(array_merge(['service_container'], array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->aliases), array_keys($this->services))));
  272.     }
  273.     /**
  274.      * Gets service ids that existed at compile time.
  275.      */
  276.     public function getRemovedIds(): array
  277.     {
  278.         return [];
  279.     }
  280.     /**
  281.      * Camelizes a string.
  282.      */
  283.     public static function camelize(string $id): string
  284.     {
  285.         return strtr(ucwords(strtr($id, ['_' => ' ''.' => '_ ''\\' => '_ '])), [' ' => '']);
  286.     }
  287.     /**
  288.      * A string to underscore.
  289.      */
  290.     public static function underscore(string $id): string
  291.     {
  292.         return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/''/([a-z\d])([A-Z])/'], ['\\1_\\2''\\1_\\2'], str_replace('_''.'$id)));
  293.     }
  294.     /**
  295.      * Creates a service by requiring its factory file.
  296.      *
  297.      * @return mixed
  298.      */
  299.     protected function load(string $file)
  300.     {
  301.         return require $file;
  302.     }
  303.     /**
  304.      * Fetches a variable from the environment.
  305.      *
  306.      * @throws EnvNotFoundException When the environment variable is not found and has no default value
  307.      */
  308.     protected function getEnv(string $name): mixed
  309.     {
  310.         if (isset($this->resolving[$envName "env($name)"])) {
  311.             throw new ParameterCircularReferenceException(array_keys($this->resolving));
  312.         }
  313.         if (isset($this->envCache[$name]) || \array_key_exists($name$this->envCache)) {
  314.             return $this->envCache[$name];
  315.         }
  316.         if (!$this->has($id 'container.env_var_processors_locator')) {
  317.             $this->set($id, new ServiceLocator([]));
  318.         }
  319.         $this->getEnv ??= $this->getEnv(...);
  320.         $processors $this->get($id);
  321.         if (false !== $i strpos($name':')) {
  322.             $prefix substr($name0$i);
  323.             $localName substr($name$i);
  324.         } else {
  325.             $prefix 'string';
  326.             $localName $name;
  327.         }
  328.         $processor $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  329.         if (false === $i) {
  330.             $prefix '';
  331.         }
  332.         $this->resolving[$envName] = true;
  333.         try {
  334.             return $this->envCache[$name] = $processor->getEnv($prefix$localName$this->getEnv);
  335.         } finally {
  336.             unset($this->resolving[$envName]);
  337.         }
  338.     }
  339.     /**
  340.      * @internal
  341.      */
  342.     final protected function getService(string|false $registrystring $id, ?string $methodstring|bool $load): mixed
  343.     {
  344.         if ('service_container' === $id) {
  345.             return $this;
  346.         }
  347.         if (\is_string($load)) {
  348.             throw new RuntimeException($load);
  349.         }
  350.         if (null === $method) {
  351.             return false !== $registry $this->{$registry}[$id] ?? null null;
  352.         }
  353.         if (false !== $registry) {
  354.             return $this->{$registry}[$id] ??= $load $this->load($method) : $this->{$method}($this);
  355.         }
  356.         if (!$load) {
  357.             return $this->{$method}($this);
  358.         }
  359.         return ($factory $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory($this) : $this->load($method);
  360.     }
  361.     private function __clone()
  362.     {
  363.     }
  364. }