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

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