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 $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.      * @throws \Exception                        if an exception has been thrown when the service has been resolved
  179.      *
  180.      * @see Reference
  181.      */
  182.     public function get(string $idint $invalidBehavior self::EXCEPTION_ON_INVALID_REFERENCE): ?object
  183.     {
  184.         return $this->services[$id]
  185.             ?? $this->services[$id $this->aliases[$id] ?? $id]
  186.             ?? ('service_container' === $id $this : ($this->factories[$id] ?? self::$make ??= self::make(...))($this$id$invalidBehavior));
  187.     }
  188.     /**
  189.      * Creates a service.
  190.      *
  191.      * As a separate method to allow "get()" to use the really fast `??` operator.
  192.      */
  193.     private static function make(self $containerstring $idint $invalidBehavior): ?object
  194.     {
  195.         if (isset($container->loading[$id])) {
  196.             throw new ServiceCircularReferenceException($idarray_merge(array_keys($container->loading), [$id]));
  197.         }
  198.         $container->loading[$id] = true;
  199.         try {
  200.             if (isset($container->fileMap[$id])) {
  201.                 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $container->load($container->fileMap[$id]);
  202.             } elseif (isset($container->methodMap[$id])) {
  203.                 return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ === $invalidBehavior null $container->{$container->methodMap[$id]}($container);
  204.             }
  205.         } catch (\Exception $e) {
  206.             unset($container->services[$id]);
  207.             throw $e;
  208.         } finally {
  209.             unset($container->loading[$id]);
  210.         }
  211.         if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
  212.             if (!$id) {
  213.                 throw new ServiceNotFoundException($id);
  214.             }
  215.             if (isset($container->syntheticIds[$id])) {
  216.                 throw new ServiceNotFoundException($idnullnull, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.'$id));
  217.             }
  218.             if (isset($container->getRemovedIds()[$id])) {
  219.                 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));
  220.             }
  221.             $alternatives = [];
  222.             foreach ($container->getServiceIds() as $knownId) {
  223.                 if ('' === $knownId || '.' === $knownId[0]) {
  224.                     continue;
  225.                 }
  226.                 $lev levenshtein($id$knownId);
  227.                 if ($lev <= \strlen($id) / || str_contains($knownId$id)) {
  228.                     $alternatives[] = $knownId;
  229.                 }
  230.             }
  231.             throw new ServiceNotFoundException($idnullnull$alternatives);
  232.         }
  233.         return null;
  234.     }
  235.     /**
  236.      * Returns true if the given service has actually been initialized.
  237.      */
  238.     public function initialized(string $id): bool
  239.     {
  240.         if (isset($this->aliases[$id])) {
  241.             $id $this->aliases[$id];
  242.         }
  243.         if ('service_container' === $id) {
  244.             return false;
  245.         }
  246.         return isset($this->services[$id]);
  247.     }
  248.     /**
  249.      * @return void
  250.      */
  251.     public function reset()
  252.     {
  253.         $services $this->services $this->privates;
  254.         $this->services $this->factories $this->privates = [];
  255.         foreach ($services as $service) {
  256.             try {
  257.                 if ($service instanceof ResetInterface) {
  258.                     $service->reset();
  259.                 }
  260.             } catch (\Throwable) {
  261.                 continue;
  262.             }
  263.         }
  264.     }
  265.     /**
  266.      * Gets all service ids.
  267.      *
  268.      * @return string[]
  269.      */
  270.     public function getServiceIds(): array
  271.     {
  272.         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))));
  273.     }
  274.     /**
  275.      * Gets service ids that existed at compile time.
  276.      */
  277.     public function getRemovedIds(): array
  278.     {
  279.         return [];
  280.     }
  281.     /**
  282.      * Camelizes a string.
  283.      */
  284.     public static function camelize(string $id): string
  285.     {
  286.         return strtr(ucwords(strtr($id, ['_' => ' ''.' => '_ ''\\' => '_ '])), [' ' => '']);
  287.     }
  288.     /**
  289.      * A string to underscore.
  290.      */
  291.     public static function underscore(string $id): string
  292.     {
  293.         return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/''/([a-z\d])([A-Z])/'], ['\\1_\\2''\\1_\\2'], str_replace('_''.'$id)));
  294.     }
  295.     /**
  296.      * Creates a service by requiring its factory file.
  297.      *
  298.      * @return mixed
  299.      */
  300.     protected function load(string $file)
  301.     {
  302.         return require $file;
  303.     }
  304.     /**
  305.      * Fetches a variable from the environment.
  306.      *
  307.      * @throws EnvNotFoundException When the environment variable is not found and has no default value
  308.      */
  309.     protected function getEnv(string $name): mixed
  310.     {
  311.         if (isset($this->resolving[$envName "env($name)"])) {
  312.             throw new ParameterCircularReferenceException(array_keys($this->resolving));
  313.         }
  314.         if (isset($this->envCache[$name]) || \array_key_exists($name$this->envCache)) {
  315.             return $this->envCache[$name];
  316.         }
  317.         if (!$this->has($id 'container.env_var_processors_locator')) {
  318.             $this->set($id, new ServiceLocator([]));
  319.         }
  320.         $this->getEnv ??= $this->getEnv(...);
  321.         $processors $this->get($id);
  322.         if (false !== $i strpos($name':')) {
  323.             $prefix substr($name0$i);
  324.             $localName substr($name$i);
  325.         } else {
  326.             $prefix 'string';
  327.             $localName $name;
  328.         }
  329.         $processor $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);
  330.         if (false === $i) {
  331.             $prefix '';
  332.         }
  333.         $this->resolving[$envName] = true;
  334.         try {
  335.             return $this->envCache[$name] = $processor->getEnv($prefix$localName$this->getEnv);
  336.         } finally {
  337.             unset($this->resolving[$envName]);
  338.         }
  339.     }
  340.     /**
  341.      * @internal
  342.      */
  343.     final protected function getService(string|false $registrystring $id, ?string $methodstring|bool $load): mixed
  344.     {
  345.         if ('service_container' === $id) {
  346.             return $this;
  347.         }
  348.         if (\is_string($load)) {
  349.             throw new RuntimeException($load);
  350.         }
  351.         if (null === $method) {
  352.             return false !== $registry $this->{$registry}[$id] ?? null null;
  353.         }
  354.         if (false !== $registry) {
  355.             return $this->{$registry}[$id] ??= $load $this->load($method) : $this->{$method}($this);
  356.         }
  357.         if (!$load) {
  358.             return $this->{$method}($this);
  359.         }
  360.         return ($factory $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory($this) : $this->load($method);
  361.     }
  362.     private function __clone()
  363.     {
  364.     }
  365. }