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\Variable;
15 use Symfony\Component\DependencyInjection\Definition;
16 use Symfony\Component\DependencyInjection\ContainerBuilder;
17 use Symfony\Component\DependencyInjection\Container;
18 use Symfony\Component\DependencyInjection\ContainerInterface;
19 use Symfony\Component\DependencyInjection\Reference;
20 use Symfony\Component\DependencyInjection\Parameter;
21 use Symfony\Component\DependencyInjection\Exception\EnvParameterException;
22 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
23 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
24 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
25 use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;
26 use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;
27 use Symfony\Component\DependencyInjection\ExpressionLanguage;
28 use Symfony\Component\ExpressionLanguage\Expression;
29 use Symfony\Component\HttpKernel\Kernel;
32 * PhpDumper dumps a service container as a PHP class.
34 * @author Fabien Potencier <fabien@symfony.com>
35 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
37 class PhpDumper extends Dumper
40 * Characters that might appear in the generated variable name as first character.
44 const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz';
47 * Characters that might appear in the generated variable name as any but the first character.
51 const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_';
53 private $inlinedDefinitions;
54 private $definitionVariables;
55 private $referenceVariables;
56 private $variableCount;
57 private $reservedVariables = array('instance', 'class');
58 private $expressionLanguage;
59 private $targetDirRegex;
60 private $targetDirMaxMatches;
62 private $serviceIdToMethodNameMap;
63 private $usedMethodNames;
66 * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface
73 public function __construct(ContainerBuilder $container)
75 parent::__construct($container);
77 $this->inlinedDefinitions = new \SplObjectStorage();
81 * Sets the dumper to be used when dumping proxies in the generated container.
83 * @param ProxyDumper $proxyDumper
85 public function setProxyDumper(ProxyDumper $proxyDumper)
87 $this->proxyDumper = $proxyDumper;
91 * Dumps the service container as a PHP class.
95 * * class: The class name
96 * * base_class: The base class name
97 * * namespace: The class namespace
99 * @param array $options An array of options
101 * @return string A PHP class representing of the service container
103 * @throws EnvParameterException When an env var exists but has not been dumped
105 public function dump(array $options = array())
107 $this->targetDirRegex = null;
108 $options = array_merge(array(
109 'class' => 'ProjectServiceContainer',
110 'base_class' => 'Container',
115 $this->initializeMethodNamesMap($options['base_class']);
117 $this->docStar = $options['debug'] ? '*' : '';
119 if (!empty($options['file']) && is_dir($dir = dirname($options['file']))) {
120 // Build a regexp where the first root dirs are mandatory,
121 // but every other sub-dir is optional up to the full path in $dir
122 // Mandate at least 2 root dirs and not more that 5 optional dirs.
124 $dir = explode(DIRECTORY_SEPARATOR, realpath($dir));
129 $lastOptionalDir = $i > 8 ? $i - 5 : 3;
130 $this->targetDirMaxMatches = $i - $lastOptionalDir;
132 while (--$i >= $lastOptionalDir) {
133 $regex = sprintf('(%s%s)?', preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex);
137 $regex = preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#').$regex;
140 $this->targetDirRegex = '#'.preg_quote($dir[0], '#').$regex.'#';
144 $code = $this->startClass($options['class'], $options['base_class'], $options['namespace']);
146 if ($this->container->isFrozen()) {
147 $code .= $this->addFrozenConstructor();
148 $code .= $this->addFrozenCompile();
149 $code .= $this->addIsFrozenMethod();
151 $code .= $this->addConstructor();
155 $this->addServices().
156 $this->addDefaultParametersMethod().
158 $this->addProxyClasses()
160 $this->targetDirRegex = null;
162 $unusedEnvs = array();
163 foreach ($this->container->getEnvCounters() as $env => $use) {
165 $unusedEnvs[] = $env;
169 throw new EnvParameterException($unusedEnvs, null, 'Environment variables "%s" are never used. Please, check your container\'s configuration.');
176 * Retrieves the currently set proxy dumper or instantiates one.
178 * @return ProxyDumper
180 private function getProxyDumper()
182 if (!$this->proxyDumper) {
183 $this->proxyDumper = new NullDumper();
186 return $this->proxyDumper;
190 * Generates Service local temp variables.
193 * @param string $definition
197 private function addServiceLocalTempVariables($cId, $definition)
199 static $template = " \$%s = %s;\n";
201 $localDefinitions = array_merge(
203 $this->getInlinedDefinitions($definition)
206 $calls = $behavior = array();
207 foreach ($localDefinitions as $iDefinition) {
208 $this->getServiceCallsFromArguments($iDefinition->getArguments(), $calls, $behavior);
209 $this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior);
210 $this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior);
211 $this->getServiceCallsFromArguments(array($iDefinition->getConfigurator()), $calls, $behavior);
212 $this->getServiceCallsFromArguments(array($iDefinition->getFactory()), $calls, $behavior);
216 foreach ($calls as $id => $callCount) {
217 if ('service_container' === $id || $id === $cId) {
221 if ($callCount > 1) {
222 $name = $this->getNextVariableName();
223 $this->referenceVariables[$id] = new Variable($name);
225 if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id]) {
226 $code .= sprintf($template, $name, $this->getServiceCall($id));
228 $code .= sprintf($template, $name, $this->getServiceCall($id, new Reference($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)));
241 * Generates code for the proxies to be attached after the container class.
245 private function addProxyClasses()
247 /* @var $definitions Definition[] */
248 $definitions = array_filter(
249 $this->container->getDefinitions(),
250 array($this->getProxyDumper(), 'isProxyCandidate')
253 $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments');
255 foreach ($definitions as $definition) {
256 $proxyCode = "\n".$this->getProxyDumper()->getProxyCode($definition);
258 $proxyCode = "<?php\n".$proxyCode;
259 $proxyCode = substr(Kernel::stripComments($proxyCode), 5);
268 * Generates the require_once statement for service includes.
270 * @param Definition $definition
274 private function addServiceInclude($definition)
276 $template = " require_once %s;\n";
279 if (null !== $file = $definition->getFile()) {
280 $code .= sprintf($template, $this->dumpValue($file));
283 foreach ($this->getInlinedDefinitions($definition) as $definition) {
284 if (null !== $file = $definition->getFile()) {
285 $code .= sprintf($template, $this->dumpValue($file));
297 * Generates the inline definition of a service.
300 * @param Definition $definition
304 * @throws RuntimeException When the factory definition is incomplete
305 * @throws ServiceCircularReferenceException When a circular reference is detected
307 private function addServiceInlinedDefinitions($id, $definition)
310 $variableMap = $this->definitionVariables;
311 $nbOccurrences = new \SplObjectStorage();
312 $processed = new \SplObjectStorage();
313 $inlinedDefinitions = $this->getInlinedDefinitions($definition);
315 foreach ($inlinedDefinitions as $definition) {
316 if (false === $nbOccurrences->contains($definition)) {
317 $nbOccurrences->offsetSet($definition, 1);
319 $i = $nbOccurrences->offsetGet($definition);
320 $nbOccurrences->offsetSet($definition, $i + 1);
324 foreach ($inlinedDefinitions as $sDefinition) {
325 if ($processed->contains($sDefinition)) {
328 $processed->offsetSet($sDefinition);
330 $class = $this->dumpValue($sDefinition->getClass());
331 if ($nbOccurrences->offsetGet($sDefinition) > 1 || $sDefinition->getMethodCalls() || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) {
332 $name = $this->getNextVariableName();
333 $variableMap->offsetSet($sDefinition, new Variable($name));
336 // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a);
337 // this is an indication for a wrong implementation, you can circumvent this problem
338 // by setting up your service structure like this:
339 // $b = new ServiceB();
340 // $a = new ServiceA(ServiceB $b);
341 // $b->setServiceA(ServiceA $a);
342 if ($this->hasReference($id, $sDefinition->getArguments())) {
343 throw new ServiceCircularReferenceException($id, array($id));
346 $code .= $this->addNewInstance($sDefinition, '$'.$name, ' = ', $id);
348 if (!$this->hasReference($id, $sDefinition->getMethodCalls(), true) && !$this->hasReference($id, $sDefinition->getProperties(), true)) {
349 $code .= $this->addServiceProperties($sDefinition, $name);
350 $code .= $this->addServiceMethodCalls($sDefinition, $name);
351 $code .= $this->addServiceConfigurator($sDefinition, $name);
362 * Adds the service return statement.
364 * @param string $id Service id
365 * @param Definition $definition
369 private function addServiceReturn($id, $definition)
371 if ($this->isSimpleInstance($id, $definition)) {
375 return "\n return \$instance;\n }\n";
379 * Generates the service instance.
382 * @param Definition $definition
386 * @throws InvalidArgumentException
387 * @throws RuntimeException
389 private function addServiceInstance($id, Definition $definition)
391 $class = $this->dumpValue($definition->getClass());
393 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)) {
394 throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
397 $simple = $this->isSimpleInstance($id, $definition);
398 $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
401 if (!$isProxyCandidate && $definition->isShared()) {
402 $instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance');
403 } elseif (!$simple) {
404 $instantiation = '$instance';
411 $instantiation .= ' = ';
414 $code = $this->addNewInstance($definition, $return, $instantiation, $id);
424 * Checks if the definition is a simple instance.
427 * @param Definition $definition
431 private function isSimpleInstance($id, Definition $definition)
433 foreach (array_merge(array($definition), $this->getInlinedDefinitions($definition)) as $sDefinition) {
434 if ($definition !== $sDefinition && !$this->hasReference($id, $sDefinition->getMethodCalls())) {
438 if ($sDefinition->getMethodCalls() || $sDefinition->getProperties() || $sDefinition->getConfigurator()) {
447 * Adds method calls to a service definition.
449 * @param Definition $definition
450 * @param string $variableName
454 private function addServiceMethodCalls(Definition $definition, $variableName = 'instance')
457 foreach ($definition->getMethodCalls() as $call) {
458 $arguments = array();
459 foreach ($call[1] as $value) {
460 $arguments[] = $this->dumpValue($value);
463 $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments)));
469 private function addServiceProperties(Definition $definition, $variableName = 'instance')
472 foreach ($definition->getProperties() as $name => $value) {
473 $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value));
480 * Generates the inline definition setup.
483 * @param Definition $definition
487 * @throws ServiceCircularReferenceException when the container contains a circular reference
489 private function addServiceInlinedDefinitionsSetup($id, Definition $definition)
491 $this->referenceVariables[$id] = new Variable('instance');
494 $processed = new \SplObjectStorage();
495 foreach ($this->getInlinedDefinitions($definition) as $iDefinition) {
496 if ($processed->contains($iDefinition)) {
499 $processed->offsetSet($iDefinition);
501 if (!$this->hasReference($id, $iDefinition->getMethodCalls(), true) && !$this->hasReference($id, $iDefinition->getProperties(), true)) {
505 // if the instance is simple, the return statement has already been generated
506 // so, the only possible way to get there is because of a circular reference
507 if ($this->isSimpleInstance($id, $definition)) {
508 throw new ServiceCircularReferenceException($id, array($id));
511 $name = (string) $this->definitionVariables->offsetGet($iDefinition);
512 $code .= $this->addServiceProperties($iDefinition, $name);
513 $code .= $this->addServiceMethodCalls($iDefinition, $name);
514 $code .= $this->addServiceConfigurator($iDefinition, $name);
525 * Adds configurator definition.
527 * @param Definition $definition
528 * @param string $variableName
532 private function addServiceConfigurator(Definition $definition, $variableName = 'instance')
534 if (!$callable = $definition->getConfigurator()) {
538 if (is_array($callable)) {
539 if ($callable[0] instanceof Reference
540 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
541 return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
544 $class = $this->dumpValue($callable[0]);
545 // If the class is a string we can optimize call_user_func away
546 if (0 === strpos($class, "'") && false === strpos($class, '$')) {
547 return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName);
550 if (0 === strpos($class, 'new ')) {
551 return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
554 return sprintf(" call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
557 return sprintf(" %s(\$%s);\n", $callable, $variableName);
564 * @param Definition $definition
568 private function addService($id, Definition $definition)
570 $this->definitionVariables = new \SplObjectStorage();
571 $this->referenceVariables = array();
572 $this->variableCount = 0;
576 if ($definition->isSynthetic()) {
577 $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically';
578 } elseif ($class = $definition->getClass()) {
579 $class = $this->container->resolveEnvPlaceholders($class);
580 $return[] = sprintf(0 === strpos($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\'));
581 } elseif ($definition->getFactory()) {
582 $factory = $definition->getFactory();
583 if (is_string($factory)) {
584 $return[] = sprintf('@return object An instance returned by %s()', $factory);
585 } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
586 if (is_string($factory[0]) || $factory[0] instanceof Reference) {
587 $return[] = sprintf('@return object An instance returned by %s::%s()', (string) $factory[0], $factory[1]);
588 } elseif ($factory[0] instanceof Definition) {
589 $return[] = sprintf('@return object An instance returned by %s::%s()', $factory[0]->getClass(), $factory[1]);
594 if ($definition->isDeprecated()) {
595 if ($return && 0 === strpos($return[count($return) - 1], '@return')) {
599 $return[] = sprintf('@deprecated %s', $definition->getDeprecationMessage($id));
602 $return = str_replace("\n * \n", "\n *\n", implode("\n * ", $return));
603 $return = $this->container->resolveEnvPlaceholders($return);
605 $shared = $definition->isShared() ? ' shared' : '';
606 $public = $definition->isPublic() ? 'public' : 'private';
607 $autowired = $definition->isAutowired() ? ' autowired' : '';
609 if ($definition->isLazy()) {
610 $lazyInitialization = '$lazyLoad = true';
612 $lazyInitialization = '';
615 // with proxies, for 5.3.3 compatibility, the getter must be public to be accessible to the initializer
616 $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
617 $visibility = $isProxyCandidate ? 'public' : 'protected';
618 $methodName = $this->generateMethodName($id);
622 * Gets the $public '$id'$shared$autowired service.
626 {$visibility} function {$methodName}($lazyInitialization)
631 $code .= $isProxyCandidate ? $this->getProxyDumper()->getProxyFactoryCode($definition, $id, $methodName) : '';
633 if ($definition->isSynthetic()) {
634 $code .= sprintf(" throw new RuntimeException('You have requested a synthetic service (\"%s\"). The DIC does not know how to construct this service.');\n }\n", $id);
636 if ($definition->isDeprecated()) {
637 $code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id)));
641 $this->addServiceInclude($definition).
642 $this->addServiceLocalTempVariables($id, $definition).
643 $this->addServiceInlinedDefinitions($id, $definition).
644 $this->addServiceInstance($id, $definition).
645 $this->addServiceInlinedDefinitionsSetup($id, $definition).
646 $this->addServiceProperties($definition).
647 $this->addServiceMethodCalls($definition).
648 $this->addServiceConfigurator($definition).
649 $this->addServiceReturn($id, $definition)
653 $this->definitionVariables = null;
654 $this->referenceVariables = null;
660 * Adds multiple services.
664 private function addServices()
666 $publicServices = $privateServices = '';
667 $definitions = $this->container->getDefinitions();
669 foreach ($definitions as $id => $definition) {
670 if ($definition->isPublic()) {
671 $publicServices .= $this->addService($id, $definition);
673 $privateServices .= $this->addService($id, $definition);
677 return $publicServices.$privateServices;
680 private function addNewInstance(Definition $definition, $return, $instantiation, $id)
682 $class = $this->dumpValue($definition->getClass());
684 $arguments = array();
685 foreach ($definition->getArguments() as $value) {
686 $arguments[] = $this->dumpValue($value);
689 if (null !== $definition->getFactory()) {
690 $callable = $definition->getFactory();
691 if (is_array($callable)) {
692 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) {
693 throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $callable[1] ?: 'n/a'));
696 if ($callable[0] instanceof Reference
697 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
698 return sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '');
701 $class = $this->dumpValue($callable[0]);
702 // If the class is a string we can optimize call_user_func away
703 if (0 === strpos($class, "'") && false === strpos($class, '$')) {
704 if ("''" === $class) {
705 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));
708 return sprintf(" $return{$instantiation}%s::%s(%s);\n", $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '');
711 if (0 === strpos($class, 'new ')) {
712 return sprintf(" $return{$instantiation}(%s)->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '');
715 return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? ', '.implode(', ', $arguments) : '');
718 return sprintf(" $return{$instantiation}%s(%s);\n", $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : '');
721 if (false !== strpos($class, '$')) {
722 return sprintf(" \$class = %s;\n\n $return{$instantiation}new \$class(%s);\n", $class, implode(', ', $arguments));
725 return sprintf(" $return{$instantiation}new %s(%s);\n", $this->dumpLiteralClass($class), implode(', ', $arguments));
729 * Adds the class headers.
731 * @param string $class Class name
732 * @param string $baseClass The name of the base class
733 * @param string $namespace The class namespace
737 private function startClass($class, $baseClass, $namespace)
739 $bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;';
740 $namespaceLine = $namespace ? "\nnamespace $namespace;\n" : '';
745 use Symfony\Component\DependencyInjection\ContainerInterface;
746 use Symfony\Component\DependencyInjection\Container;
747 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
748 use Symfony\Component\DependencyInjection\Exception\LogicException;
749 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
755 * This class has been auto-generated
756 * by the Symfony Dependency Injection Component.
758 class $class extends $baseClass
760 private \$parameters;
761 private \$targetDirs = array();
767 * Adds the constructor.
771 private function addConstructor()
773 $targetDirs = $this->exportTargetDirs();
774 $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null;
781 public function __construct()
783 parent::__construct($arguments);
787 $code .= $this->addMethodMap();
788 $code .= $this->addPrivateServices();
789 $code .= $this->addAliases();
800 * Adds the constructor for a frozen container.
804 private function addFrozenConstructor()
806 $targetDirs = $this->exportTargetDirs();
813 public function __construct()
817 if ($this->container->getParameterBag()->all()) {
818 $code .= "\n \$this->parameters = \$this->getDefaultParameters();\n";
821 $code .= "\n \$this->services = array();\n";
822 $code .= $this->addMethodMap();
823 $code .= $this->addPrivateServices();
824 $code .= $this->addAliases();
835 * Adds the constructor for a frozen container.
839 private function addFrozenCompile()
846 public function compile()
848 throw new LogicException('You cannot compile a dumped frozen container.');
855 * Adds the isFrozen method for a frozen container.
859 private function addIsFrozenMethod()
866 public function isFrozen()
875 * Adds the methodMap property definition.
879 private function addMethodMap()
881 if (!$definitions = $this->container->getDefinitions()) {
885 $code = " \$this->methodMap = array(\n";
887 foreach ($definitions as $id => $definition) {
888 $code .= ' '.$this->export($id).' => '.$this->export($this->generateMethodName($id)).",\n";
891 return $code." );\n";
895 * Adds the privates property definition.
899 private function addPrivateServices()
901 if (!$definitions = $this->container->getDefinitions()) {
907 foreach ($definitions as $id => $definition) {
908 if (!$definition->isPublic()) {
909 $code .= ' '.$this->export($id)." => true,\n";
917 $out = " \$this->privates = array(\n";
925 * Adds the aliases property definition.
929 private function addAliases()
931 if (!$aliases = $this->container->getAliases()) {
932 return $this->container->isFrozen() ? "\n \$this->aliases = array();\n" : '';
935 $code = " \$this->aliases = array(\n";
937 foreach ($aliases as $alias => $id) {
939 while (isset($aliases[$id])) {
940 $id = (string) $aliases[$id];
942 $code .= ' '.$this->export($alias).' => '.$this->export($id).",\n";
945 return $code." );\n";
949 * Adds default parameters method.
953 private function addDefaultParametersMethod()
955 if (!$this->container->getParameterBag()->all()) {
960 $dynamicPhp = array();
962 foreach ($this->container->getParameterBag()->all() as $key => $value) {
963 if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) {
964 throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: %s.', $resolvedKey));
966 $export = $this->exportParameters(array($value));
967 $export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2);
969 if (preg_match("/\\\$this->(?:getEnv\('\w++'\)|targetDirs\[\d++\])/", $export[1])) {
970 $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]);
972 $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]);
975 $parameters = sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', 8));
978 if ($this->container->isFrozen()) {
984 public function getParameter($name)
986 $name = strtolower($name);
988 if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters) || isset($this->loadedDynamicParameters[$name]))) {
989 throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
991 if (isset($this->loadedDynamicParameters[$name])) {
992 return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
995 return $this->parameters[$name];
1001 public function hasParameter($name)
1003 $name = strtolower($name);
1005 return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters) || isset($this->loadedDynamicParameters[$name]);
1011 public function setParameter($name, $value)
1013 throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
1019 public function getParameterBag()
1021 if (null === $this->parameterBag) {
1022 $parameters = $this->parameters;
1023 foreach ($this->loadedDynamicParameters as $name => $loaded) {
1024 $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
1026 $this->parameterBag = new FrozenParameterBag($parameters);
1029 return $this->parameterBag;
1033 if ('' === $this->docStar) {
1034 $code = str_replace('/**', '/*', $code);
1038 $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, count($dynamicPhp), false)), '', 8);
1039 $getDynamicParameter = <<<'EOF'
1042 default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name));
1044 $this->loadedDynamicParameters[$name] = true;
1046 return $this->dynamicParameters[$name] = $value;
1048 $getDynamicParameter = sprintf($getDynamicParameter, implode("\n", $dynamicPhp));
1050 $loadedDynamicParameters = 'array()';
1051 $getDynamicParameter = str_repeat(' ', 8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));';
1056 private \$loadedDynamicParameters = {$loadedDynamicParameters};
1057 private \$dynamicParameters = array();
1060 * Computes a dynamic parameter.
1062 * @param string The name of the dynamic parameter to load
1064 * @return mixed The value of the dynamic parameter
1066 * @throws InvalidArgumentException When the dynamic parameter does not exist
1068 private function getDynamicParameter(\$name)
1070 {$getDynamicParameter}
1074 } elseif ($dynamicPhp) {
1075 throw new RuntimeException('You cannot dump a not-frozen container with dynamic parameters.');
1081 * Gets the default parameters.
1083 * @return array An array of the default parameters
1085 protected function getDefaultParameters()
1096 * Exports parameters.
1098 * @param array $parameters
1099 * @param string $path
1100 * @param int $indent
1104 * @throws InvalidArgumentException
1106 private function exportParameters(array $parameters, $path = '', $indent = 12)
1109 foreach ($parameters as $key => $value) {
1110 if (is_array($value)) {
1111 $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4);
1112 } elseif ($value instanceof Variable) {
1113 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key));
1114 } elseif ($value instanceof Definition) {
1115 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));
1116 } elseif ($value instanceof Reference) {
1117 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));
1118 } elseif ($value instanceof Expression) {
1119 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key));
1121 $value = $this->export($value);
1124 $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), $this->export($key), $value);
1127 return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4));
1131 * Ends the class definition.
1135 private function endClass()
1144 * Wraps the service conditionals.
1146 * @param string $value
1147 * @param string $code
1151 private function wrapServiceConditionals($value, $code)
1153 if (!$services = ContainerBuilder::getServiceConditionals($value)) {
1157 $conditions = array();
1158 foreach ($services as $service) {
1159 if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) {
1163 $conditions[] = sprintf("\$this->has('%s')", $service);
1170 // re-indent the wrapped code
1171 $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
1173 return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code);
1177 * Builds service calls from arguments.
1179 * @param array $arguments
1180 * @param array &$calls By reference
1181 * @param array &$behavior By reference
1183 private function getServiceCallsFromArguments(array $arguments, array &$calls, array &$behavior)
1185 foreach ($arguments as $argument) {
1186 if (is_array($argument)) {
1187 $this->getServiceCallsFromArguments($argument, $calls, $behavior);
1188 } elseif ($argument instanceof Reference) {
1189 $id = (string) $argument;
1191 if (!isset($calls[$id])) {
1194 if (!isset($behavior[$id])) {
1195 $behavior[$id] = $argument->getInvalidBehavior();
1196 } elseif (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) {
1197 $behavior[$id] = $argument->getInvalidBehavior();
1206 * Returns the inline definition.
1208 * @param Definition $definition
1212 private function getInlinedDefinitions(Definition $definition)
1214 if (false === $this->inlinedDefinitions->contains($definition)) {
1215 $definitions = array_merge(
1216 $this->getDefinitionsFromArguments($definition->getArguments()),
1217 $this->getDefinitionsFromArguments($definition->getMethodCalls()),
1218 $this->getDefinitionsFromArguments($definition->getProperties()),
1219 $this->getDefinitionsFromArguments(array($definition->getConfigurator())),
1220 $this->getDefinitionsFromArguments(array($definition->getFactory()))
1223 $this->inlinedDefinitions->offsetSet($definition, $definitions);
1225 return $definitions;
1228 return $this->inlinedDefinitions->offsetGet($definition);
1232 * Gets the definition from arguments.
1234 * @param array $arguments
1238 private function getDefinitionsFromArguments(array $arguments)
1240 $definitions = array();
1241 foreach ($arguments as $argument) {
1242 if (is_array($argument)) {
1243 $definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument));
1244 } elseif ($argument instanceof Definition) {
1245 $definitions = array_merge(
1247 $this->getInlinedDefinitions($argument),
1253 return $definitions;
1257 * Checks if a service id has a reference.
1260 * @param array $arguments
1262 * @param array $visited
1266 private function hasReference($id, array $arguments, $deep = false, array &$visited = array())
1268 foreach ($arguments as $argument) {
1269 if (is_array($argument)) {
1270 if ($this->hasReference($id, $argument, $deep, $visited)) {
1273 } elseif ($argument instanceof Reference) {
1274 $argumentId = (string) $argument;
1275 if ($id === $argumentId) {
1279 if ($deep && !isset($visited[$argumentId]) && 'service_container' !== $argumentId) {
1280 $visited[$argumentId] = true;
1282 $service = $this->container->getDefinition($argumentId);
1284 // if the proxy manager is enabled, disable searching for references in lazy services,
1285 // as these services will be instantiated lazily and don't have direct related references.
1286 if ($service->isLazy() && !$this->getProxyDumper() instanceof NullDumper) {
1290 $arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties());
1292 if ($this->hasReference($id, $arguments, $deep, $visited)) {
1305 * @param mixed $value
1306 * @param bool $interpolate
1310 * @throws RuntimeException
1312 private function dumpValue($value, $interpolate = true)
1314 if (is_array($value)) {
1316 foreach ($value as $k => $v) {
1317 $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
1320 return sprintf('array(%s)', implode(', ', $code));
1321 } elseif ($value instanceof Definition) {
1322 if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
1323 return $this->dumpValue($this->definitionVariables->offsetGet($value), $interpolate);
1325 if ($value->getMethodCalls()) {
1326 throw new RuntimeException('Cannot dump definitions which have method calls.');
1328 if ($value->getProperties()) {
1329 throw new RuntimeException('Cannot dump definitions which have properties.');
1331 if (null !== $value->getConfigurator()) {
1332 throw new RuntimeException('Cannot dump definitions which have a configurator.');
1335 $arguments = array();
1336 foreach ($value->getArguments() as $argument) {
1337 $arguments[] = $this->dumpValue($argument);
1340 if (null !== $value->getFactory()) {
1341 $factory = $value->getFactory();
1343 if (is_string($factory)) {
1344 return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments));
1347 if (is_array($factory)) {
1348 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) {
1349 throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a'));
1352 if (is_string($factory[0])) {
1353 return sprintf('%s::%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory[0])), $factory[1], implode(', ', $arguments));
1356 if ($factory[0] instanceof Definition) {
1357 return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($factory[0]), $factory[1], count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
1360 if ($factory[0] instanceof Reference) {
1361 return sprintf('%s->%s(%s)', $this->dumpValue($factory[0]), $factory[1], implode(', ', $arguments));
1365 throw new RuntimeException('Cannot dump definition because of invalid factory');
1368 $class = $value->getClass();
1369 if (null === $class) {
1370 throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
1373 return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments));
1374 } elseif ($value instanceof Variable) {
1376 } elseif ($value instanceof Reference) {
1377 if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) {
1378 return $this->dumpValue($this->referenceVariables[$id], $interpolate);
1381 return $this->getServiceCall((string) $value, $value);
1382 } elseif ($value instanceof Expression) {
1383 return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container'));
1384 } elseif ($value instanceof Parameter) {
1385 return $this->dumpParameter($value);
1386 } elseif (true === $interpolate && is_string($value)) {
1387 if (preg_match('/^%([^%]+)%$/', $value, $match)) {
1388 // we do this to deal with non string values (Boolean, integer, ...)
1389 // the preg_replace_callback converts them to strings
1390 return $this->dumpParameter(strtolower($match[1]));
1392 $replaceParameters = function ($match) {
1393 return "'.".$this->dumpParameter(strtolower($match[2])).".'";
1396 $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value)));
1400 } elseif (is_object($value) || is_resource($value)) {
1401 throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
1404 return $this->export($value);
1408 * Dumps a string to a literal (aka PHP Code) class value.
1410 * @param string $class
1414 * @throws RuntimeException
1416 private function dumpLiteralClass($class)
1418 if (false !== strpos($class, '$')) {
1419 return sprintf('${($_ = %s) && false ?: "_"}', $class);
1421 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)) {
1422 throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s)', $class ?: 'n/a'));
1425 $class = substr(str_replace('\\\\', '\\', $class), 1, -1);
1427 return 0 === strpos($class, '\\') ? $class : '\\'.$class;
1431 * Dumps a parameter.
1433 * @param string $name
1437 private function dumpParameter($name)
1439 if ($this->container->isFrozen() && $this->container->hasParameter($name)) {
1440 return $this->dumpValue($this->container->getParameter($name), false);
1443 return sprintf("\$this->getParameter('%s')", strtolower($name));
1447 * Gets a service call.
1450 * @param Reference $reference
1454 private function getServiceCall($id, Reference $reference = null)
1456 while ($this->container->hasAlias($id)) {
1457 $id = (string) $this->container->getAlias($id);
1460 if ('service_container' === $id) {
1464 if ($this->container->hasDefinition($id) && !$this->container->getDefinition($id)->isPublic()) {
1465 // The following is PHP 5.5 syntax for what could be written as "(\$this->services['$id'] ?? \$this->{$this->generateMethodName($id)}())" on PHP>=7.0
1467 return "\${(\$_ = isset(\$this->services['$id']) ? \$this->services['$id'] : \$this->{$this->generateMethodName($id)}()) && false ?: '_'}";
1469 if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
1470 return sprintf('$this->get(\'%s\', ContainerInterface::NULL_ON_INVALID_REFERENCE)', $id);
1473 return sprintf('$this->get(\'%s\')', $id);
1477 * Initializes the method names map to avoid conflicts with the Container methods.
1479 * @param string $class the container base class
1481 private function initializeMethodNamesMap($class)
1483 $this->serviceIdToMethodNameMap = array();
1484 $this->usedMethodNames = array();
1487 $reflectionClass = new \ReflectionClass($class);
1488 foreach ($reflectionClass->getMethods() as $method) {
1489 $this->usedMethodNames[strtolower($method->getName())] = true;
1491 } catch (\ReflectionException $e) {
1496 * Convert a service id to a valid PHP method name.
1502 * @throws InvalidArgumentException
1504 private function generateMethodName($id)
1506 if (isset($this->serviceIdToMethodNameMap[$id])) {
1507 return $this->serviceIdToMethodNameMap[$id];
1510 $name = Container::camelize($id);
1511 $name = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '', $name);
1512 $methodName = 'get'.$name.'Service';
1515 while (isset($this->usedMethodNames[strtolower($methodName)])) {
1517 $methodName = 'get'.$name.$suffix.'Service';
1520 $this->serviceIdToMethodNameMap[$id] = $methodName;
1521 $this->usedMethodNames[strtolower($methodName)] = true;
1527 * Returns the next name to use.
1531 private function getNextVariableName()
1533 $firstChars = self::FIRST_CHARS;
1534 $firstCharsLength = strlen($firstChars);
1535 $nonFirstChars = self::NON_FIRST_CHARS;
1536 $nonFirstCharsLength = strlen($nonFirstChars);
1540 $i = $this->variableCount;
1543 $name .= $firstChars[$i % $firstCharsLength];
1544 $i = (int) ($i / $firstCharsLength);
1549 $name .= $nonFirstChars[$i % $nonFirstCharsLength];
1550 $i = (int) ($i / $nonFirstCharsLength);
1553 ++$this->variableCount;
1555 // check that the name is not reserved
1556 if (in_array($name, $this->reservedVariables, true)) {
1564 private function getExpressionLanguage()
1566 if (null === $this->expressionLanguage) {
1567 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
1568 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
1570 $providers = $this->container->getExpressionLanguageProviders();
1571 $this->expressionLanguage = new ExpressionLanguage(null, $providers, function ($arg) {
1572 $id = '""' === substr_replace($arg, '', 1, -1) ? stripcslashes(substr($arg, 1, -1)) : null;
1574 if (null !== $id && ($this->container->hasAlias($id) || $this->container->hasDefinition($id))) {
1575 return $this->getServiceCall($id);
1578 return sprintf('$this->get(%s)', $arg);
1581 if ($this->container->isTrackingResources()) {
1582 foreach ($providers as $provider) {
1583 $this->container->addObjectResource($provider);
1588 return $this->expressionLanguage;
1591 private function exportTargetDirs()
1593 return null === $this->targetDirRegex ? '' : <<<EOF
1596 for (\$i = 1; \$i <= {$this->targetDirMaxMatches}; ++\$i) {
1597 \$this->targetDirs[\$i] = \$dir = dirname(\$dir);
1602 private function export($value)
1604 if (null !== $this->targetDirRegex && is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) {
1605 $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1])).'.' : '';
1606 $suffix = $matches[0][1] + strlen($matches[0][0]);
1607 $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix)) : '';
1608 $dirname = '__DIR__';
1610 if (0 < $offset = 1 + $this->targetDirMaxMatches - count($matches)) {
1611 $dirname = sprintf('$this->targetDirs[%d]', $offset);
1614 if ($prefix || $suffix) {
1615 return sprintf('(%s%s%s)', $prefix, $dirname, $suffix);
1621 return $this->doExport($value);
1624 private function doExport($value)
1626 $export = var_export($value, true);
1628 if ("'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('%s').'")) {
1629 $export = $resolvedExport;
1630 if ("'" === $export[1]) {
1631 $export = substr($export, 3);
1633 if (".''" === substr($export, -3)) {
1634 $export = substr($export, 0, -3);