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

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