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

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