Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / vendor / symfony / dependency-injection / ContainerBuilder.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\DependencyInjection;
13
14 use Psr\Container\ContainerInterface as PsrContainerInterface;
15 use Symfony\Component\Config\Resource\ClassExistenceResource;
16 use Symfony\Component\Config\Resource\ComposerResource;
17 use Symfony\Component\Config\Resource\DirectoryResource;
18 use Symfony\Component\Config\Resource\FileExistenceResource;
19 use Symfony\Component\Config\Resource\FileResource;
20 use Symfony\Component\Config\Resource\GlobResource;
21 use Symfony\Component\Config\Resource\ReflectionClassResource;
22 use Symfony\Component\Config\Resource\ResourceInterface;
23 use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
24 use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
25 use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
26 use Symfony\Component\DependencyInjection\Compiler\Compiler;
27 use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
28 use Symfony\Component\DependencyInjection\Compiler\PassConfig;
29 use Symfony\Component\DependencyInjection\Compiler\ResolveEnvPlaceholdersPass;
30 use Symfony\Component\DependencyInjection\Exception\BadMethodCallException;
31 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
32 use Symfony\Component\DependencyInjection\Exception\LogicException;
33 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
34 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
35 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
36 use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
37 use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
38 use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
39 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
40 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
41 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
42 use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
43 use Symfony\Component\ExpressionLanguage\Expression;
44 use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
45
46 /**
47  * ContainerBuilder is a DI container that provides an API to easily describe services.
48  *
49  * @author Fabien Potencier <fabien@symfony.com>
50  */
51 class ContainerBuilder extends Container implements TaggedContainerInterface
52 {
53     /**
54      * @var ExtensionInterface[]
55      */
56     private $extensions = array();
57
58     /**
59      * @var ExtensionInterface[]
60      */
61     private $extensionsByNs = array();
62
63     /**
64      * @var Definition[]
65      */
66     private $definitions = array();
67
68     /**
69      * @var Alias[]
70      */
71     private $aliasDefinitions = array();
72
73     /**
74      * @var ResourceInterface[]
75      */
76     private $resources = array();
77
78     private $extensionConfigs = array();
79
80     /**
81      * @var Compiler
82      */
83     private $compiler;
84
85     private $trackResources;
86
87     /**
88      * @var InstantiatorInterface|null
89      */
90     private $proxyInstantiator;
91
92     /**
93      * @var ExpressionLanguage|null
94      */
95     private $expressionLanguage;
96
97     /**
98      * @var ExpressionFunctionProviderInterface[]
99      */
100     private $expressionLanguageProviders = array();
101
102     /**
103      * @var string[] with tag names used by findTaggedServiceIds
104      */
105     private $usedTags = array();
106
107     /**
108      * @var string[][] a map of env var names to their placeholders
109      */
110     private $envPlaceholders = array();
111
112     /**
113      * @var int[] a map of env vars to their resolution counter
114      */
115     private $envCounters = array();
116
117     /**
118      * @var string[] the list of vendor directories
119      */
120     private $vendors;
121
122     private $autoconfiguredInstanceof = array();
123
124     private $removedIds = array();
125
126     private static $internalTypes = array(
127         'int' => true,
128         'float' => true,
129         'string' => true,
130         'bool' => true,
131         'resource' => true,
132         'object' => true,
133         'array' => true,
134         'null' => true,
135         'callable' => true,
136         'iterable' => true,
137         'mixed' => true,
138     );
139
140     public function __construct(ParameterBagInterface $parameterBag = null)
141     {
142         parent::__construct($parameterBag);
143
144         $this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface');
145         $this->setDefinition('service_container', (new Definition(ContainerInterface::class))->setSynthetic(true)->setPublic(true));
146         $this->setAlias(PsrContainerInterface::class, new Alias('service_container', false));
147         $this->setAlias(ContainerInterface::class, new Alias('service_container', false));
148     }
149
150     /**
151      * @var \ReflectionClass[] a list of class reflectors
152      */
153     private $classReflectors;
154
155     /**
156      * Sets the track resources flag.
157      *
158      * If you are not using the loaders and therefore don't want
159      * to depend on the Config component, set this flag to false.
160      *
161      * @param bool $track True if you want to track resources, false otherwise
162      */
163     public function setResourceTracking($track)
164     {
165         $this->trackResources = (bool) $track;
166     }
167
168     /**
169      * Checks if resources are tracked.
170      *
171      * @return bool true If resources are tracked, false otherwise
172      */
173     public function isTrackingResources()
174     {
175         return $this->trackResources;
176     }
177
178     /**
179      * Sets the instantiator to be used when fetching proxies.
180      */
181     public function setProxyInstantiator(InstantiatorInterface $proxyInstantiator)
182     {
183         $this->proxyInstantiator = $proxyInstantiator;
184     }
185
186     public function registerExtension(ExtensionInterface $extension)
187     {
188         $this->extensions[$extension->getAlias()] = $extension;
189
190         if (false !== $extension->getNamespace()) {
191             $this->extensionsByNs[$extension->getNamespace()] = $extension;
192         }
193     }
194
195     /**
196      * Returns an extension by alias or namespace.
197      *
198      * @param string $name An alias or a namespace
199      *
200      * @return ExtensionInterface An extension instance
201      *
202      * @throws LogicException if the extension is not registered
203      */
204     public function getExtension($name)
205     {
206         if (isset($this->extensions[$name])) {
207             return $this->extensions[$name];
208         }
209
210         if (isset($this->extensionsByNs[$name])) {
211             return $this->extensionsByNs[$name];
212         }
213
214         throw new LogicException(sprintf('Container extension "%s" is not registered', $name));
215     }
216
217     /**
218      * Returns all registered extensions.
219      *
220      * @return ExtensionInterface[] An array of ExtensionInterface
221      */
222     public function getExtensions()
223     {
224         return $this->extensions;
225     }
226
227     /**
228      * Checks if we have an extension.
229      *
230      * @param string $name The name of the extension
231      *
232      * @return bool If the extension exists
233      */
234     public function hasExtension($name)
235     {
236         return isset($this->extensions[$name]) || isset($this->extensionsByNs[$name]);
237     }
238
239     /**
240      * Returns an array of resources loaded to build this configuration.
241      *
242      * @return ResourceInterface[] An array of resources
243      */
244     public function getResources()
245     {
246         return array_values($this->resources);
247     }
248
249     /**
250      * @return $this
251      */
252     public function addResource(ResourceInterface $resource)
253     {
254         if (!$this->trackResources) {
255             return $this;
256         }
257
258         if ($resource instanceof GlobResource && $this->inVendors($resource->getPrefix())) {
259             return $this;
260         }
261
262         $this->resources[(string) $resource] = $resource;
263
264         return $this;
265     }
266
267     /**
268      * Sets the resources for this configuration.
269      *
270      * @param ResourceInterface[] $resources An array of resources
271      *
272      * @return $this
273      */
274     public function setResources(array $resources)
275     {
276         if (!$this->trackResources) {
277             return $this;
278         }
279
280         $this->resources = $resources;
281
282         return $this;
283     }
284
285     /**
286      * Adds the object class hierarchy as resources.
287      *
288      * @param object|string $object An object instance or class name
289      *
290      * @return $this
291      */
292     public function addObjectResource($object)
293     {
294         if ($this->trackResources) {
295             if (\is_object($object)) {
296                 $object = \get_class($object);
297             }
298             if (!isset($this->classReflectors[$object])) {
299                 $this->classReflectors[$object] = new \ReflectionClass($object);
300             }
301             $class = $this->classReflectors[$object];
302
303             foreach ($class->getInterfaceNames() as $name) {
304                 if (null === $interface = &$this->classReflectors[$name]) {
305                     $interface = new \ReflectionClass($name);
306                 }
307                 $file = $interface->getFileName();
308                 if (false !== $file && file_exists($file)) {
309                     $this->fileExists($file);
310                 }
311             }
312             do {
313                 $file = $class->getFileName();
314                 if (false !== $file && file_exists($file)) {
315                     $this->fileExists($file);
316                 }
317                 foreach ($class->getTraitNames() as $name) {
318                     $this->addObjectResource($name);
319                 }
320             } while ($class = $class->getParentClass());
321         }
322
323         return $this;
324     }
325
326     /**
327      * Adds the given class hierarchy as resources.
328      *
329      * @return $this
330      *
331      * @deprecated since version 3.3, to be removed in 4.0. Use addObjectResource() or getReflectionClass() instead.
332      */
333     public function addClassResource(\ReflectionClass $class)
334     {
335         @trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the addObjectResource() or the getReflectionClass() method instead.', E_USER_DEPRECATED);
336
337         return $this->addObjectResource($class->name);
338     }
339
340     /**
341      * Retrieves the requested reflection class and registers it for resource tracking.
342      *
343      * @param string $class
344      * @param bool   $throw
345      *
346      * @return \ReflectionClass|null
347      *
348      * @throws \ReflectionException when a parent class/interface/trait is not found and $throw is true
349      *
350      * @final
351      */
352     public function getReflectionClass($class, $throw = true)
353     {
354         if (!$class = $this->getParameterBag()->resolveValue($class)) {
355             return;
356         }
357
358         if (isset(self::$internalTypes[$class])) {
359             return null;
360         }
361
362         $resource = null;
363
364         try {
365             if (isset($this->classReflectors[$class])) {
366                 $classReflector = $this->classReflectors[$class];
367             } elseif ($this->trackResources) {
368                 $resource = new ClassExistenceResource($class, false);
369                 $classReflector = $resource->isFresh(0) ? false : new \ReflectionClass($class);
370             } else {
371                 $classReflector = new \ReflectionClass($class);
372             }
373         } catch (\ReflectionException $e) {
374             if ($throw) {
375                 throw $e;
376             }
377             $classReflector = false;
378         }
379
380         if ($this->trackResources) {
381             if (!$classReflector) {
382                 $this->addResource($resource ?: new ClassExistenceResource($class, false));
383             } elseif (!$classReflector->isInternal()) {
384                 $path = $classReflector->getFileName();
385
386                 if (!$this->inVendors($path)) {
387                     $this->addResource(new ReflectionClassResource($classReflector, $this->vendors));
388                 }
389             }
390             $this->classReflectors[$class] = $classReflector;
391         }
392
393         return $classReflector ?: null;
394     }
395
396     /**
397      * Checks whether the requested file or directory exists and registers the result for resource tracking.
398      *
399      * @param string      $path          The file or directory path for which to check the existence
400      * @param bool|string $trackContents Whether to track contents of the given resource. If a string is passed,
401      *                                   it will be used as pattern for tracking contents of the requested directory
402      *
403      * @return bool
404      *
405      * @final
406      */
407     public function fileExists($path, $trackContents = true)
408     {
409         $exists = file_exists($path);
410
411         if (!$this->trackResources || $this->inVendors($path)) {
412             return $exists;
413         }
414
415         if (!$exists) {
416             $this->addResource(new FileExistenceResource($path));
417
418             return $exists;
419         }
420
421         if (is_dir($path)) {
422             if ($trackContents) {
423                 $this->addResource(new DirectoryResource($path, \is_string($trackContents) ? $trackContents : null));
424             } else {
425                 $this->addResource(new GlobResource($path, '/*', false));
426             }
427         } elseif ($trackContents) {
428             $this->addResource(new FileResource($path));
429         }
430
431         return $exists;
432     }
433
434     /**
435      * Loads the configuration for an extension.
436      *
437      * @param string $extension The extension alias or namespace
438      * @param array  $values    An array of values that customizes the extension
439      *
440      * @return $this
441      *
442      * @throws BadMethodCallException When this ContainerBuilder is compiled
443      * @throws \LogicException        if the extension is not registered
444      */
445     public function loadFromExtension($extension, array $values = null)
446     {
447         if ($this->isCompiled()) {
448             throw new BadMethodCallException('Cannot load from an extension on a compiled container.');
449         }
450
451         if (\func_num_args() < 2) {
452             $values = array();
453         }
454
455         $namespace = $this->getExtension($extension)->getAlias();
456
457         $this->extensionConfigs[$namespace][] = $values;
458
459         return $this;
460     }
461
462     /**
463      * Adds a compiler pass.
464      *
465      * @param CompilerPassInterface $pass     A compiler pass
466      * @param string                $type     The type of compiler pass
467      * @param int                   $priority Used to sort the passes
468      *
469      * @return $this
470      */
471     public function addCompilerPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, int $priority = 0*/)
472     {
473         if (\func_num_args() >= 3) {
474             $priority = func_get_arg(2);
475         } else {
476             if (__CLASS__ !== \get_class($this)) {
477                 $r = new \ReflectionMethod($this, __FUNCTION__);
478                 if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
479                     @trigger_error(sprintf('Method %s() will have a third `int $priority = 0` argument in version 4.0. Not defining it is deprecated since Symfony 3.2.', __METHOD__), E_USER_DEPRECATED);
480                 }
481             }
482
483             $priority = 0;
484         }
485
486         $this->getCompiler()->addPass($pass, $type, $priority);
487
488         $this->addObjectResource($pass);
489
490         return $this;
491     }
492
493     /**
494      * Returns the compiler pass config which can then be modified.
495      *
496      * @return PassConfig The compiler pass config
497      */
498     public function getCompilerPassConfig()
499     {
500         return $this->getCompiler()->getPassConfig();
501     }
502
503     /**
504      * Returns the compiler.
505      *
506      * @return Compiler The compiler
507      */
508     public function getCompiler()
509     {
510         if (null === $this->compiler) {
511             $this->compiler = new Compiler();
512         }
513
514         return $this->compiler;
515     }
516
517     /**
518      * Sets a service.
519      *
520      * @param string $id      The service identifier
521      * @param object $service The service instance
522      *
523      * @throws BadMethodCallException When this ContainerBuilder is compiled
524      */
525     public function set($id, $service)
526     {
527         $id = $this->normalizeId($id);
528
529         if ($this->isCompiled() && (isset($this->definitions[$id]) && !$this->definitions[$id]->isSynthetic())) {
530             // setting a synthetic service on a compiled container is alright
531             throw new BadMethodCallException(sprintf('Setting service "%s" for an unknown or non-synthetic service definition on a compiled container is not allowed.', $id));
532         }
533
534         unset($this->definitions[$id], $this->aliasDefinitions[$id], $this->removedIds[$id]);
535
536         parent::set($id, $service);
537     }
538
539     /**
540      * Removes a service definition.
541      *
542      * @param string $id The service identifier
543      */
544     public function removeDefinition($id)
545     {
546         if (isset($this->definitions[$id = $this->normalizeId($id)])) {
547             unset($this->definitions[$id]);
548             $this->removedIds[$id] = true;
549         }
550     }
551
552     /**
553      * Returns true if the given service is defined.
554      *
555      * @param string $id The service identifier
556      *
557      * @return bool true if the service is defined, false otherwise
558      */
559     public function has($id)
560     {
561         $id = $this->normalizeId($id);
562
563         return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || parent::has($id);
564     }
565
566     /**
567      * Gets a service.
568      *
569      * @param string $id              The service identifier
570      * @param int    $invalidBehavior The behavior when the service does not exist
571      *
572      * @return object The associated service
573      *
574      * @throws InvalidArgumentException          when no definitions are available
575      * @throws ServiceCircularReferenceException When a circular reference is detected
576      * @throws ServiceNotFoundException          When the service is not defined
577      * @throws \Exception
578      *
579      * @see Reference
580      */
581     public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
582     {
583         if ($this->isCompiled() && isset($this->removedIds[$id = $this->normalizeId($id)])) {
584             @trigger_error(sprintf('Fetching the "%s" private service or alias is deprecated since Symfony 3.4 and will fail in 4.0. Make it public instead.', $id), E_USER_DEPRECATED);
585         }
586
587         return $this->doGet($id, $invalidBehavior);
588     }
589
590     private function doGet($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, array &$inlineServices = null, $isConstructorArgument = false)
591     {
592         $id = $this->normalizeId($id);
593
594         if (isset($inlineServices[$id])) {
595             return $inlineServices[$id];
596         }
597         if (null === $inlineServices) {
598             $isConstructorArgument = true;
599             $inlineServices = array();
600         }
601         try {
602             if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) {
603                 return parent::get($id, $invalidBehavior);
604             }
605             if ($service = parent::get($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)) {
606                 return $service;
607             }
608         } catch (ServiceCircularReferenceException $e) {
609             if ($isConstructorArgument) {
610                 throw $e;
611             }
612         }
613
614         if (!isset($this->definitions[$id]) && isset($this->aliasDefinitions[$id])) {
615             return $this->doGet((string) $this->aliasDefinitions[$id], $invalidBehavior, $inlineServices, $isConstructorArgument);
616         }
617
618         try {
619             $definition = $this->getDefinition($id);
620         } catch (ServiceNotFoundException $e) {
621             if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) {
622                 return;
623             }
624
625             throw $e;
626         }
627
628         if ($isConstructorArgument) {
629             $this->loading[$id] = true;
630         }
631
632         try {
633             return $this->createService($definition, $inlineServices, $isConstructorArgument, $id);
634         } finally {
635             if ($isConstructorArgument) {
636                 unset($this->loading[$id]);
637             }
638         }
639     }
640
641     /**
642      * Merges a ContainerBuilder with the current ContainerBuilder configuration.
643      *
644      * Service definitions overrides the current defined ones.
645      *
646      * But for parameters, they are overridden by the current ones. It allows
647      * the parameters passed to the container constructor to have precedence
648      * over the loaded ones.
649      *
650      *     $container = new ContainerBuilder(new ParameterBag(array('foo' => 'bar')));
651      *     $loader = new LoaderXXX($container);
652      *     $loader->load('resource_name');
653      *     $container->register('foo', 'stdClass');
654      *
655      * In the above example, even if the loaded resource defines a foo
656      * parameter, the value will still be 'bar' as defined in the ContainerBuilder
657      * constructor.
658      *
659      * @throws BadMethodCallException When this ContainerBuilder is compiled
660      */
661     public function merge(self $container)
662     {
663         if ($this->isCompiled()) {
664             throw new BadMethodCallException('Cannot merge on a compiled container.');
665         }
666
667         $this->addDefinitions($container->getDefinitions());
668         $this->addAliases($container->getAliases());
669         $this->getParameterBag()->add($container->getParameterBag()->all());
670
671         if ($this->trackResources) {
672             foreach ($container->getResources() as $resource) {
673                 $this->addResource($resource);
674             }
675         }
676
677         foreach ($this->extensions as $name => $extension) {
678             if (!isset($this->extensionConfigs[$name])) {
679                 $this->extensionConfigs[$name] = array();
680             }
681
682             $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name));
683         }
684
685         if ($this->getParameterBag() instanceof EnvPlaceholderParameterBag && $container->getParameterBag() instanceof EnvPlaceholderParameterBag) {
686             $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders();
687             $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag());
688         } else {
689             $envPlaceholders = array();
690         }
691
692         foreach ($container->envCounters as $env => $count) {
693             if (!$count && !isset($envPlaceholders[$env])) {
694                 continue;
695             }
696             if (!isset($this->envCounters[$env])) {
697                 $this->envCounters[$env] = $count;
698             } else {
699                 $this->envCounters[$env] += $count;
700             }
701         }
702
703         foreach ($container->getAutoconfiguredInstanceof() as $interface => $childDefinition) {
704             if (isset($this->autoconfiguredInstanceof[$interface])) {
705                 throw new InvalidArgumentException(sprintf('"%s" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.', $interface));
706             }
707
708             $this->autoconfiguredInstanceof[$interface] = $childDefinition;
709         }
710     }
711
712     /**
713      * Returns the configuration array for the given extension.
714      *
715      * @param string $name The name of the extension
716      *
717      * @return array An array of configuration
718      */
719     public function getExtensionConfig($name)
720     {
721         if (!isset($this->extensionConfigs[$name])) {
722             $this->extensionConfigs[$name] = array();
723         }
724
725         return $this->extensionConfigs[$name];
726     }
727
728     /**
729      * Prepends a config array to the configs of the given extension.
730      *
731      * @param string $name   The name of the extension
732      * @param array  $config The config to set
733      */
734     public function prependExtensionConfig($name, array $config)
735     {
736         if (!isset($this->extensionConfigs[$name])) {
737             $this->extensionConfigs[$name] = array();
738         }
739
740         array_unshift($this->extensionConfigs[$name], $config);
741     }
742
743     /**
744      * Compiles the container.
745      *
746      * This method passes the container to compiler
747      * passes whose job is to manipulate and optimize
748      * the container.
749      *
750      * The main compiler passes roughly do four things:
751      *
752      *  * The extension configurations are merged;
753      *  * Parameter values are resolved;
754      *  * The parameter bag is frozen;
755      *  * Extension loading is disabled.
756      *
757      * @param bool $resolveEnvPlaceholders Whether %env()% parameters should be resolved using the current
758      *                                     env vars or be replaced by uniquely identifiable placeholders.
759      *                                     Set to "true" when you want to use the current ContainerBuilder
760      *                                     directly, keep to "false" when the container is dumped instead.
761      */
762     public function compile(/*$resolveEnvPlaceholders = false*/)
763     {
764         if (1 <= \func_num_args()) {
765             $resolveEnvPlaceholders = func_get_arg(0);
766         } else {
767             if (__CLASS__ !== static::class) {
768                 $r = new \ReflectionMethod($this, __FUNCTION__);
769                 if (__CLASS__ !== $r->getDeclaringClass()->getName() && (1 > $r->getNumberOfParameters() || 'resolveEnvPlaceholders' !== $r->getParameters()[0]->name)) {
770                     @trigger_error(sprintf('The %s::compile() method expects a first "$resolveEnvPlaceholders" argument since Symfony 3.3. It will be made mandatory in 4.0.', static::class), E_USER_DEPRECATED);
771                 }
772             }
773             $resolveEnvPlaceholders = false;
774         }
775         $compiler = $this->getCompiler();
776
777         if ($this->trackResources) {
778             foreach ($compiler->getPassConfig()->getPasses() as $pass) {
779                 $this->addObjectResource($pass);
780             }
781         }
782         $bag = $this->getParameterBag();
783
784         if ($resolveEnvPlaceholders && $bag instanceof EnvPlaceholderParameterBag) {
785             $compiler->addPass(new ResolveEnvPlaceholdersPass(), PassConfig::TYPE_AFTER_REMOVING, -1000);
786         }
787
788         $compiler->compile($this);
789
790         foreach ($this->definitions as $id => $definition) {
791             if ($this->trackResources && $definition->isLazy()) {
792                 $this->getReflectionClass($definition->getClass());
793             }
794         }
795
796         $this->extensionConfigs = array();
797
798         if ($bag instanceof EnvPlaceholderParameterBag) {
799             if ($resolveEnvPlaceholders) {
800                 $this->parameterBag = new ParameterBag($this->resolveEnvPlaceholders($bag->all(), true));
801             }
802
803             $this->envPlaceholders = $bag->getEnvPlaceholders();
804         }
805
806         parent::compile();
807
808         foreach ($this->definitions + $this->aliasDefinitions as $id => $definition) {
809             if (!$definition->isPublic() || $definition->isPrivate()) {
810                 $this->removedIds[$id] = true;
811             }
812         }
813     }
814
815     /**
816      * Gets all service ids.
817      *
818      * @return array An array of all defined service ids
819      */
820     public function getServiceIds()
821     {
822         return array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds()));
823     }
824
825     /**
826      * Gets removed service or alias ids.
827      *
828      * @return array
829      */
830     public function getRemovedIds()
831     {
832         return $this->removedIds;
833     }
834
835     /**
836      * Adds the service aliases.
837      */
838     public function addAliases(array $aliases)
839     {
840         foreach ($aliases as $alias => $id) {
841             $this->setAlias($alias, $id);
842         }
843     }
844
845     /**
846      * Sets the service aliases.
847      */
848     public function setAliases(array $aliases)
849     {
850         $this->aliasDefinitions = array();
851         $this->addAliases($aliases);
852     }
853
854     /**
855      * Sets an alias for an existing service.
856      *
857      * @param string       $alias The alias to create
858      * @param string|Alias $id    The service to alias
859      *
860      * @return Alias
861      *
862      * @throws InvalidArgumentException if the id is not a string or an Alias
863      * @throws InvalidArgumentException if the alias is for itself
864      */
865     public function setAlias($alias, $id)
866     {
867         $alias = $this->normalizeId($alias);
868
869         if (\is_string($id)) {
870             $id = new Alias($this->normalizeId($id));
871         } elseif (!$id instanceof Alias) {
872             throw new InvalidArgumentException('$id must be a string, or an Alias object.');
873         }
874
875         if ($alias === (string) $id) {
876             throw new InvalidArgumentException(sprintf('An alias can not reference itself, got a circular reference on "%s".', $alias));
877         }
878
879         unset($this->definitions[$alias], $this->removedIds[$alias]);
880
881         return $this->aliasDefinitions[$alias] = $id;
882     }
883
884     /**
885      * Removes an alias.
886      *
887      * @param string $alias The alias to remove
888      */
889     public function removeAlias($alias)
890     {
891         if (isset($this->aliasDefinitions[$alias = $this->normalizeId($alias)])) {
892             unset($this->aliasDefinitions[$alias]);
893             $this->removedIds[$alias] = true;
894         }
895     }
896
897     /**
898      * Returns true if an alias exists under the given identifier.
899      *
900      * @param string $id The service identifier
901      *
902      * @return bool true if the alias exists, false otherwise
903      */
904     public function hasAlias($id)
905     {
906         return isset($this->aliasDefinitions[$this->normalizeId($id)]);
907     }
908
909     /**
910      * Gets all defined aliases.
911      *
912      * @return Alias[] An array of aliases
913      */
914     public function getAliases()
915     {
916         return $this->aliasDefinitions;
917     }
918
919     /**
920      * Gets an alias.
921      *
922      * @param string $id The service identifier
923      *
924      * @return Alias An Alias instance
925      *
926      * @throws InvalidArgumentException if the alias does not exist
927      */
928     public function getAlias($id)
929     {
930         $id = $this->normalizeId($id);
931
932         if (!isset($this->aliasDefinitions[$id])) {
933             throw new InvalidArgumentException(sprintf('The service alias "%s" does not exist.', $id));
934         }
935
936         return $this->aliasDefinitions[$id];
937     }
938
939     /**
940      * Registers a service definition.
941      *
942      * This methods allows for simple registration of service definition
943      * with a fluid interface.
944      *
945      * @param string $id         The service identifier
946      * @param string $class|null The service class
947      *
948      * @return Definition A Definition instance
949      */
950     public function register($id, $class = null)
951     {
952         return $this->setDefinition($id, new Definition($class));
953     }
954
955     /**
956      * Registers an autowired service definition.
957      *
958      * This method implements a shortcut for using setDefinition() with
959      * an autowired definition.
960      *
961      * @param string      $id    The service identifier
962      * @param string|null $class The service class
963      *
964      * @return Definition The created definition
965      */
966     public function autowire($id, $class = null)
967     {
968         return $this->setDefinition($id, (new Definition($class))->setAutowired(true));
969     }
970
971     /**
972      * Adds the service definitions.
973      *
974      * @param Definition[] $definitions An array of service definitions
975      */
976     public function addDefinitions(array $definitions)
977     {
978         foreach ($definitions as $id => $definition) {
979             $this->setDefinition($id, $definition);
980         }
981     }
982
983     /**
984      * Sets the service definitions.
985      *
986      * @param Definition[] $definitions An array of service definitions
987      */
988     public function setDefinitions(array $definitions)
989     {
990         $this->definitions = array();
991         $this->addDefinitions($definitions);
992     }
993
994     /**
995      * Gets all service definitions.
996      *
997      * @return Definition[] An array of Definition instances
998      */
999     public function getDefinitions()
1000     {
1001         return $this->definitions;
1002     }
1003
1004     /**
1005      * Sets a service definition.
1006      *
1007      * @param string     $id         The service identifier
1008      * @param Definition $definition A Definition instance
1009      *
1010      * @return Definition the service definition
1011      *
1012      * @throws BadMethodCallException When this ContainerBuilder is compiled
1013      */
1014     public function setDefinition($id, Definition $definition)
1015     {
1016         if ($this->isCompiled()) {
1017             throw new BadMethodCallException('Adding definition to a compiled container is not allowed');
1018         }
1019
1020         $id = $this->normalizeId($id);
1021
1022         unset($this->aliasDefinitions[$id], $this->removedIds[$id]);
1023
1024         return $this->definitions[$id] = $definition;
1025     }
1026
1027     /**
1028      * Returns true if a service definition exists under the given identifier.
1029      *
1030      * @param string $id The service identifier
1031      *
1032      * @return bool true if the service definition exists, false otherwise
1033      */
1034     public function hasDefinition($id)
1035     {
1036         return isset($this->definitions[$this->normalizeId($id)]);
1037     }
1038
1039     /**
1040      * Gets a service definition.
1041      *
1042      * @param string $id The service identifier
1043      *
1044      * @return Definition A Definition instance
1045      *
1046      * @throws ServiceNotFoundException if the service definition does not exist
1047      */
1048     public function getDefinition($id)
1049     {
1050         $id = $this->normalizeId($id);
1051
1052         if (!isset($this->definitions[$id])) {
1053             throw new ServiceNotFoundException($id);
1054         }
1055
1056         return $this->definitions[$id];
1057     }
1058
1059     /**
1060      * Gets a service definition by id or alias.
1061      *
1062      * The method "unaliases" recursively to return a Definition instance.
1063      *
1064      * @param string $id The service identifier or alias
1065      *
1066      * @return Definition A Definition instance
1067      *
1068      * @throws ServiceNotFoundException if the service definition does not exist
1069      */
1070     public function findDefinition($id)
1071     {
1072         $id = $this->normalizeId($id);
1073
1074         $seen = array();
1075         while (isset($this->aliasDefinitions[$id])) {
1076             $id = (string) $this->aliasDefinitions[$id];
1077
1078             if (isset($seen[$id])) {
1079                 $seen = array_values($seen);
1080                 $seen = \array_slice($seen, array_search($id, $seen));
1081                 $seen[] = $id;
1082
1083                 throw new ServiceCircularReferenceException($id, $seen);
1084             }
1085
1086             $seen[$id] = $id;
1087         }
1088
1089         return $this->getDefinition($id);
1090     }
1091
1092     /**
1093      * Creates a service for a service definition.
1094      *
1095      * @param Definition $definition A service definition instance
1096      * @param string     $id         The service identifier
1097      * @param bool       $tryProxy   Whether to try proxying the service with a lazy proxy
1098      *
1099      * @return object The service described by the service definition
1100      *
1101      * @throws RuntimeException         When the factory definition is incomplete
1102      * @throws RuntimeException         When the service is a synthetic service
1103      * @throws InvalidArgumentException When configure callable is not callable
1104      */
1105     private function createService(Definition $definition, array &$inlineServices, $isConstructorArgument = false, $id = null, $tryProxy = true)
1106     {
1107         if (null === $id && isset($inlineServices[$h = spl_object_hash($definition)])) {
1108             return $inlineServices[$h];
1109         }
1110
1111         if ($definition instanceof ChildDefinition) {
1112             throw new RuntimeException(sprintf('Constructing service "%s" from a parent definition is not supported at build time.', $id));
1113         }
1114
1115         if ($definition->isSynthetic()) {
1116             throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The DIC does not know how to construct this service.', $id));
1117         }
1118
1119         if ($definition->isDeprecated()) {
1120             @trigger_error($definition->getDeprecationMessage($id), E_USER_DEPRECATED);
1121         }
1122
1123         if ($tryProxy && $definition->isLazy() && !$tryProxy = !($proxy = $this->proxyInstantiator) || $proxy instanceof RealServiceInstantiator) {
1124             $proxy = $proxy->instantiateProxy(
1125                 $this,
1126                 $definition,
1127                 $id, function () use ($definition, &$inlineServices, $id) {
1128                     return $this->createService($definition, $inlineServices, true, $id, false);
1129                 }
1130             );
1131             $this->shareService($definition, $proxy, $id, $inlineServices);
1132
1133             return $proxy;
1134         }
1135
1136         $parameterBag = $this->getParameterBag();
1137
1138         if (null !== $definition->getFile()) {
1139             require_once $parameterBag->resolveValue($definition->getFile());
1140         }
1141
1142         $arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices, $isConstructorArgument);
1143
1144         if (null !== $factory = $definition->getFactory()) {
1145             if (\is_array($factory)) {
1146                 $factory = array($this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]);
1147             } elseif (!\is_string($factory)) {
1148                 throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
1149             }
1150         }
1151
1152         if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) {
1153             return $this->services[$id];
1154         }
1155
1156         if (null !== $factory) {
1157             $service = \call_user_func_array($factory, $arguments);
1158
1159             if (!$definition->isDeprecated() && \is_array($factory) && \is_string($factory[0])) {
1160                 $r = new \ReflectionClass($factory[0]);
1161
1162                 if (0 < strpos($r->getDocComment(), "\n * @deprecated ")) {
1163                     @trigger_error(sprintf('The "%s" service relies on the deprecated "%s" factory class. It should either be deprecated or its factory upgraded.', $id, $r->name), E_USER_DEPRECATED);
1164                 }
1165             }
1166         } else {
1167             $r = new \ReflectionClass($class = $parameterBag->resolveValue($definition->getClass()));
1168
1169             $service = null === $r->getConstructor() ? $r->newInstance() : $r->newInstanceArgs($arguments);
1170             // don't trigger deprecations for internal uses
1171             // @deprecated since version 3.3, to be removed in 4.0 along with the deprecated class
1172             $deprecationWhitelist = array('event_dispatcher' => ContainerAwareEventDispatcher::class);
1173
1174             if (!$definition->isDeprecated() && 0 < strpos($r->getDocComment(), "\n * @deprecated ") && (!isset($deprecationWhitelist[$id]) || $deprecationWhitelist[$id] !== $class)) {
1175                 @trigger_error(sprintf('The "%s" service relies on the deprecated "%s" class. It should either be deprecated or its implementation upgraded.', $id, $r->name), E_USER_DEPRECATED);
1176             }
1177         }
1178
1179         if ($tryProxy || !$definition->isLazy()) {
1180             // share only if proxying failed, or if not a proxy
1181             $this->shareService($definition, $service, $id, $inlineServices);
1182         }
1183
1184         $properties = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getProperties())), $inlineServices);
1185         foreach ($properties as $name => $value) {
1186             $service->$name = $value;
1187         }
1188
1189         foreach ($definition->getMethodCalls() as $call) {
1190             $this->callMethod($service, $call, $inlineServices);
1191         }
1192
1193         if ($callable = $definition->getConfigurator()) {
1194             if (\is_array($callable)) {
1195                 $callable[0] = $parameterBag->resolveValue($callable[0]);
1196
1197                 if ($callable[0] instanceof Reference) {
1198                     $callable[0] = $this->doGet((string) $callable[0], $callable[0]->getInvalidBehavior(), $inlineServices);
1199                 } elseif ($callable[0] instanceof Definition) {
1200                     $callable[0] = $this->createService($callable[0], $inlineServices);
1201                 }
1202             }
1203
1204             if (!\is_callable($callable)) {
1205                 throw new InvalidArgumentException(sprintf('The configure callable for class "%s" is not a callable.', \get_class($service)));
1206             }
1207
1208             \call_user_func($callable, $service);
1209         }
1210
1211         return $service;
1212     }
1213
1214     /**
1215      * Replaces service references by the real service instance and evaluates expressions.
1216      *
1217      * @param mixed $value A value
1218      *
1219      * @return mixed The same value with all service references replaced by
1220      *               the real service instances and all expressions evaluated
1221      */
1222     public function resolveServices($value)
1223     {
1224         return $this->doResolveServices($value);
1225     }
1226
1227     private function doResolveServices($value, array &$inlineServices = array(), $isConstructorArgument = false)
1228     {
1229         if (\is_array($value)) {
1230             foreach ($value as $k => $v) {
1231                 $value[$k] = $this->doResolveServices($v, $inlineServices, $isConstructorArgument);
1232             }
1233         } elseif ($value instanceof ServiceClosureArgument) {
1234             $reference = $value->getValues()[0];
1235             $value = function () use ($reference) {
1236                 return $this->resolveServices($reference);
1237             };
1238         } elseif ($value instanceof IteratorArgument) {
1239             $value = new RewindableGenerator(function () use ($value) {
1240                 foreach ($value->getValues() as $k => $v) {
1241                     foreach (self::getServiceConditionals($v) as $s) {
1242                         if (!$this->has($s)) {
1243                             continue 2;
1244                         }
1245                     }
1246                     foreach (self::getInitializedConditionals($v) as $s) {
1247                         if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) {
1248                             continue 2;
1249                         }
1250                     }
1251
1252                     yield $k => $this->resolveServices($v);
1253                 }
1254             }, function () use ($value) {
1255                 $count = 0;
1256                 foreach ($value->getValues() as $v) {
1257                     foreach (self::getServiceConditionals($v) as $s) {
1258                         if (!$this->has($s)) {
1259                             continue 2;
1260                         }
1261                     }
1262                     foreach (self::getInitializedConditionals($v) as $s) {
1263                         if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE)) {
1264                             continue 2;
1265                         }
1266                     }
1267
1268                     ++$count;
1269                 }
1270
1271                 return $count;
1272             });
1273         } elseif ($value instanceof Reference) {
1274             $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices, $isConstructorArgument);
1275         } elseif ($value instanceof Definition) {
1276             $value = $this->createService($value, $inlineServices, $isConstructorArgument);
1277         } elseif ($value instanceof Parameter) {
1278             $value = $this->getParameter((string) $value);
1279         } elseif ($value instanceof Expression) {
1280             $value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this));
1281         }
1282
1283         return $value;
1284     }
1285
1286     /**
1287      * Returns service ids for a given tag.
1288      *
1289      * Example:
1290      *
1291      *     $container->register('foo')->addTag('my.tag', array('hello' => 'world'));
1292      *
1293      *     $serviceIds = $container->findTaggedServiceIds('my.tag');
1294      *     foreach ($serviceIds as $serviceId => $tags) {
1295      *         foreach ($tags as $tag) {
1296      *             echo $tag['hello'];
1297      *         }
1298      *     }
1299      *
1300      * @param string $name
1301      * @param bool   $throwOnAbstract
1302      *
1303      * @return array An array of tags with the tagged service as key, holding a list of attribute arrays
1304      */
1305     public function findTaggedServiceIds($name, $throwOnAbstract = false)
1306     {
1307         $this->usedTags[] = $name;
1308         $tags = array();
1309         foreach ($this->getDefinitions() as $id => $definition) {
1310             if ($definition->hasTag($name)) {
1311                 if ($throwOnAbstract && $definition->isAbstract()) {
1312                     throw new InvalidArgumentException(sprintf('The service "%s" tagged "%s" must not be abstract.', $id, $name));
1313                 }
1314                 $tags[$id] = $definition->getTag($name);
1315             }
1316         }
1317
1318         return $tags;
1319     }
1320
1321     /**
1322      * Returns all tags the defined services use.
1323      *
1324      * @return array An array of tags
1325      */
1326     public function findTags()
1327     {
1328         $tags = array();
1329         foreach ($this->getDefinitions() as $id => $definition) {
1330             $tags = array_merge(array_keys($definition->getTags()), $tags);
1331         }
1332
1333         return array_unique($tags);
1334     }
1335
1336     /**
1337      * Returns all tags not queried by findTaggedServiceIds.
1338      *
1339      * @return string[] An array of tags
1340      */
1341     public function findUnusedTags()
1342     {
1343         return array_values(array_diff($this->findTags(), $this->usedTags));
1344     }
1345
1346     public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
1347     {
1348         $this->expressionLanguageProviders[] = $provider;
1349     }
1350
1351     /**
1352      * @return ExpressionFunctionProviderInterface[]
1353      */
1354     public function getExpressionLanguageProviders()
1355     {
1356         return $this->expressionLanguageProviders;
1357     }
1358
1359     /**
1360      * Returns a ChildDefinition that will be used for autoconfiguring the interface/class.
1361      *
1362      * @param string $interface The class or interface to match
1363      *
1364      * @return ChildDefinition
1365      */
1366     public function registerForAutoconfiguration($interface)
1367     {
1368         if (!isset($this->autoconfiguredInstanceof[$interface])) {
1369             $this->autoconfiguredInstanceof[$interface] = new ChildDefinition('');
1370         }
1371
1372         return $this->autoconfiguredInstanceof[$interface];
1373     }
1374
1375     /**
1376      * Returns an array of ChildDefinition[] keyed by interface.
1377      *
1378      * @return ChildDefinition[]
1379      */
1380     public function getAutoconfiguredInstanceof()
1381     {
1382         return $this->autoconfiguredInstanceof;
1383     }
1384
1385     /**
1386      * Resolves env parameter placeholders in a string or an array.
1387      *
1388      * @param mixed            $value     The value to resolve
1389      * @param string|true|null $format    A sprintf() format returning the replacement for each env var name or
1390      *                                    null to resolve back to the original "%env(VAR)%" format or
1391      *                                    true to resolve to the actual values of the referenced env vars
1392      * @param array            &$usedEnvs Env vars found while resolving are added to this array
1393      *
1394      * @return mixed The value with env parameters resolved if a string or an array is passed
1395      */
1396     public function resolveEnvPlaceholders($value, $format = null, array &$usedEnvs = null)
1397     {
1398         if (null === $format) {
1399             $format = '%%env(%s)%%';
1400         }
1401
1402         $bag = $this->getParameterBag();
1403         if (true === $format) {
1404             $value = $bag->resolveValue($value);
1405         }
1406
1407         if (\is_array($value)) {
1408             $result = array();
1409             foreach ($value as $k => $v) {
1410                 $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs);
1411             }
1412
1413             return $result;
1414         }
1415
1416         if (!\is_string($value) || 38 > \strlen($value)) {
1417             return $value;
1418         }
1419         $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
1420
1421         $completed = false;
1422         foreach ($envPlaceholders as $env => $placeholders) {
1423             foreach ($placeholders as $placeholder) {
1424                 if (false !== stripos($value, $placeholder)) {
1425                     if (true === $format) {
1426                         $resolved = $bag->escapeValue($this->getEnv($env));
1427                     } else {
1428                         $resolved = sprintf($format, $env);
1429                     }
1430                     if ($placeholder === $value) {
1431                         $value = $resolved;
1432                         $completed = true;
1433                     } else {
1434                         if (!\is_string($resolved) && !is_numeric($resolved)) {
1435                             throw new RuntimeException(sprintf('A string value must be composed of strings and/or numbers, but found parameter "env(%s)" of type %s inside string value "%s".', $env, \gettype($resolved), $this->resolveEnvPlaceholders($value)));
1436                         }
1437                         $value = str_ireplace($placeholder, $resolved, $value);
1438                     }
1439                     $usedEnvs[$env] = $env;
1440                     $this->envCounters[$env] = isset($this->envCounters[$env]) ? 1 + $this->envCounters[$env] : 1;
1441
1442                     if ($completed) {
1443                         break 2;
1444                     }
1445                 }
1446             }
1447         }
1448
1449         return $value;
1450     }
1451
1452     /**
1453      * Get statistics about env usage.
1454      *
1455      * @return int[] The number of time each env vars has been resolved
1456      */
1457     public function getEnvCounters()
1458     {
1459         $bag = $this->getParameterBag();
1460         $envPlaceholders = $bag instanceof EnvPlaceholderParameterBag ? $bag->getEnvPlaceholders() : $this->envPlaceholders;
1461
1462         foreach ($envPlaceholders as $env => $placeholders) {
1463             if (!isset($this->envCounters[$env])) {
1464                 $this->envCounters[$env] = 0;
1465             }
1466         }
1467
1468         return $this->envCounters;
1469     }
1470
1471     /**
1472      * @internal
1473      */
1474     public function getNormalizedIds()
1475     {
1476         $normalizedIds = array();
1477
1478         foreach ($this->normalizedIds as $k => $v) {
1479             if ($v !== (string) $k) {
1480                 $normalizedIds[$k] = $v;
1481             }
1482         }
1483
1484         return $normalizedIds;
1485     }
1486
1487     /**
1488      * @final
1489      */
1490     public function log(CompilerPassInterface $pass, $message)
1491     {
1492         $this->getCompiler()->log($pass, $this->resolveEnvPlaceholders($message));
1493     }
1494
1495     /**
1496      * {@inheritdoc}
1497      */
1498     public function normalizeId($id)
1499     {
1500         if (!\is_string($id)) {
1501             $id = (string) $id;
1502         }
1503
1504         return isset($this->definitions[$id]) || isset($this->aliasDefinitions[$id]) || isset($this->removedIds[$id]) ? $id : parent::normalizeId($id);
1505     }
1506
1507     /**
1508      * Returns the Service Conditionals.
1509      *
1510      * @param mixed $value An array of conditionals to return
1511      *
1512      * @return array An array of Service conditionals
1513      *
1514      * @internal since version 3.4
1515      */
1516     public static function getServiceConditionals($value)
1517     {
1518         $services = array();
1519
1520         if (\is_array($value)) {
1521             foreach ($value as $v) {
1522                 $services = array_unique(array_merge($services, self::getServiceConditionals($v)));
1523             }
1524         } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $value->getInvalidBehavior()) {
1525             $services[] = (string) $value;
1526         }
1527
1528         return $services;
1529     }
1530
1531     /**
1532      * Returns the initialized conditionals.
1533      *
1534      * @param mixed $value An array of conditionals to return
1535      *
1536      * @return array An array of uninitialized conditionals
1537      *
1538      * @internal
1539      */
1540     public static function getInitializedConditionals($value)
1541     {
1542         $services = array();
1543
1544         if (\is_array($value)) {
1545             foreach ($value as $v) {
1546                 $services = array_unique(array_merge($services, self::getInitializedConditionals($v)));
1547             }
1548         } elseif ($value instanceof Reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $value->getInvalidBehavior()) {
1549             $services[] = (string) $value;
1550         }
1551
1552         return $services;
1553     }
1554
1555     /**
1556      * Computes a reasonably unique hash of a value.
1557      *
1558      * @param mixed $value A serializable value
1559      *
1560      * @return string
1561      */
1562     public static function hash($value)
1563     {
1564         $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7);
1565
1566         return str_replace(array('/', '+'), array('.', '_'), strtolower($hash));
1567     }
1568
1569     /**
1570      * {@inheritdoc}
1571      */
1572     protected function getEnv($name)
1573     {
1574         $value = parent::getEnv($name);
1575         $bag = $this->getParameterBag();
1576
1577         if (!\is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) {
1578             return $value;
1579         }
1580
1581         foreach ($bag->getEnvPlaceholders() as $env => $placeholders) {
1582             if (isset($placeholders[$value])) {
1583                 $bag = new ParameterBag($bag->all());
1584
1585                 return $bag->unescapeValue($bag->get("env($name)"));
1586             }
1587         }
1588
1589         $this->resolving["env($name)"] = true;
1590         try {
1591             return $bag->unescapeValue($this->resolveEnvPlaceholders($bag->escapeValue($value), true));
1592         } finally {
1593             unset($this->resolving["env($name)"]);
1594         }
1595     }
1596
1597     private function callMethod($service, $call, array &$inlineServices)
1598     {
1599         foreach (self::getServiceConditionals($call[1]) as $s) {
1600             if (!$this->has($s)) {
1601                 return;
1602             }
1603         }
1604         foreach (self::getInitializedConditionals($call[1]) as $s) {
1605             if (!$this->doGet($s, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE, $inlineServices)) {
1606                 return;
1607             }
1608         }
1609
1610         \call_user_func_array(array($service, $call[0]), $this->doResolveServices($this->getParameterBag()->unescapeValue($this->getParameterBag()->resolveValue($call[1])), $inlineServices));
1611     }
1612
1613     /**
1614      * Shares a given service in the container.
1615      *
1616      * @param Definition  $definition
1617      * @param object      $service
1618      * @param string|null $id
1619      */
1620     private function shareService(Definition $definition, $service, $id, array &$inlineServices)
1621     {
1622         $inlineServices[null !== $id ? $id : spl_object_hash($definition)] = $service;
1623
1624         if (null !== $id && $definition->isShared()) {
1625             $this->services[$id] = $service;
1626             unset($this->loading[$id]);
1627         }
1628     }
1629
1630     private function getExpressionLanguage()
1631     {
1632         if (null === $this->expressionLanguage) {
1633             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
1634                 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
1635             }
1636             $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
1637         }
1638
1639         return $this->expressionLanguage;
1640     }
1641
1642     private function inVendors($path)
1643     {
1644         if (null === $this->vendors) {
1645             $resource = new ComposerResource();
1646             $this->vendors = $resource->getVendors();
1647             $this->addResource($resource);
1648         }
1649         $path = realpath($path) ?: $path;
1650
1651         foreach ($this->vendors as $vendor) {
1652             if (0 === strpos($path, $vendor) && false !== strpbrk(substr($path, \strlen($vendor), 1), '/'.\DIRECTORY_SEPARATOR)) {
1653                 return true;
1654             }
1655         }
1656
1657         return false;
1658     }
1659 }