4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\Dumper;
14 use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
15 use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
16 use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
17 use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
18 use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass;
19 use Symfony\Component\DependencyInjection\Container;
20 use Symfony\Component\DependencyInjection\ContainerBuilder;
21 use Symfony\Component\DependencyInjection\ContainerInterface;
22 use Symfony\Component\DependencyInjection\Definition;
23 use Symfony\Component\DependencyInjection\Exception\EnvParameterException;
24 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
25 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
26 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
27 use Symfony\Component\DependencyInjection\ExpressionLanguage;
28 use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;
29 use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;
30 use Symfony\Component\DependencyInjection\Parameter;
31 use Symfony\Component\DependencyInjection\Reference;
32 use Symfony\Component\DependencyInjection\TypedReference;
33 use Symfony\Component\DependencyInjection\Variable;
34 use Symfony\Component\ExpressionLanguage\Expression;
35 use Symfony\Component\HttpKernel\Kernel;
38 * PhpDumper dumps a service container as a PHP class.
40 * @author Fabien Potencier <fabien@symfony.com>
41 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
43 class PhpDumper extends Dumper
46 * Characters that might appear in the generated variable name as first character.
48 const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz';
51 * Characters that might appear in the generated variable name as any but the first character.
53 const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_';
55 private $definitionVariables;
56 private $referenceVariables;
57 private $variableCount;
58 private $inlinedDefinitions;
59 private $serviceCalls;
60 private $reservedVariables = array('instance', 'class', 'this');
61 private $expressionLanguage;
62 private $targetDirRegex;
63 private $targetDirMaxMatches;
65 private $serviceIdToMethodNameMap;
66 private $usedMethodNames;
70 private $inlineRequires;
71 private $inlinedRequires = array();
72 private $circularReferences = array();
82 public function __construct(ContainerBuilder $container)
84 if (!$container->isCompiled()) {
85 @trigger_error('Dumping an uncompiled ContainerBuilder is deprecated since Symfony 3.3 and will not be supported anymore in 4.0. Compile the container beforehand.', E_USER_DEPRECATED);
88 parent::__construct($container);
92 * Sets the dumper to be used when dumping proxies in the generated container.
94 public function setProxyDumper(ProxyDumper $proxyDumper)
96 $this->proxyDumper = $proxyDumper;
100 * Dumps the service container as a PHP class.
104 * * class: The class name
105 * * base_class: The base class name
106 * * namespace: The class namespace
107 * * as_files: To split the container in several files
109 * @return string|array A PHP class representing the service container or an array of PHP files if the "as_files" option is set
111 * @throws EnvParameterException When an env var exists but has not been dumped
113 public function dump(array $options = array())
115 $this->targetDirRegex = null;
116 $this->inlinedRequires = array();
117 $options = array_merge(array(
118 'class' => 'ProjectServiceContainer',
119 'base_class' => 'Container',
123 'hot_path_tag' => 'container.hot_path',
124 'inline_class_loader_parameter' => 'container.dumper.inline_class_loader',
125 'build_time' => time(),
128 $this->namespace = $options['namespace'];
129 $this->asFiles = $options['as_files'];
130 $this->hotPathTag = $options['hot_path_tag'];
131 $this->inlineRequires = $options['inline_class_loader_parameter'] && $this->container->hasParameter($options['inline_class_loader_parameter']) && $this->container->getParameter($options['inline_class_loader_parameter']);
133 if (0 !== strpos($baseClass = $options['base_class'], '\\') && 'Container' !== $baseClass) {
134 $baseClass = sprintf('%s\%s', $options['namespace'] ? '\\'.$options['namespace'] : '', $baseClass);
135 $baseClassWithNamespace = $baseClass;
136 } elseif ('Container' === $baseClass) {
137 $baseClassWithNamespace = Container::class;
139 $baseClassWithNamespace = $baseClass;
142 $this->initializeMethodNamesMap('Container' === $baseClass ? Container::class : $baseClass);
144 if ($this->getProxyDumper() instanceof NullDumper) {
145 (new AnalyzeServiceReferencesPass(true, false))->process($this->container);
147 (new CheckCircularReferencesPass())->process($this->container);
148 } catch (ServiceCircularReferenceException $e) {
149 $path = $e->getPath();
151 $path[key($path)] .= '". Try running "composer require symfony/proxy-manager-bridge';
153 throw new ServiceCircularReferenceException($e->getServiceId(), $path);
157 (new AnalyzeServiceReferencesPass(false))->process($this->container);
158 $this->circularReferences = array();
159 $checkedNodes = array();
160 foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) {
161 $currentPath = array($id => $id);
162 $this->analyzeCircularReferences($node->getOutEdges(), $checkedNodes, $currentPath);
164 $this->container->getCompiler()->getServiceReferenceGraph()->clear();
166 $this->docStar = $options['debug'] ? '*' : '';
168 if (!empty($options['file']) && is_dir($dir = \dirname($options['file']))) {
169 // Build a regexp where the first root dirs are mandatory,
170 // but every other sub-dir is optional up to the full path in $dir
171 // Mandate at least 2 root dirs and not more that 5 optional dirs.
173 $dir = explode(\DIRECTORY_SEPARATOR, realpath($dir));
178 $lastOptionalDir = $i > 8 ? $i - 5 : 3;
179 $this->targetDirMaxMatches = $i - $lastOptionalDir;
181 while (--$i >= $lastOptionalDir) {
182 $regex = sprintf('(%s%s)?', preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex);
186 $regex = preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#').$regex;
189 $this->targetDirRegex = '#'.preg_quote($dir[0], '#').$regex.'#';
194 $this->startClass($options['class'], $baseClass, $baseClassWithNamespace).
195 $this->addServices().
196 $this->addDefaultParametersMethod().
200 if ($this->asFiles) {
204 use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
206 // This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
211 if ($ids = array_keys($this->container->getRemovedIds())) {
213 $c = "<?php\n\nreturn array(\n";
214 foreach ($ids as $id) {
215 $c .= ' '.$this->doExport($id)." => true,\n";
217 $files['removed-ids.php'] = $c .= ");\n";
220 foreach ($this->generateServiceFiles() as $file => $c) {
221 $files[$file] = $fileStart.$c;
223 foreach ($this->generateProxyClasses() as $file => $c) {
224 $files[$file] = "<?php\n".$c;
226 $files[$options['class'].'.php'] = $code;
227 $hash = ucfirst(strtr(ContainerBuilder::hash($files), '._', 'xx'));
230 foreach ($files as $file => $c) {
231 $code["Container{$hash}/{$file}"] = $c;
234 $code["Container{$hash}/{$options['class']}.php"] = substr_replace($files[$options['class'].'.php'], "<?php\n\nnamespace Container{$hash};\n", 0, 6);
235 $namespaceLine = $this->namespace ? "\nnamespace {$this->namespace};\n" : '';
236 $time = $options['build_time'];
237 $id = hash('crc32', $hash.$time);
239 $code[$options['class'].'.php'] = <<<EOF
242 // This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
244 if (\\class_exists(\\Container{$hash}\\{$options['class']}::class, false)) {
246 } elseif (!include __DIR__.'/Container{$hash}/{$options['class']}.php') {
247 touch(__DIR__.'/Container{$hash}.legacy');
252 if (!\\class_exists({$options['class']}::class, false)) {
253 \\class_alias(\\Container{$hash}\\{$options['class']}::class, {$options['class']}::class, false);
256 return new \\Container{$hash}\\{$options['class']}(array(
257 'container.build_hash' => '$hash',
258 'container.build_id' => '$id',
259 'container.build_time' => $time,
260 ), __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}');
264 foreach ($this->generateProxyClasses() as $c) {
269 $this->targetDirRegex = null;
270 $this->inlinedRequires = array();
271 $this->circularReferences = array();
273 $unusedEnvs = array();
274 foreach ($this->container->getEnvCounters() as $env => $use) {
276 $unusedEnvs[] = $env;
280 throw new EnvParameterException($unusedEnvs, null, 'Environment variables "%s" are never used. Please, check your container\'s configuration.');
287 * Retrieves the currently set proxy dumper or instantiates one.
289 * @return ProxyDumper
291 private function getProxyDumper()
293 if (!$this->proxyDumper) {
294 $this->proxyDumper = new NullDumper();
297 return $this->proxyDumper;
300 private function analyzeCircularReferences(array $edges, &$checkedNodes, &$currentPath)
302 foreach ($edges as $edge) {
303 $node = $edge->getDestNode();
304 $id = $node->getId();
306 if ($node->getValue() && ($edge->isLazy() || $edge->isWeak())) {
308 } elseif (isset($currentPath[$id])) {
309 foreach (array_reverse($currentPath) as $parentId) {
310 $this->circularReferences[$parentId][$id] = $id;
313 } elseif (!isset($checkedNodes[$id])) {
314 $checkedNodes[$id] = true;
315 $currentPath[$id] = $id;
316 $this->analyzeCircularReferences($node->getOutEdges(), $checkedNodes, $currentPath);
317 unset($currentPath[$id]);
322 private function collectLineage($class, array &$lineage)
324 if (isset($lineage[$class])) {
327 if (!$r = $this->container->getReflectionClass($class, false)) {
330 if ($this->container instanceof $class) {
333 $file = $r->getFileName();
334 if (!$file || $this->doExport($file) === $exportedFile = $this->export($file)) {
338 if ($parent = $r->getParentClass()) {
339 $this->collectLineage($parent->name, $lineage);
342 foreach ($r->getInterfaces() as $parent) {
343 $this->collectLineage($parent->name, $lineage);
346 foreach ($r->getTraits() as $parent) {
347 $this->collectLineage($parent->name, $lineage);
350 $lineage[$class] = substr($exportedFile, 1, -1);
353 private function generateProxyClasses()
355 $alreadyGenerated = array();
356 $definitions = $this->container->getDefinitions();
357 $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments');
358 $proxyDumper = $this->getProxyDumper();
360 foreach ($definitions as $definition) {
361 if (!$proxyDumper->isProxyCandidate($definition)) {
364 if (isset($alreadyGenerated[$class = $definition->getClass()])) {
367 $alreadyGenerated[$class] = true;
368 // register class' reflector for resource tracking
369 $this->container->getReflectionClass($class);
370 if ("\n" === $proxyCode = "\n".$proxyDumper->getProxyCode($definition)) {
374 $proxyCode = "<?php\n".$proxyCode;
375 $proxyCode = substr(Kernel::stripComments($proxyCode), 5);
377 yield sprintf('%s.php', explode(' ', $proxyCode, 3)[1]) => $proxyCode;
382 * Generates the require_once statement for service includes.
386 private function addServiceInclude($cId, Definition $definition)
390 if ($this->inlineRequires && !$this->isHotPath($definition)) {
392 foreach ($this->inlinedDefinitions as $def) {
393 if (!$def->isDeprecated() && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) {
394 $this->collectLineage($class, $lineage);
398 foreach ($this->serviceCalls as $id => list($callCount, $behavior)) {
399 if ('service_container' !== $id && $id !== $cId
400 && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior
401 && $this->container->has($id)
402 && $this->isTrivialInstance($def = $this->container->findDefinition($id))
403 && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())
405 $this->collectLineage($class, $lineage);
409 foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) {
410 $code .= sprintf(" include_once %s;\n", $file);
414 foreach ($this->inlinedDefinitions as $def) {
415 if ($file = $def->getFile()) {
416 $code .= sprintf(" include_once %s;\n", $this->dumpValue($file));
428 * Generates the service instance.
431 * @param Definition $definition
432 * @param bool $isSimpleInstance
436 * @throws InvalidArgumentException
437 * @throws RuntimeException
439 private function addServiceInstance($id, Definition $definition, $isSimpleInstance)
441 $class = $this->dumpValue($definition->getClass());
443 if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
444 throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
447 $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
450 if (!$isProxyCandidate && $definition->isShared()) {
451 $instantiation = "\$this->services['$id'] = ".($isSimpleInstance ? '' : '$instance');
452 } elseif (!$isSimpleInstance) {
453 $instantiation = '$instance';
457 if ($isSimpleInstance) {
460 $instantiation .= ' = ';
463 return $this->addNewInstance($definition, $return, $instantiation, $id);
467 * Checks if the definition is a trivial instance.
469 * @param Definition $definition
473 private function isTrivialInstance(Definition $definition)
475 if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) {
478 if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < \count($definition->getArguments())) {
482 foreach ($definition->getArguments() as $arg) {
483 if (!$arg || $arg instanceof Parameter) {
486 if (\is_array($arg) && 3 >= \count($arg)) {
487 foreach ($arg as $k => $v) {
488 if ($this->dumpValue($k) !== $this->dumpValue($k, false)) {
491 if (!$v || $v instanceof Parameter) {
494 if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) {
497 if (!is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($v, false)) {
501 } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) {
503 } elseif (!is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($arg, false)) {
512 * Adds method calls to a service definition.
514 * @param Definition $definition
515 * @param string $variableName
519 private function addServiceMethodCalls(Definition $definition, $variableName = 'instance')
522 foreach ($definition->getMethodCalls() as $call) {
523 $arguments = array();
524 foreach ($call[1] as $value) {
525 $arguments[] = $this->dumpValue($value);
528 $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments)));
534 private function addServiceProperties(Definition $definition, $variableName = 'instance')
537 foreach ($definition->getProperties() as $name => $value) {
538 $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value));
545 * Adds configurator definition.
547 * @param Definition $definition
548 * @param string $variableName
552 private function addServiceConfigurator(Definition $definition, $variableName = 'instance')
554 if (!$callable = $definition->getConfigurator()) {
558 if (\is_array($callable)) {
559 if ($callable[0] instanceof Reference
560 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
561 return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
564 $class = $this->dumpValue($callable[0]);
565 // If the class is a string we can optimize call_user_func away
566 if (0 === strpos($class, "'") && false === strpos($class, '$')) {
567 return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName);
570 if (0 === strpos($class, 'new ')) {
571 return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
574 return sprintf(" \\call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
577 return sprintf(" %s(\$%s);\n", $callable, $variableName);
584 * @param Definition $definition
585 * @param string &$file
589 private function addService($id, Definition $definition, &$file = null)
591 $this->definitionVariables = new \SplObjectStorage();
592 $this->referenceVariables = array();
593 $this->variableCount = 0;
594 $this->definitionVariables[$definition] = $this->referenceVariables[$id] = new Variable('instance');
598 if ($class = $definition->getClass()) {
599 $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class);
600 $return[] = sprintf(0 === strpos($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\'));
601 } elseif ($definition->getFactory()) {
602 $factory = $definition->getFactory();
603 if (\is_string($factory)) {
604 $return[] = sprintf('@return object An instance returned by %s()', $factory);
605 } elseif (\is_array($factory) && (\is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
606 $class = $factory[0] instanceof Definition ? $factory[0]->getClass() : (string) $factory[0];
607 $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class);
608 $return[] = sprintf('@return object An instance returned by %s::%s()', $class, $factory[1]);
612 if ($definition->isDeprecated()) {
613 if ($return && 0 === strpos($return[\count($return) - 1], '@return')) {
617 $return[] = sprintf('@deprecated %s', $definition->getDeprecationMessage($id));
620 $return = str_replace("\n * \n", "\n *\n", implode("\n * ", $return));
621 $return = $this->container->resolveEnvPlaceholders($return);
623 $shared = $definition->isShared() ? ' shared' : '';
624 $public = $definition->isPublic() ? 'public' : 'private';
625 $autowired = $definition->isAutowired() ? ' autowired' : '';
627 if ($definition->isLazy()) {
628 $lazyInitialization = '$lazyLoad = true';
630 $lazyInitialization = '';
633 $asFile = $this->asFiles && $definition->isShared() && !$this->isHotPath($definition);
634 $methodName = $this->generateMethodName($id);
636 $file = $methodName.'.php';
637 $code = " // Returns the $public '$id'$shared$autowired service.\n\n";
642 * Gets the $public '$id'$shared$autowired service.
646 protected function {$methodName}($lazyInitialization)
652 $this->serviceCalls = array();
653 $this->inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition), null, $this->serviceCalls);
655 $code .= $this->addServiceInclude($id, $definition);
657 if ($this->getProxyDumper()->isProxyCandidate($definition)) {
658 $factoryCode = $asFile ? "\$this->load('%s.php', false)" : '$this->%s(false)';
659 $code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName));
662 if ($definition->isDeprecated()) {
663 $code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id)));
667 $arguments = array($definition->getArguments(), $definition->getFactory());
668 $this->addInlineVariables($head, $tail, $id, $arguments, true);
669 $code .= '' !== $head ? $head."\n" : '';
671 if ($arguments = array_filter(array($definition->getProperties(), $definition->getMethodCalls(), $definition->getConfigurator()))) {
672 $this->addInlineVariables($tail, $tail, $id, $arguments, false);
674 $tail .= '' !== $tail ? "\n" : '';
675 $tail .= $this->addServiceProperties($definition);
676 $tail .= $this->addServiceMethodCalls($definition);
677 $tail .= $this->addServiceConfigurator($definition);
680 $code .= $this->addServiceInstance($id, $definition, '' === $tail)
681 .('' !== $tail ? "\n".$tail."\n return \$instance;\n" : '');
684 $code = implode("\n", array_map(function ($line) { return $line ? substr($line, 8) : $line; }, explode("\n", $code)));
689 $this->definitionVariables = $this->inlinedDefinitions = null;
690 $this->referenceVariables = $this->serviceCalls = null;
695 private function addInlineVariables(&$head, &$tail, $id, array $arguments, $forConstructor)
699 foreach ($arguments as $argument) {
700 if (\is_array($argument)) {
701 $hasSelfRef = $this->addInlineVariables($head, $tail, $id, $argument, $forConstructor) || $hasSelfRef;
702 } elseif ($argument instanceof Reference) {
703 $hasSelfRef = $this->addInlineReference($head, $id, $this->container->normalizeId($argument), $forConstructor) || $hasSelfRef;
704 } elseif ($argument instanceof Definition) {
705 $hasSelfRef = $this->addInlineService($head, $tail, $id, $argument, $forConstructor) || $hasSelfRef;
712 private function addInlineReference(&$code, $id, $targetId, $forConstructor)
714 $hasSelfRef = isset($this->circularReferences[$id][$targetId]);
716 if ('service_container' === $targetId || isset($this->referenceVariables[$targetId])) {
720 list($callCount, $behavior) = $this->serviceCalls[$targetId];
722 if (2 > $callCount && (!$hasSelfRef || !$forConstructor)) {
726 $name = $this->getNextVariableName();
727 $this->referenceVariables[$targetId] = new Variable($name);
729 $reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $behavior ? new Reference($targetId, $behavior) : null;
730 $code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($targetId, $reference));
732 if (!$hasSelfRef || !$forConstructor) {
736 $code .= sprintf(<<<'EOTXT'
738 if (isset($this->%s['%s'])) {
739 return $this->%1$s['%2$s'];
751 private function addInlineService(&$head, &$tail, $id, Definition $definition, $forConstructor)
753 if (isset($this->definitionVariables[$definition])) {
757 $arguments = array($definition->getArguments(), $definition->getFactory());
759 if (2 > $this->inlinedDefinitions[$definition] && !$definition->getMethodCalls() && !$definition->getProperties() && !$definition->getConfigurator()) {
760 return $this->addInlineVariables($head, $tail, $id, $arguments, $forConstructor);
763 $name = $this->getNextVariableName();
764 $this->definitionVariables[$definition] = new Variable($name);
767 if ($forConstructor) {
768 $hasSelfRef = $this->addInlineVariables($code, $tail, $id, $arguments, $forConstructor);
770 $hasSelfRef = $this->addInlineVariables($code, $code, $id, $arguments, $forConstructor);
772 $code .= $this->addNewInstance($definition, '$'.$name, ' = ', $id);
773 $hasSelfRef && !$forConstructor ? $tail .= ('' !== $tail ? "\n" : '').$code : $head .= ('' !== $head ? "\n" : '').$code;
776 $arguments = array($definition->getProperties(), $definition->getMethodCalls(), $definition->getConfigurator());
777 $hasSelfRef = $this->addInlineVariables($code, $code, $id, $arguments, false) || $hasSelfRef;
779 $code .= '' !== $code ? "\n" : '';
780 $code .= $this->addServiceProperties($definition, $name);
781 $code .= $this->addServiceMethodCalls($definition, $name);
782 $code .= $this->addServiceConfigurator($definition, $name);
784 $hasSelfRef ? $tail .= ('' !== $tail ? "\n" : '').$code : $head .= $code;
791 * Adds multiple services.
795 private function addServices()
797 $publicServices = $privateServices = '';
798 $definitions = $this->container->getDefinitions();
800 foreach ($definitions as $id => $definition) {
801 if ($definition->isSynthetic() || ($this->asFiles && $definition->isShared() && !$this->isHotPath($definition))) {
804 if ($definition->isPublic()) {
805 $publicServices .= $this->addService($id, $definition);
807 $privateServices .= $this->addService($id, $definition);
811 return $publicServices.$privateServices;
814 private function generateServiceFiles()
816 $definitions = $this->container->getDefinitions();
818 foreach ($definitions as $id => $definition) {
819 if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) {
820 $code = $this->addService($id, $definition, $file);
821 yield $file => $code;
826 private function addNewInstance(Definition $definition, $return, $instantiation, $id)
828 $class = $this->dumpValue($definition->getClass());
829 $return = ' '.$return.$instantiation;
831 $arguments = array();
832 foreach ($definition->getArguments() as $value) {
833 $arguments[] = $this->dumpValue($value);
836 if (null !== $definition->getFactory()) {
837 $callable = $definition->getFactory();
838 if (\is_array($callable)) {
839 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) {
840 throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $callable[1] ?: 'n/a'));
843 if ($callable[0] instanceof Reference
844 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
845 return $return.sprintf("%s->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '');
848 $class = $this->dumpValue($callable[0]);
849 // If the class is a string we can optimize call_user_func away
850 if (0 === strpos($class, "'") && false === strpos($class, '$')) {
851 if ("''" === $class) {
852 throw new RuntimeException(sprintf('Cannot dump definition: The "%s" service is defined to be created by a factory but is missing the service reference, did you forget to define the factory service id or class?', $id));
855 return $return.sprintf("%s::%s(%s);\n", $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '');
858 if (0 === strpos($class, 'new ')) {
859 return $return.sprintf("(%s)->%s(%s);\n", $class, $callable[1], $arguments ? implode(', ', $arguments) : '');
862 return $return.sprintf("\\call_user_func(array(%s, '%s')%s);\n", $class, $callable[1], $arguments ? ', '.implode(', ', $arguments) : '');
865 return $return.sprintf("%s(%s);\n", $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : '');
868 if (false !== strpos($class, '$')) {
869 return sprintf(" \$class = %s;\n\n%snew \$class(%s);\n", $class, $return, implode(', ', $arguments));
872 return $return.sprintf("new %s(%s);\n", $this->dumpLiteralClass($class), implode(', ', $arguments));
876 * Adds the class headers.
878 * @param string $class Class name
879 * @param string $baseClass The name of the base class
880 * @param string $baseClassWithNamespace Fully qualified base class name
884 private function startClass($class, $baseClass, $baseClassWithNamespace)
886 $bagClass = $this->container->isCompiled() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;';
887 $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';
892 use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
893 use Symfony\Component\DependencyInjection\ContainerInterface;
894 use Symfony\Component\DependencyInjection\Container;
895 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
896 use Symfony\Component\DependencyInjection\Exception\LogicException;
897 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
901 * This class has been auto-generated
902 * by the Symfony Dependency Injection Component.
904 * @final since Symfony 3.3
906 class $class extends $baseClass
908 private \$parameters;
909 private \$targetDirs = array();
911 public function __construct()
915 if (null !== $this->targetDirRegex) {
916 $dir = $this->asFiles ? '$this->targetDirs[0] = \\dirname($containerDir)' : '__DIR__';
919 for (\$i = 1; \$i <= {$this->targetDirMaxMatches}; ++\$i) {
920 \$this->targetDirs[\$i] = \$dir = \\dirname(\$dir);
925 if ($this->asFiles) {
926 $code = str_replace('$parameters', "\$buildParameters;\n private \$containerDir;\n private \$parameters", $code);
927 $code = str_replace('__construct()', '__construct(array $buildParameters = array(), $containerDir = __DIR__)', $code);
928 $code .= " \$this->buildParameters = \$buildParameters;\n";
929 $code .= " \$this->containerDir = \$containerDir;\n";
932 if ($this->container->isCompiled()) {
933 if (Container::class !== $baseClassWithNamespace) {
934 $r = $this->container->getReflectionClass($baseClassWithNamespace, false);
936 && (null !== $constructor = $r->getConstructor())
937 && 0 === $constructor->getNumberOfRequiredParameters()
938 && Container::class !== $constructor->getDeclaringClass()->name
940 $code .= " parent::__construct();\n";
941 $code .= " \$this->parameterBag = null;\n\n";
945 if ($this->container->getParameterBag()->all()) {
946 $code .= " \$this->parameters = \$this->getDefaultParameters();\n\n";
949 $code .= " \$this->services = array();\n";
951 $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null;
952 $code .= " parent::__construct($arguments);\n";
955 $code .= $this->addNormalizedIds();
956 $code .= $this->addSyntheticIds();
957 $code .= $this->addMethodMap();
958 $code .= $this->asFiles ? $this->addFileMap() : '';
959 $code .= $this->addPrivateServices();
960 $code .= $this->addAliases();
961 $code .= $this->addInlineRequires();
966 $code .= $this->addRemovedIds();
968 if ($this->container->isCompiled()) {
971 public function compile()
973 throw new LogicException('You cannot compile a dumped container that was already compiled.');
976 public function isCompiled()
981 public function isFrozen()
983 @trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the isCompiled() method instead.', __METHOD__), E_USER_DEPRECATED);
991 if ($this->asFiles) {
994 protected function load(\$file, \$lazyLoad = true)
996 return require \$this->containerDir.\\DIRECTORY_SEPARATOR.\$file;
1002 $proxyDumper = $this->getProxyDumper();
1003 foreach ($this->container->getDefinitions() as $definition) {
1004 if (!$proxyDumper->isProxyCandidate($definition)) {
1007 if ($this->asFiles) {
1008 $proxyLoader = '$this->load("{$class}.php")';
1009 } elseif ($this->namespace) {
1010 $proxyLoader = 'class_alias("'.$this->namespace.'\\\\{$class}", $class, false)';
1015 $proxyLoader = "class_exists(\$class, false) || {$proxyLoader};\n\n ";
1019 protected function createProxy(\$class, \Closure \$factory)
1021 {$proxyLoader}return \$factory();
1032 * Adds the normalizedIds property definition.
1036 private function addNormalizedIds()
1039 $normalizedIds = $this->container->getNormalizedIds();
1040 ksort($normalizedIds);
1041 foreach ($normalizedIds as $id => $normalizedId) {
1042 if ($this->container->has($normalizedId)) {
1043 $code .= ' '.$this->doExport($id).' => '.$this->doExport($normalizedId).",\n";
1047 return $code ? " \$this->normalizedIds = array(\n".$code." );\n" : '';
1051 * Adds the syntheticIds definition.
1055 private function addSyntheticIds()
1058 $definitions = $this->container->getDefinitions();
1059 ksort($definitions);
1060 foreach ($definitions as $id => $definition) {
1061 if ($definition->isSynthetic() && 'service_container' !== $id) {
1062 $code .= ' '.$this->doExport($id)." => true,\n";
1066 return $code ? " \$this->syntheticIds = array(\n{$code} );\n" : '';
1070 * Adds the removedIds definition.
1074 private function addRemovedIds()
1076 if (!$ids = $this->container->getRemovedIds()) {
1079 if ($this->asFiles) {
1080 $code = "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'";
1083 $ids = array_keys($ids);
1085 foreach ($ids as $id) {
1086 if (preg_match('/^\d+_[^~]++~[._a-zA-Z\d]{7}$/', $id)) {
1089 $code .= ' '.$this->doExport($id)." => true,\n";
1092 $code = "array(\n{$code} )";
1097 public function getRemovedIds()
1106 * Adds the methodMap property definition.
1110 private function addMethodMap()
1113 $definitions = $this->container->getDefinitions();
1114 ksort($definitions);
1115 foreach ($definitions as $id => $definition) {
1116 if (!$definition->isSynthetic() && (!$this->asFiles || !$definition->isShared() || $this->isHotPath($definition))) {
1117 $code .= ' '.$this->doExport($id).' => '.$this->doExport($this->generateMethodName($id)).",\n";
1121 return $code ? " \$this->methodMap = array(\n{$code} );\n" : '';
1125 * Adds the fileMap property definition.
1129 private function addFileMap()
1132 $definitions = $this->container->getDefinitions();
1133 ksort($definitions);
1134 foreach ($definitions as $id => $definition) {
1135 if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) {
1136 $code .= sprintf(" %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id));
1140 return $code ? " \$this->fileMap = array(\n{$code} );\n" : '';
1144 * Adds the privates property definition.
1148 private function addPrivateServices()
1152 $aliases = $this->container->getAliases();
1154 foreach ($aliases as $id => $alias) {
1155 if ($alias->isPrivate()) {
1156 $code .= ' '.$this->doExport($id)." => true,\n";
1160 $definitions = $this->container->getDefinitions();
1161 ksort($definitions);
1162 foreach ($definitions as $id => $definition) {
1163 if (!$definition->isPublic()) {
1164 $code .= ' '.$this->doExport($id)." => true,\n";
1172 $out = " \$this->privates = array(\n";
1180 * Adds the aliases property definition.
1184 private function addAliases()
1186 if (!$aliases = $this->container->getAliases()) {
1187 return $this->container->isCompiled() ? "\n \$this->aliases = array();\n" : '';
1190 $code = " \$this->aliases = array(\n";
1192 foreach ($aliases as $alias => $id) {
1193 $id = $this->container->normalizeId($id);
1194 while (isset($aliases[$id])) {
1195 $id = $this->container->normalizeId($aliases[$id]);
1197 $code .= ' '.$this->doExport($alias).' => '.$this->doExport($id).",\n";
1200 return $code." );\n";
1203 private function addInlineRequires()
1205 if (!$this->hotPathTag || !$this->inlineRequires) {
1211 foreach ($this->container->findTaggedServiceIds($this->hotPathTag) as $id => $tags) {
1212 $definition = $this->container->getDefinition($id);
1213 $inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition));
1215 foreach ($inlinedDefinitions as $def) {
1216 if (\is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) {
1217 $this->collectLineage($class, $lineage);
1224 foreach ($lineage as $file) {
1225 if (!isset($this->inlinedRequires[$file])) {
1226 $this->inlinedRequires[$file] = true;
1227 $code .= sprintf("\n include_once %s;", $file);
1231 return $code ? sprintf("\n \$this->privates['service_container'] = function () {%s\n };\n", $code) : '';
1235 * Adds default parameters method.
1239 private function addDefaultParametersMethod()
1241 if (!$this->container->getParameterBag()->all()) {
1246 $dynamicPhp = array();
1247 $normalizedParams = array();
1249 foreach ($this->container->getParameterBag()->all() as $key => $value) {
1250 if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) {
1251 throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: %s.', $resolvedKey));
1253 if ($key !== $lcKey = strtolower($key)) {
1254 $normalizedParams[] = sprintf(' %s => %s,', $this->export($lcKey), $this->export($key));
1256 $export = $this->exportParameters(array($value));
1257 $export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2);
1259 if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $export[1])) {
1260 $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]);
1262 $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]);
1265 $parameters = sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', 8));
1268 if ($this->container->isCompiled()) {
1271 public function getParameter($name)
1273 $name = (string) $name;
1274 if (isset($this->buildParameters[$name])) {
1275 return $this->buildParameters[$name];
1277 if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) {
1278 $name = $this->normalizeParameterName($name);
1280 if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) {
1281 throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
1284 if (isset($this->loadedDynamicParameters[$name])) {
1285 return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
1288 return $this->parameters[$name];
1291 public function hasParameter($name)
1293 $name = (string) $name;
1294 if (isset($this->buildParameters[$name])) {
1297 $name = $this->normalizeParameterName($name);
1299 return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters);
1302 public function setParameter($name, $value)
1304 throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
1307 public function getParameterBag()
1309 if (null === $this->parameterBag) {
1310 $parameters = $this->parameters;
1311 foreach ($this->loadedDynamicParameters as $name => $loaded) {
1312 $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
1314 foreach ($this->buildParameters as $name => $value) {
1315 $parameters[$name] = $value;
1317 $this->parameterBag = new FrozenParameterBag($parameters);
1320 return $this->parameterBag;
1324 if (!$this->asFiles) {
1325 $code = preg_replace('/^.*buildParameters.*\n.*\n.*\n/m', '', $code);
1329 $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, \count($dynamicPhp), false)), '', 8);
1330 $getDynamicParameter = <<<'EOF'
1333 default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name));
1335 $this->loadedDynamicParameters[$name] = true;
1337 return $this->dynamicParameters[$name] = $value;
1339 $getDynamicParameter = sprintf($getDynamicParameter, implode("\n", $dynamicPhp));
1341 $loadedDynamicParameters = 'array()';
1342 $getDynamicParameter = str_repeat(' ', 8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));';
1347 private \$loadedDynamicParameters = {$loadedDynamicParameters};
1348 private \$dynamicParameters = array();
1351 * Computes a dynamic parameter.
1353 * @param string The name of the dynamic parameter to load
1355 * @return mixed The value of the dynamic parameter
1357 * @throws InvalidArgumentException When the dynamic parameter does not exist
1359 private function getDynamicParameter(\$name)
1361 {$getDynamicParameter}
1367 $code .= ' private $normalizedParameterNames = '.($normalizedParams ? sprintf("array(\n%s\n );", implode("\n", $normalizedParams)) : 'array();')."\n";
1370 private function normalizeParameterName($name)
1372 if (isset($this->normalizedParameterNames[$normalizedName = strtolower($name)]) || isset($this->parameters[$normalizedName]) || array_key_exists($normalizedName, $this->parameters)) {
1373 $normalizedName = isset($this->normalizedParameterNames[$normalizedName]) ? $this->normalizedParameterNames[$normalizedName] : $normalizedName;
1374 if ((string) $name !== $normalizedName) {
1375 @trigger_error(sprintf('Parameter names will be made case sensitive in Symfony 4.0. Using "%s" instead of "%s" is deprecated since Symfony 3.4.', $name, $normalizedName), E_USER_DEPRECATED);
1378 $normalizedName = $this->normalizedParameterNames[$normalizedName] = (string) $name;
1381 return $normalizedName;
1385 } elseif ($dynamicPhp) {
1386 throw new RuntimeException('You cannot dump a not-frozen container with dynamic parameters.');
1392 * Gets the default parameters.
1394 * @return array An array of the default parameters
1396 protected function getDefaultParameters()
1407 * Exports parameters.
1409 * @param array $parameters
1410 * @param string $path
1411 * @param int $indent
1415 * @throws InvalidArgumentException
1417 private function exportParameters(array $parameters, $path = '', $indent = 12)
1420 foreach ($parameters as $key => $value) {
1421 if (\is_array($value)) {
1422 $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4);
1423 } elseif ($value instanceof ArgumentInterface) {
1424 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain special arguments. "%s" found in "%s".', \get_class($value), $path.'/'.$key));
1425 } elseif ($value instanceof Variable) {
1426 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key));
1427 } elseif ($value instanceof Definition) {
1428 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', $value->getClass(), $path.'/'.$key));
1429 } elseif ($value instanceof Reference) {
1430 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', $value, $path.'/'.$key));
1431 } elseif ($value instanceof Expression) {
1432 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key));
1434 $value = $this->export($value);
1437 $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), $this->export($key), $value);
1440 return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4));
1444 * Ends the class definition.
1448 private function endClass()
1457 * Wraps the service conditionals.
1459 * @param string $value
1460 * @param string $code
1464 private function wrapServiceConditionals($value, $code)
1466 if (!$condition = $this->getServiceConditionals($value)) {
1470 // re-indent the wrapped code
1471 $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
1473 return sprintf(" if (%s) {\n%s }\n", $condition, $code);
1477 * Get the conditions to execute for conditional services.
1479 * @param string $value
1481 * @return string|null
1483 private function getServiceConditionals($value)
1485 $conditions = array();
1486 foreach (ContainerBuilder::getInitializedConditionals($value) as $service) {
1487 if (!$this->container->hasDefinition($service)) {
1490 $conditions[] = sprintf("isset(\$this->services['%s'])", $service);
1492 foreach (ContainerBuilder::getServiceConditionals($value) as $service) {
1493 if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) {
1497 $conditions[] = sprintf("\$this->has('%s')", $service);
1504 return implode(' && ', $conditions);
1507 private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = array())
1509 if (null === $definitions) {
1510 $definitions = new \SplObjectStorage();
1513 foreach ($arguments as $argument) {
1514 if (\is_array($argument)) {
1515 $this->getDefinitionsFromArguments($argument, $definitions, $calls);
1516 } elseif ($argument instanceof Reference) {
1517 $id = $this->container->normalizeId($argument);
1519 if (!isset($calls[$id])) {
1520 $calls[$id] = array(0, $argument->getInvalidBehavior());
1522 $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior());
1526 } elseif (!$argument instanceof Definition) {
1528 } elseif (isset($definitions[$argument])) {
1529 $definitions[$argument] = 1 + $definitions[$argument];
1531 $definitions[$argument] = 1;
1532 $arguments = array($argument->getArguments(), $argument->getFactory(), $argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator());
1533 $this->getDefinitionsFromArguments($arguments, $definitions, $calls);
1537 return $definitions;
1543 * @param mixed $value
1544 * @param bool $interpolate
1548 * @throws RuntimeException
1550 private function dumpValue($value, $interpolate = true)
1552 if (\is_array($value)) {
1553 if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) {
1554 return $this->dumpValue("%$param%");
1557 foreach ($value as $k => $v) {
1558 $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
1561 return sprintf('array(%s)', implode(', ', $code));
1562 } elseif ($value instanceof ArgumentInterface) {
1563 $scope = array($this->definitionVariables, $this->referenceVariables);
1564 $this->definitionVariables = $this->referenceVariables = null;
1567 if ($value instanceof ServiceClosureArgument) {
1568 $value = $value->getValues()[0];
1569 $code = $this->dumpValue($value, $interpolate);
1571 if ($value instanceof TypedReference) {
1572 $code = sprintf('$f = function (\\%s $v%s) { return $v; }; return $f(%s);', $value->getType(), ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $value->getInvalidBehavior() ? ' = null' : '', $code);
1574 $code = sprintf('return %s;', $code);
1577 return sprintf("function () {\n %s\n }", $code);
1580 if ($value instanceof IteratorArgument) {
1581 $operands = array(0);
1583 $code[] = 'new RewindableGenerator(function () {';
1585 if (!$values = $value->getValues()) {
1586 $code[] = ' return new \EmptyIterator();';
1588 $countCode = array();
1589 $countCode[] = 'function () {';
1591 foreach ($values as $k => $v) {
1592 ($c = $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0];
1593 $v = $this->wrapServiceConditionals($v, sprintf(" yield %s => %s;\n", $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)));
1594 foreach (explode("\n", $v) as $v) {
1601 $countCode[] = sprintf(' return %s;', implode(' + ', $operands));
1602 $countCode[] = ' }';
1605 $code[] = sprintf(' }, %s)', \count($operands) > 1 ? implode("\n", $countCode) : $operands[0]);
1607 return implode("\n", $code);
1610 list($this->definitionVariables, $this->referenceVariables) = $scope;
1612 } elseif ($value instanceof Definition) {
1613 if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
1614 return $this->dumpValue($this->definitionVariables[$value], $interpolate);
1616 if ($value->getMethodCalls()) {
1617 throw new RuntimeException('Cannot dump definitions which have method calls.');
1619 if ($value->getProperties()) {
1620 throw new RuntimeException('Cannot dump definitions which have properties.');
1622 if (null !== $value->getConfigurator()) {
1623 throw new RuntimeException('Cannot dump definitions which have a configurator.');
1626 $arguments = array();
1627 foreach ($value->getArguments() as $argument) {
1628 $arguments[] = $this->dumpValue($argument);
1631 if (null !== $value->getFactory()) {
1632 $factory = $value->getFactory();
1634 if (\is_string($factory)) {
1635 return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments));
1638 if (\is_array($factory)) {
1639 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) {
1640 throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a'));
1643 $class = $this->dumpValue($factory[0]);
1644 if (\is_string($factory[0])) {
1645 return sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $factory[1], implode(', ', $arguments));
1648 if ($factory[0] instanceof Definition) {
1649 if (0 === strpos($class, 'new ')) {
1650 return sprintf('(%s)->%s(%s)', $class, $factory[1], implode(', ', $arguments));
1653 return sprintf("\\call_user_func(array(%s, '%s')%s)", $class, $factory[1], \count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
1656 if ($factory[0] instanceof Reference) {
1657 return sprintf('%s->%s(%s)', $class, $factory[1], implode(', ', $arguments));
1661 throw new RuntimeException('Cannot dump definition because of invalid factory');
1664 $class = $value->getClass();
1665 if (null === $class) {
1666 throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
1669 return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments));
1670 } elseif ($value instanceof Variable) {
1672 } elseif ($value instanceof Reference) {
1673 $id = $this->container->normalizeId($value);
1674 if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) {
1675 return $this->dumpValue($this->referenceVariables[$id], $interpolate);
1678 return $this->getServiceCall($id, $value);
1679 } elseif ($value instanceof Expression) {
1680 return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container'));
1681 } elseif ($value instanceof Parameter) {
1682 return $this->dumpParameter($value);
1683 } elseif (true === $interpolate && \is_string($value)) {
1684 if (preg_match('/^%([^%]+)%$/', $value, $match)) {
1685 // we do this to deal with non string values (Boolean, integer, ...)
1686 // the preg_replace_callback converts them to strings
1687 return $this->dumpParameter($match[1]);
1689 $replaceParameters = function ($match) {
1690 return "'.".$this->dumpParameter($match[2]).".'";
1693 $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value)));
1697 } elseif (\is_object($value) || \is_resource($value)) {
1698 throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
1701 return $this->export($value);
1705 * Dumps a string to a literal (aka PHP Code) class value.
1707 * @param string $class
1711 * @throws RuntimeException
1713 private function dumpLiteralClass($class)
1715 if (false !== strpos($class, '$')) {
1716 return sprintf('${($_ = %s) && false ?: "_"}', $class);
1718 if (0 !== strpos($class, "'") || !preg_match('/^\'(?:\\\{2})?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
1719 throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s)', $class ?: 'n/a'));
1722 $class = substr(str_replace('\\\\', '\\', $class), 1, -1);
1724 return 0 === strpos($class, '\\') ? $class : '\\'.$class;
1728 * Dumps a parameter.
1730 * @param string $name
1734 private function dumpParameter($name)
1736 if ($this->container->isCompiled() && $this->container->hasParameter($name)) {
1737 $value = $this->container->getParameter($name);
1738 $dumpedValue = $this->dumpValue($value, false);
1740 if (!$value || !\is_array($value)) {
1741 return $dumpedValue;
1744 if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
1745 return sprintf("\$this->parameters['%s']", $name);
1749 return sprintf("\$this->getParameter('%s')", $name);
1753 * Gets a service call.
1756 * @param Reference $reference
1760 private function getServiceCall($id, Reference $reference = null)
1762 while ($this->container->hasAlias($id)) {
1763 $id = (string) $this->container->getAlias($id);
1765 $id = $this->container->normalizeId($id);
1767 if ('service_container' === $id) {
1771 if ($this->container->hasDefinition($id) && $definition = $this->container->getDefinition($id)) {
1772 if ($definition->isSynthetic()) {
1773 $code = sprintf('$this->get(\'%s\'%s)', $id, null !== $reference ? ', '.$reference->getInvalidBehavior() : '');
1774 } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
1776 if (!$definition->isShared()) {
1779 } elseif ($this->isTrivialInstance($definition)) {
1780 $code = substr($this->addNewInstance($definition, '', '', $id), 8, -2);
1781 if ($definition->isShared()) {
1782 $code = sprintf('$this->services[\'%s\'] = %s', $id, $code);
1784 } elseif ($this->asFiles && $definition->isShared() && !$this->isHotPath($definition)) {
1785 $code = sprintf("\$this->load('%s.php')", $this->generateMethodName($id));
1787 $code = sprintf('$this->%s()', $this->generateMethodName($id));
1789 } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
1791 } elseif (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
1792 $code = sprintf('$this->get(\'%s\', /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $id, ContainerInterface::NULL_ON_INVALID_REFERENCE);
1794 $code = sprintf('$this->get(\'%s\')', $id);
1797 // The following is PHP 5.5 syntax for what could be written as "(\$this->services['$id'] ?? $code)" on PHP>=7.0
1799 return "\${(\$_ = isset(\$this->services['$id']) ? \$this->services['$id'] : $code) && false ?: '_'}";
1803 * Initializes the method names map to avoid conflicts with the Container methods.
1805 * @param string $class the container base class
1807 private function initializeMethodNamesMap($class)
1809 $this->serviceIdToMethodNameMap = array();
1810 $this->usedMethodNames = array();
1812 if ($reflectionClass = $this->container->getReflectionClass($class)) {
1813 foreach ($reflectionClass->getMethods() as $method) {
1814 $this->usedMethodNames[strtolower($method->getName())] = true;
1820 * Convert a service id to a valid PHP method name.
1826 * @throws InvalidArgumentException
1828 private function generateMethodName($id)
1830 if (isset($this->serviceIdToMethodNameMap[$id])) {
1831 return $this->serviceIdToMethodNameMap[$id];
1834 $i = strrpos($id, '\\');
1835 $name = Container::camelize(false !== $i && isset($id[1 + $i]) ? substr($id, 1 + $i) : $id);
1836 $name = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '', $name);
1837 $methodName = 'get'.$name.'Service';
1840 while (isset($this->usedMethodNames[strtolower($methodName)])) {
1842 $methodName = 'get'.$name.$suffix.'Service';
1845 $this->serviceIdToMethodNameMap[$id] = $methodName;
1846 $this->usedMethodNames[strtolower($methodName)] = true;
1852 * Returns the next name to use.
1856 private function getNextVariableName()
1858 $firstChars = self::FIRST_CHARS;
1859 $firstCharsLength = \strlen($firstChars);
1860 $nonFirstChars = self::NON_FIRST_CHARS;
1861 $nonFirstCharsLength = \strlen($nonFirstChars);
1865 $i = $this->variableCount;
1868 $name .= $firstChars[$i % $firstCharsLength];
1869 $i = (int) ($i / $firstCharsLength);
1874 $name .= $nonFirstChars[$i % $nonFirstCharsLength];
1875 $i = (int) ($i / $nonFirstCharsLength);
1878 ++$this->variableCount;
1880 // check that the name is not reserved
1881 if (\in_array($name, $this->reservedVariables, true)) {
1889 private function getExpressionLanguage()
1891 if (null === $this->expressionLanguage) {
1892 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
1893 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
1895 $providers = $this->container->getExpressionLanguageProviders();
1896 $this->expressionLanguage = new ExpressionLanguage(null, $providers, function ($arg) {
1897 $id = '""' === substr_replace($arg, '', 1, -1) ? stripcslashes(substr($arg, 1, -1)) : null;
1899 if (null !== $id && ($this->container->hasAlias($id) || $this->container->hasDefinition($id))) {
1900 return $this->getServiceCall($id);
1903 return sprintf('$this->get(%s)', $arg);
1906 if ($this->container->isTrackingResources()) {
1907 foreach ($providers as $provider) {
1908 $this->container->addObjectResource($provider);
1913 return $this->expressionLanguage;
1916 private function isHotPath(Definition $definition)
1918 return $this->hotPathTag && $definition->hasTag($this->hotPathTag) && !$definition->isDeprecated();
1921 private function export($value)
1923 if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) {
1924 $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1]), true).'.' : '';
1925 $suffix = $matches[0][1] + \strlen($matches[0][0]);
1926 $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : '';
1927 $dirname = $this->asFiles ? '$this->containerDir' : '__DIR__';
1928 $offset = 1 + $this->targetDirMaxMatches - \count($matches);
1930 if ($this->asFiles || 0 < $offset) {
1931 $dirname = sprintf('$this->targetDirs[%d]', $offset);
1934 if ($prefix || $suffix) {
1935 return sprintf('(%s%s%s)', $prefix, $dirname, $suffix);
1941 return $this->doExport($value, true);
1944 private function doExport($value, $resolveEnv = false)
1946 if (\is_string($value) && false !== strpos($value, "\n")) {
1947 $cleanParts = explode("\n", $value);
1948 $cleanParts = array_map(function ($part) { return var_export($part, true); }, $cleanParts);
1949 $export = implode('."\n".', $cleanParts);
1951 $export = var_export($value, true);
1954 if ($resolveEnv && "'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('string:%s').'")) {
1955 $export = $resolvedExport;
1956 if (".''" === substr($export, -3)) {
1957 $export = substr($export, 0, -3);
1958 if ("'" === $export[1]) {
1959 $export = substr_replace($export, '', 18, 7);
1962 if ("'" === $export[1]) {
1963 $export = substr($export, 3);