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

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