Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\DependencyInjection\Dumper; Chris@0: Chris@14: use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; Chris@14: use Symfony\Component\DependencyInjection\Argument\IteratorArgument; Chris@14: use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; Chris@17: use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; Chris@17: use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass; Chris@17: use Symfony\Component\DependencyInjection\Container; Chris@17: use Symfony\Component\DependencyInjection\ContainerBuilder; Chris@17: use Symfony\Component\DependencyInjection\ContainerInterface; Chris@0: use Symfony\Component\DependencyInjection\Definition; Chris@0: use Symfony\Component\DependencyInjection\Exception\EnvParameterException; Chris@0: use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; Chris@0: use Symfony\Component\DependencyInjection\Exception\RuntimeException; Chris@0: use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; Chris@17: use Symfony\Component\DependencyInjection\ExpressionLanguage; Chris@0: use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; Chris@0: use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; Chris@17: use Symfony\Component\DependencyInjection\Parameter; Chris@17: use Symfony\Component\DependencyInjection\Reference; Chris@17: use Symfony\Component\DependencyInjection\TypedReference; Chris@17: use Symfony\Component\DependencyInjection\Variable; Chris@0: use Symfony\Component\ExpressionLanguage\Expression; Chris@0: use Symfony\Component\HttpKernel\Kernel; Chris@0: Chris@0: /** Chris@0: * PhpDumper dumps a service container as a PHP class. Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: * @author Johannes M. Schmitt Chris@0: */ Chris@0: class PhpDumper extends Dumper Chris@0: { Chris@0: /** Chris@0: * Characters that might appear in the generated variable name as first character. Chris@0: */ Chris@0: const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz'; Chris@0: Chris@0: /** Chris@0: * Characters that might appear in the generated variable name as any but the first character. Chris@0: */ Chris@0: const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_'; Chris@0: Chris@0: private $definitionVariables; Chris@0: private $referenceVariables; Chris@0: private $variableCount; Chris@17: private $inlinedDefinitions; Chris@17: private $serviceCalls; Chris@17: private $reservedVariables = ['instance', 'class', 'this']; Chris@0: private $expressionLanguage; Chris@0: private $targetDirRegex; Chris@0: private $targetDirMaxMatches; Chris@0: private $docStar; Chris@0: private $serviceIdToMethodNameMap; Chris@0: private $usedMethodNames; Chris@14: private $namespace; Chris@14: private $asFiles; Chris@14: private $hotPathTag; Chris@14: private $inlineRequires; Chris@17: private $inlinedRequires = []; Chris@17: private $circularReferences = []; Chris@0: Chris@0: /** Chris@14: * @var ProxyDumper Chris@0: */ Chris@0: private $proxyDumper; Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function __construct(ContainerBuilder $container) Chris@0: { Chris@14: if (!$container->isCompiled()) { Chris@14: @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); Chris@14: } Chris@14: Chris@0: parent::__construct($container); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the dumper to be used when dumping proxies in the generated container. Chris@0: */ Chris@0: public function setProxyDumper(ProxyDumper $proxyDumper) Chris@0: { Chris@0: $this->proxyDumper = $proxyDumper; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Dumps the service container as a PHP class. Chris@0: * Chris@0: * Available options: Chris@0: * Chris@0: * * class: The class name Chris@0: * * base_class: The base class name Chris@0: * * namespace: The class namespace Chris@14: * * as_files: To split the container in several files Chris@0: * Chris@14: * @return string|array A PHP class representing the service container or an array of PHP files if the "as_files" option is set Chris@0: * Chris@0: * @throws EnvParameterException When an env var exists but has not been dumped Chris@0: */ Chris@17: public function dump(array $options = []) Chris@0: { Chris@0: $this->targetDirRegex = null; Chris@17: $this->inlinedRequires = []; Chris@17: $options = array_merge([ Chris@0: 'class' => 'ProjectServiceContainer', Chris@0: 'base_class' => 'Container', Chris@0: 'namespace' => '', Chris@14: 'as_files' => false, Chris@0: 'debug' => true, Chris@14: 'hot_path_tag' => 'container.hot_path', Chris@14: 'inline_class_loader_parameter' => 'container.dumper.inline_class_loader', Chris@14: 'build_time' => time(), Chris@17: ], $options); Chris@0: Chris@14: $this->namespace = $options['namespace']; Chris@14: $this->asFiles = $options['as_files']; Chris@14: $this->hotPathTag = $options['hot_path_tag']; Chris@14: $this->inlineRequires = $options['inline_class_loader_parameter'] && $this->container->hasParameter($options['inline_class_loader_parameter']) && $this->container->getParameter($options['inline_class_loader_parameter']); Chris@14: Chris@14: if (0 !== strpos($baseClass = $options['base_class'], '\\') && 'Container' !== $baseClass) { Chris@14: $baseClass = sprintf('%s\%s', $options['namespace'] ? '\\'.$options['namespace'] : '', $baseClass); Chris@14: $baseClassWithNamespace = $baseClass; Chris@14: } elseif ('Container' === $baseClass) { Chris@14: $baseClassWithNamespace = Container::class; Chris@14: } else { Chris@14: $baseClassWithNamespace = $baseClass; Chris@14: } Chris@14: Chris@14: $this->initializeMethodNamesMap('Container' === $baseClass ? Container::class : $baseClass); Chris@14: Chris@17: if ($this->getProxyDumper() instanceof NullDumper) { Chris@17: (new AnalyzeServiceReferencesPass(true, false))->process($this->container); Chris@17: try { Chris@17: (new CheckCircularReferencesPass())->process($this->container); Chris@17: } catch (ServiceCircularReferenceException $e) { Chris@17: $path = $e->getPath(); Chris@17: end($path); Chris@17: $path[key($path)] .= '". Try running "composer require symfony/proxy-manager-bridge'; Chris@17: Chris@17: throw new ServiceCircularReferenceException($e->getServiceId(), $path); Chris@17: } Chris@17: } Chris@17: Chris@17: (new AnalyzeServiceReferencesPass(false, !$this->getProxyDumper() instanceof NullDumper))->process($this->container); Chris@17: $checkedNodes = []; Chris@17: $this->circularReferences = []; Chris@14: foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) { Chris@17: if (!$node->getValue() instanceof Definition) { Chris@17: continue; Chris@17: } Chris@17: if (!isset($checkedNodes[$id])) { Chris@17: $this->analyzeCircularReferences($id, $node->getOutEdges(), $checkedNodes); Chris@17: } Chris@14: } Chris@14: $this->container->getCompiler()->getServiceReferenceGraph()->clear(); Chris@17: $checkedNodes = []; Chris@0: Chris@0: $this->docStar = $options['debug'] ? '*' : ''; Chris@0: Chris@17: if (!empty($options['file']) && is_dir($dir = \dirname($options['file']))) { Chris@0: // Build a regexp where the first root dirs are mandatory, Chris@0: // but every other sub-dir is optional up to the full path in $dir Chris@0: // Mandate at least 2 root dirs and not more that 5 optional dirs. Chris@0: Chris@17: $dir = explode(\DIRECTORY_SEPARATOR, realpath($dir)); Chris@17: $i = \count($dir); Chris@0: Chris@0: if (3 <= $i) { Chris@0: $regex = ''; Chris@0: $lastOptionalDir = $i > 8 ? $i - 5 : 3; Chris@0: $this->targetDirMaxMatches = $i - $lastOptionalDir; Chris@0: Chris@0: while (--$i >= $lastOptionalDir) { Chris@17: $regex = sprintf('(%s%s)?', preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex); Chris@0: } Chris@0: Chris@0: do { Chris@17: $regex = preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#').$regex; Chris@0: } while (0 < --$i); Chris@0: Chris@0: $this->targetDirRegex = '#'.preg_quote($dir[0], '#').$regex.'#'; Chris@0: } Chris@0: } Chris@0: Chris@14: $code = Chris@14: $this->startClass($options['class'], $baseClass, $baseClassWithNamespace). Chris@14: $this->addServices(). Chris@14: $this->addDefaultParametersMethod(). Chris@14: $this->endClass() Chris@14: ; Chris@0: Chris@14: if ($this->asFiles) { Chris@14: $fileStart = <<container->getRemovedIds())) { Chris@14: sort($ids); Chris@17: $c = "doExport($id)." => true,\n"; Chris@14: } Chris@17: $files['removed-ids.php'] = $c .= "];\n"; Chris@14: } Chris@14: Chris@14: foreach ($this->generateServiceFiles() as $file => $c) { Chris@14: $files[$file] = $fileStart.$c; Chris@14: } Chris@14: foreach ($this->generateProxyClasses() as $file => $c) { Chris@14: $files[$file] = " $c) { Chris@14: $code["Container{$hash}/{$file}"] = $c; Chris@14: } Chris@14: array_pop($code); Chris@14: $code["Container{$hash}/{$options['class']}.php"] = substr_replace($files[$options['class'].'.php'], "namespace ? "\nnamespace {$this->namespace};\n" : ''; Chris@14: $time = $options['build_time']; Chris@14: $id = hash('crc32', $hash.$time); Chris@14: Chris@14: $code[$options['class'].'.php'] = << '$hash', Chris@14: 'container.build_id' => '$id', Chris@14: 'container.build_time' => $time, Chris@17: ], __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}'); Chris@14: Chris@14: EOF; Chris@0: } else { Chris@14: foreach ($this->generateProxyClasses() as $c) { Chris@14: $code .= $c; Chris@14: } Chris@0: } Chris@0: Chris@0: $this->targetDirRegex = null; Chris@17: $this->inlinedRequires = []; Chris@17: $this->circularReferences = []; Chris@0: Chris@17: $unusedEnvs = []; Chris@0: foreach ($this->container->getEnvCounters() as $env => $use) { Chris@0: if (!$use) { Chris@0: $unusedEnvs[] = $env; Chris@0: } Chris@0: } Chris@0: if ($unusedEnvs) { Chris@12: throw new EnvParameterException($unusedEnvs, null, 'Environment variables "%s" are never used. Please, check your container\'s configuration.'); Chris@0: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Retrieves the currently set proxy dumper or instantiates one. Chris@0: * Chris@0: * @return ProxyDumper Chris@0: */ Chris@0: private function getProxyDumper() Chris@0: { Chris@0: if (!$this->proxyDumper) { Chris@0: $this->proxyDumper = new NullDumper(); Chris@0: } Chris@0: Chris@0: return $this->proxyDumper; Chris@0: } Chris@0: Chris@17: private function analyzeCircularReferences($sourceId, array $edges, &$checkedNodes, &$currentPath = []) Chris@0: { Chris@17: $checkedNodes[$sourceId] = true; Chris@17: $currentPath[$sourceId] = $sourceId; Chris@0: Chris@14: foreach ($edges as $edge) { Chris@14: $node = $edge->getDestNode(); Chris@14: $id = $node->getId(); Chris@14: Chris@17: if (!$node->getValue() instanceof Definition || $sourceId === $id || $edge->isLazy() || $edge->isWeak()) { Chris@14: // no-op Chris@14: } elseif (isset($currentPath[$id])) { Chris@17: $currentId = $id; Chris@14: foreach (array_reverse($currentPath) as $parentId) { Chris@17: $this->circularReferences[$parentId][$currentId] = $currentId; Chris@17: if ($parentId === $id) { Chris@17: break; Chris@17: } Chris@17: $currentId = $parentId; Chris@14: } Chris@14: } elseif (!isset($checkedNodes[$id])) { Chris@17: $this->analyzeCircularReferences($id, $node->getOutEdges(), $checkedNodes, $currentPath); Chris@17: } elseif (isset($this->circularReferences[$id])) { Chris@17: $this->connectCircularReferences($id, $currentPath); Chris@14: } Chris@14: } Chris@17: unset($currentPath[$sourceId]); Chris@17: } Chris@17: Chris@17: private function connectCircularReferences($sourceId, &$currentPath, &$subPath = []) Chris@17: { Chris@17: $subPath[$sourceId] = $sourceId; Chris@17: $currentPath[$sourceId] = $sourceId; Chris@17: Chris@17: foreach ($this->circularReferences[$sourceId] as $id) { Chris@17: if (isset($currentPath[$id])) { Chris@17: $currentId = $id; Chris@17: foreach (array_reverse($currentPath) as $parentId) { Chris@17: $this->circularReferences[$parentId][$currentId] = $currentId; Chris@17: if ($parentId === $id) { Chris@17: break; Chris@17: } Chris@17: $currentId = $parentId; Chris@17: } Chris@17: } elseif (!isset($subPath[$id]) && isset($this->circularReferences[$id])) { Chris@17: $this->connectCircularReferences($id, $currentPath, $subPath); Chris@17: } Chris@17: } Chris@17: unset($currentPath[$sourceId]); Chris@17: unset($subPath[$sourceId]); Chris@14: } Chris@14: Chris@14: private function collectLineage($class, array &$lineage) Chris@14: { Chris@14: if (isset($lineage[$class])) { Chris@14: return; Chris@14: } Chris@14: if (!$r = $this->container->getReflectionClass($class, false)) { Chris@14: return; Chris@14: } Chris@14: if ($this->container instanceof $class) { Chris@14: return; Chris@14: } Chris@14: $file = $r->getFileName(); Chris@14: if (!$file || $this->doExport($file) === $exportedFile = $this->export($file)) { Chris@14: return; Chris@14: } Chris@14: Chris@14: if ($parent = $r->getParentClass()) { Chris@14: $this->collectLineage($parent->name, $lineage); Chris@14: } Chris@14: Chris@14: foreach ($r->getInterfaces() as $parent) { Chris@14: $this->collectLineage($parent->name, $lineage); Chris@14: } Chris@14: Chris@14: foreach ($r->getTraits() as $parent) { Chris@14: $this->collectLineage($parent->name, $lineage); Chris@14: } Chris@14: Chris@14: $lineage[$class] = substr($exportedFile, 1, -1); Chris@14: } Chris@14: Chris@14: private function generateProxyClasses() Chris@14: { Chris@17: $alreadyGenerated = []; Chris@14: $definitions = $this->container->getDefinitions(); Chris@0: $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments'); Chris@14: $proxyDumper = $this->getProxyDumper(); Chris@14: ksort($definitions); Chris@0: foreach ($definitions as $definition) { Chris@14: if (!$proxyDumper->isProxyCandidate($definition)) { Chris@14: continue; Chris@14: } Chris@16: if (isset($alreadyGenerated[$class = $definition->getClass()])) { Chris@16: continue; Chris@16: } Chris@16: $alreadyGenerated[$class] = true; Chris@14: // register class' reflector for resource tracking Chris@16: $this->container->getReflectionClass($class); Chris@17: if ("\n" === $proxyCode = "\n".$proxyDumper->getProxyCode($definition)) { Chris@17: continue; Chris@17: } Chris@0: if ($strip) { Chris@0: $proxyCode = " $proxyCode; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates the require_once statement for service includes. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@17: private function addServiceInclude($cId, Definition $definition) Chris@0: { Chris@0: $code = ''; Chris@0: Chris@14: if ($this->inlineRequires && !$this->isHotPath($definition)) { Chris@17: $lineage = []; Chris@17: foreach ($this->inlinedDefinitions as $def) { Chris@17: if (!$def->isDeprecated() && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) { Chris@14: $this->collectLineage($class, $lineage); Chris@14: } Chris@14: } Chris@14: Chris@17: foreach ($this->serviceCalls as $id => list($callCount, $behavior)) { Chris@14: if ('service_container' !== $id && $id !== $cId Chris@17: && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior Chris@14: && $this->container->has($id) Chris@14: && $this->isTrivialInstance($def = $this->container->findDefinition($id)) Chris@17: && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass()) Chris@14: ) { Chris@14: $this->collectLineage($class, $lineage); Chris@14: } Chris@14: } Chris@14: Chris@14: foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) { Chris@14: $code .= sprintf(" include_once %s;\n", $file); Chris@14: } Chris@0: } Chris@0: Chris@17: foreach ($this->inlinedDefinitions as $def) { Chris@14: if ($file = $def->getFile()) { Chris@14: $code .= sprintf(" include_once %s;\n", $this->dumpValue($file)); Chris@0: } Chris@0: } Chris@0: Chris@0: if ('' !== $code) { Chris@0: $code .= "\n"; Chris@0: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates the service instance. Chris@0: * Chris@0: * @param string $id Chris@0: * @param Definition $definition Chris@14: * @param bool $isSimpleInstance Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: * @throws RuntimeException Chris@0: */ Chris@14: private function addServiceInstance($id, Definition $definition, $isSimpleInstance) Chris@0: { Chris@12: $class = $this->dumpValue($definition->getClass()); Chris@0: Chris@12: 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)) { Chris@0: throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id)); Chris@0: } Chris@0: Chris@0: $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); Chris@0: $instantiation = ''; Chris@0: Chris@0: if (!$isProxyCandidate && $definition->isShared()) { Chris@18: $instantiation = sprintf('$this->services[%s] = %s', $this->doExport($id), $isSimpleInstance ? '' : '$instance'); Chris@14: } elseif (!$isSimpleInstance) { Chris@0: $instantiation = '$instance'; Chris@0: } Chris@0: Chris@0: $return = ''; Chris@14: if ($isSimpleInstance) { Chris@0: $return = 'return '; Chris@0: } else { Chris@0: $instantiation .= ' = '; Chris@0: } Chris@0: Chris@17: return $this->addNewInstance($definition, $return, $instantiation, $id); Chris@0: } Chris@0: Chris@0: /** Chris@14: * Checks if the definition is a trivial instance. Chris@0: * Chris@0: * @param Definition $definition Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@14: private function isTrivialInstance(Definition $definition) Chris@0: { Chris@14: if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) { Chris@14: return false; Chris@14: } Chris@17: if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < \count($definition->getArguments())) { Chris@14: return false; Chris@14: } Chris@14: Chris@14: foreach ($definition->getArguments() as $arg) { Chris@14: if (!$arg || $arg instanceof Parameter) { Chris@0: continue; Chris@0: } Chris@17: if (\is_array($arg) && 3 >= \count($arg)) { Chris@14: foreach ($arg as $k => $v) { Chris@14: if ($this->dumpValue($k) !== $this->dumpValue($k, false)) { Chris@14: return false; Chris@14: } Chris@14: if (!$v || $v instanceof Parameter) { Chris@14: continue; Chris@14: } Chris@14: if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) { Chris@14: continue; Chris@14: } Chris@14: if (!is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($v, false)) { Chris@14: return false; Chris@14: } Chris@14: } Chris@14: } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) { Chris@14: continue; Chris@14: } elseif (!is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($arg, false)) { Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds method calls to a service definition. Chris@0: * Chris@0: * @param Definition $definition Chris@0: * @param string $variableName Chris@0: * Chris@0: * @return string Chris@0: */ Chris@12: private function addServiceMethodCalls(Definition $definition, $variableName = 'instance') Chris@0: { Chris@0: $calls = ''; Chris@0: foreach ($definition->getMethodCalls() as $call) { Chris@17: $arguments = []; Chris@0: foreach ($call[1] as $value) { Chris@0: $arguments[] = $this->dumpValue($value); Chris@0: } Chris@0: Chris@0: $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments))); Chris@0: } Chris@0: Chris@0: return $calls; Chris@0: } Chris@0: Chris@12: private function addServiceProperties(Definition $definition, $variableName = 'instance') Chris@0: { Chris@0: $code = ''; Chris@0: foreach ($definition->getProperties() as $name => $value) { Chris@0: $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value)); Chris@0: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds configurator definition. Chris@0: * Chris@0: * @param Definition $definition Chris@0: * @param string $variableName Chris@0: * Chris@0: * @return string Chris@0: */ Chris@12: private function addServiceConfigurator(Definition $definition, $variableName = 'instance') Chris@0: { Chris@0: if (!$callable = $definition->getConfigurator()) { Chris@0: return ''; Chris@0: } Chris@0: Chris@17: if (\is_array($callable)) { Chris@0: if ($callable[0] instanceof Reference Chris@17: || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0])) Chris@17: ) { Chris@0: return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); Chris@0: } Chris@0: Chris@0: $class = $this->dumpValue($callable[0]); Chris@0: // If the class is a string we can optimize call_user_func away Chris@0: if (0 === strpos($class, "'") && false === strpos($class, '$')) { Chris@0: return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName); Chris@0: } Chris@0: Chris@0: if (0 === strpos($class, 'new ')) { Chris@0: return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); Chris@0: } Chris@0: Chris@17: return sprintf(" \\call_user_func([%s, '%s'], \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); Chris@0: } Chris@0: Chris@0: return sprintf(" %s(\$%s);\n", $callable, $variableName); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds a service. Chris@0: * Chris@0: * @param string $id Chris@0: * @param Definition $definition Chris@14: * @param string &$file Chris@0: * Chris@0: * @return string Chris@0: */ Chris@14: private function addService($id, Definition $definition, &$file = null) Chris@0: { Chris@0: $this->definitionVariables = new \SplObjectStorage(); Chris@17: $this->referenceVariables = []; Chris@0: $this->variableCount = 0; Chris@17: $this->referenceVariables[$id] = new Variable('instance'); Chris@0: Chris@17: $return = []; Chris@0: Chris@14: if ($class = $definition->getClass()) { Chris@17: $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class); Chris@12: $return[] = sprintf(0 === strpos($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\')); Chris@0: } elseif ($definition->getFactory()) { Chris@0: $factory = $definition->getFactory(); Chris@17: if (\is_string($factory)) { Chris@0: $return[] = sprintf('@return object An instance returned by %s()', $factory); Chris@17: } elseif (\is_array($factory) && (\is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) { Chris@17: $class = $factory[0] instanceof Definition ? $factory[0]->getClass() : (string) $factory[0]; Chris@17: $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class); Chris@17: $return[] = sprintf('@return object An instance returned by %s::%s()', $class, $factory[1]); Chris@0: } Chris@0: } Chris@0: Chris@0: if ($definition->isDeprecated()) { Chris@17: if ($return && 0 === strpos($return[\count($return) - 1], '@return')) { Chris@0: $return[] = ''; Chris@0: } Chris@0: Chris@0: $return[] = sprintf('@deprecated %s', $definition->getDeprecationMessage($id)); Chris@0: } Chris@0: Chris@0: $return = str_replace("\n * \n", "\n *\n", implode("\n * ", $return)); Chris@0: $return = $this->container->resolveEnvPlaceholders($return); Chris@0: Chris@12: $shared = $definition->isShared() ? ' shared' : ''; Chris@12: $public = $definition->isPublic() ? 'public' : 'private'; Chris@12: $autowired = $definition->isAutowired() ? ' autowired' : ''; Chris@0: Chris@0: if ($definition->isLazy()) { Chris@17: unset($this->circularReferences[$id]); Chris@0: $lazyInitialization = '$lazyLoad = true'; Chris@0: } else { Chris@0: $lazyInitialization = ''; Chris@0: } Chris@0: Chris@14: $asFile = $this->asFiles && $definition->isShared() && !$this->isHotPath($definition); Chris@0: $methodName = $this->generateMethodName($id); Chris@14: if ($asFile) { Chris@14: $file = $methodName.'.php'; Chris@14: $code = " // Returns the $public '$id'$shared$autowired service.\n\n"; Chris@14: } else { Chris@14: $code = <<docStar} Chris@12: * Gets the $public '$id'$shared$autowired service. Chris@12: * Chris@0: * $return Chris@18: EOF; Chris@18: $code = str_replace('*/', ' ', $code).<<serviceCalls = []; Chris@17: $this->inlinedDefinitions = $this->getDefinitionsFromArguments([$definition], null, $this->serviceCalls); Chris@17: Chris@17: $code .= $this->addServiceInclude($id, $definition); Chris@17: Chris@14: if ($this->getProxyDumper()->isProxyCandidate($definition)) { Chris@14: $factoryCode = $asFile ? "\$this->load('%s.php', false)" : '$this->%s(false)'; Chris@18: $code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName, $this->doExport($id))); Chris@14: } Chris@0: Chris@14: if ($definition->isDeprecated()) { Chris@14: $code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id))); Chris@14: } Chris@14: Chris@17: $code .= $this->addInlineService($id, $definition); Chris@14: Chris@14: if ($asFile) { Chris@14: $code = implode("\n", array_map(function ($line) { return $line ? substr($line, 8) : $line; }, explode("\n", $code))); Chris@0: } else { Chris@14: $code .= " }\n"; Chris@0: } Chris@0: Chris@17: $this->definitionVariables = $this->inlinedDefinitions = null; Chris@17: $this->referenceVariables = $this->serviceCalls = null; Chris@17: Chris@17: return $code; Chris@17: } Chris@17: Chris@17: private function addInlineVariables($id, Definition $definition, array $arguments, $forConstructor) Chris@17: { Chris@17: $code = ''; Chris@17: Chris@17: foreach ($arguments as $argument) { Chris@17: if (\is_array($argument)) { Chris@17: $code .= $this->addInlineVariables($id, $definition, $argument, $forConstructor); Chris@17: } elseif ($argument instanceof Reference) { Chris@17: $code .= $this->addInlineReference($id, $definition, $this->container->normalizeId($argument), $forConstructor); Chris@17: } elseif ($argument instanceof Definition) { Chris@17: $code .= $this->addInlineService($id, $definition, $argument, $forConstructor); Chris@17: } Chris@17: } Chris@17: Chris@17: return $code; Chris@17: } Chris@17: Chris@17: private function addInlineReference($id, Definition $definition, $targetId, $forConstructor) Chris@17: { Chris@17: list($callCount, $behavior) = $this->serviceCalls[$targetId]; Chris@17: Chris@17: while ($this->container->hasAlias($targetId)) { Chris@17: $targetId = (string) $this->container->getAlias($targetId); Chris@17: } Chris@17: Chris@17: if ($id === $targetId) { Chris@17: return $this->addInlineService($id, $definition, $definition); Chris@17: } Chris@17: Chris@17: if ('service_container' === $targetId || isset($this->referenceVariables[$targetId])) { Chris@17: return ''; Chris@17: } Chris@17: Chris@17: $hasSelfRef = isset($this->circularReferences[$id][$targetId]); Chris@17: $forConstructor = $forConstructor && !isset($this->definitionVariables[$definition]); Chris@17: $code = $hasSelfRef && !$forConstructor ? $this->addInlineService($id, $definition, $definition) : ''; Chris@17: Chris@17: if (isset($this->referenceVariables[$targetId]) || (2 > $callCount && (!$hasSelfRef || !$forConstructor))) { Chris@17: return $code; Chris@17: } Chris@17: Chris@17: $name = $this->getNextVariableName(); Chris@17: $this->referenceVariables[$targetId] = new Variable($name); Chris@17: Chris@17: $reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $behavior ? new Reference($targetId, $behavior) : null; Chris@17: $code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($targetId, $reference)); Chris@17: Chris@17: if (!$hasSelfRef || !$forConstructor) { Chris@17: return $code; Chris@17: } Chris@17: Chris@17: $code .= sprintf(<<<'EOTXT' Chris@17: Chris@18: if (isset($this->%s[%s])) { Chris@18: return $this->%1$s[%2$s]; Chris@17: } Chris@17: Chris@17: EOTXT Chris@17: , Chris@17: 'services', Chris@18: $this->doExport($id) Chris@17: ); Chris@17: Chris@17: return $code; Chris@17: } Chris@17: Chris@17: private function addInlineService($id, Definition $definition, Definition $inlineDef = null, $forConstructor = true) Chris@17: { Chris@17: $isSimpleInstance = $isRootInstance = null === $inlineDef; Chris@17: Chris@17: if (isset($this->definitionVariables[$inlineDef = $inlineDef ?: $definition])) { Chris@17: return ''; Chris@17: } Chris@17: Chris@17: $arguments = [$inlineDef->getArguments(), $inlineDef->getFactory()]; Chris@17: Chris@17: $code = $this->addInlineVariables($id, $definition, $arguments, $forConstructor); Chris@17: Chris@17: if ($arguments = array_filter([$inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()])) { Chris@17: $isSimpleInstance = false; Chris@17: } elseif ($definition !== $inlineDef && 2 > $this->inlinedDefinitions[$inlineDef]) { Chris@17: return $code; Chris@17: } Chris@17: Chris@17: if (isset($this->definitionVariables[$inlineDef])) { Chris@17: $isSimpleInstance = false; Chris@17: } else { Chris@17: $name = $definition === $inlineDef ? 'instance' : $this->getNextVariableName(); Chris@17: $this->definitionVariables[$inlineDef] = new Variable($name); Chris@17: $code .= '' !== $code ? "\n" : ''; Chris@17: Chris@17: if ('instance' === $name) { Chris@17: $code .= $this->addServiceInstance($id, $definition, $isSimpleInstance); Chris@17: } else { Chris@17: $code .= $this->addNewInstance($inlineDef, '$'.$name, ' = ', $id); Chris@17: } Chris@17: Chris@17: if ('' !== $inline = $this->addInlineVariables($id, $definition, $arguments, false)) { Chris@17: $code .= "\n".$inline."\n"; Chris@17: } elseif ($arguments && 'instance' === $name) { Chris@17: $code .= "\n"; Chris@17: } Chris@17: Chris@17: $code .= $this->addServiceProperties($inlineDef, $name); Chris@17: $code .= $this->addServiceMethodCalls($inlineDef, $name); Chris@17: $code .= $this->addServiceConfigurator($inlineDef, $name); Chris@17: } Chris@17: Chris@17: if ($isRootInstance && !$isSimpleInstance) { Chris@17: $code .= "\n return \$instance;\n"; Chris@17: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds multiple services. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addServices() Chris@0: { Chris@0: $publicServices = $privateServices = ''; Chris@0: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@14: if ($definition->isSynthetic() || ($this->asFiles && $definition->isShared() && !$this->isHotPath($definition))) { Chris@14: continue; Chris@14: } Chris@0: if ($definition->isPublic()) { Chris@0: $publicServices .= $this->addService($id, $definition); Chris@0: } else { Chris@0: $privateServices .= $this->addService($id, $definition); Chris@0: } Chris@0: } Chris@0: Chris@0: return $publicServices.$privateServices; Chris@0: } Chris@0: Chris@14: private function generateServiceFiles() Chris@14: { Chris@14: $definitions = $this->container->getDefinitions(); Chris@14: ksort($definitions); Chris@14: foreach ($definitions as $id => $definition) { Chris@14: if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) { Chris@14: $code = $this->addService($id, $definition, $file); Chris@14: yield $file => $code; Chris@14: } Chris@14: } Chris@14: } Chris@14: Chris@0: private function addNewInstance(Definition $definition, $return, $instantiation, $id) Chris@0: { Chris@0: $class = $this->dumpValue($definition->getClass()); Chris@14: $return = ' '.$return.$instantiation; Chris@0: Chris@17: $arguments = []; Chris@0: foreach ($definition->getArguments() as $value) { Chris@0: $arguments[] = $this->dumpValue($value); Chris@0: } Chris@0: Chris@0: if (null !== $definition->getFactory()) { Chris@0: $callable = $definition->getFactory(); Chris@17: if (\is_array($callable)) { Chris@0: if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) { Chris@0: throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $callable[1] ?: 'n/a')); Chris@0: } Chris@0: Chris@0: if ($callable[0] instanceof Reference Chris@0: || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { Chris@14: return $return.sprintf("%s->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: $class = $this->dumpValue($callable[0]); Chris@0: // If the class is a string we can optimize call_user_func away Chris@0: if (0 === strpos($class, "'") && false === strpos($class, '$')) { Chris@0: if ("''" === $class) { Chris@0: 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)); Chris@0: } Chris@0: Chris@14: return $return.sprintf("%s::%s(%s);\n", $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: if (0 === strpos($class, 'new ')) { Chris@14: return $return.sprintf("(%s)->%s(%s);\n", $class, $callable[1], $arguments ? implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@17: return $return.sprintf("\\call_user_func([%s, '%s']%s);\n", $class, $callable[1], $arguments ? ', '.implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@14: return $return.sprintf("%s(%s);\n", $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: if (false !== strpos($class, '$')) { Chris@14: return sprintf(" \$class = %s;\n\n%snew \$class(%s);\n", $class, $return, implode(', ', $arguments)); Chris@0: } Chris@0: Chris@14: return $return.sprintf("new %s(%s);\n", $this->dumpLiteralClass($class), implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the class headers. Chris@0: * Chris@14: * @param string $class Class name Chris@14: * @param string $baseClass The name of the base class Chris@14: * @param string $baseClassWithNamespace Fully qualified base class name Chris@0: * Chris@0: * @return string Chris@0: */ Chris@14: private function startClass($class, $baseClass, $baseClassWithNamespace) Chris@0: { Chris@14: $bagClass = $this->container->isCompiled() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;'; Chris@14: $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; Chris@0: Chris@14: $code = <<docStar} Chris@0: * This class has been auto-generated Chris@0: * by the Symfony Dependency Injection Component. Chris@14: * Chris@14: * @final since Symfony 3.3 Chris@0: */ Chris@0: class $class extends $baseClass Chris@0: { Chris@0: private \$parameters; Chris@17: private \$targetDirs = []; Chris@0: Chris@14: public function __construct() Chris@0: { Chris@0: Chris@0: EOF; Chris@14: if (null !== $this->targetDirRegex) { Chris@14: $dir = $this->asFiles ? '$this->targetDirs[0] = \\dirname($containerDir)' : '__DIR__'; Chris@14: $code .= <<targetDirMaxMatches}; ++\$i) { Chris@14: \$this->targetDirs[\$i] = \$dir = \\dirname(\$dir); Chris@14: } Chris@0: Chris@14: EOF; Chris@14: } Chris@14: if ($this->asFiles) { Chris@14: $code = str_replace('$parameters', "\$buildParameters;\n private \$containerDir;\n private \$parameters", $code); Chris@17: $code = str_replace('__construct()', '__construct(array $buildParameters = [], $containerDir = __DIR__)', $code); Chris@14: $code .= " \$this->buildParameters = \$buildParameters;\n"; Chris@14: $code .= " \$this->containerDir = \$containerDir;\n"; Chris@14: } Chris@14: Chris@14: if ($this->container->isCompiled()) { Chris@14: if (Container::class !== $baseClassWithNamespace) { Chris@14: $r = $this->container->getReflectionClass($baseClassWithNamespace, false); Chris@14: if (null !== $r Chris@14: && (null !== $constructor = $r->getConstructor()) Chris@14: && 0 === $constructor->getNumberOfRequiredParameters() Chris@14: && Container::class !== $constructor->getDeclaringClass()->name Chris@14: ) { Chris@14: $code .= " parent::__construct();\n"; Chris@14: $code .= " \$this->parameterBag = null;\n\n"; Chris@14: } Chris@14: } Chris@14: Chris@14: if ($this->container->getParameterBag()->all()) { Chris@14: $code .= " \$this->parameters = \$this->getDefaultParameters();\n\n"; Chris@14: } Chris@14: Chris@17: $code .= " \$this->services = [];\n"; Chris@14: } else { Chris@14: $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null; Chris@14: $code .= " parent::__construct($arguments);\n"; Chris@14: } Chris@14: Chris@14: $code .= $this->addNormalizedIds(); Chris@14: $code .= $this->addSyntheticIds(); Chris@0: $code .= $this->addMethodMap(); Chris@14: $code .= $this->asFiles ? $this->addFileMap() : ''; Chris@0: $code .= $this->addPrivateServices(); Chris@0: $code .= $this->addAliases(); Chris@14: $code .= $this->addInlineRequires(); Chris@0: $code .= <<<'EOF' Chris@0: } Chris@0: Chris@0: EOF; Chris@14: $code .= $this->addRemovedIds(); Chris@14: Chris@14: if ($this->container->isCompiled()) { Chris@14: $code .= <<asFiles) { Chris@14: $code .= <<containerDir.\\DIRECTORY_SEPARATOR.\$file; Chris@14: } Chris@14: Chris@14: EOF; Chris@14: } Chris@14: Chris@14: $proxyDumper = $this->getProxyDumper(); Chris@14: foreach ($this->container->getDefinitions() as $definition) { Chris@14: if (!$proxyDumper->isProxyCandidate($definition)) { Chris@14: continue; Chris@14: } Chris@14: if ($this->asFiles) { Chris@14: $proxyLoader = '$this->load("{$class}.php")'; Chris@14: } elseif ($this->namespace) { Chris@14: $proxyLoader = 'class_alias("'.$this->namespace.'\\\\{$class}", $class, false)'; Chris@14: } else { Chris@14: $proxyLoader = ''; Chris@14: } Chris@14: if ($proxyLoader) { Chris@14: $proxyLoader = "class_exists(\$class, false) || {$proxyLoader};\n\n "; Chris@14: } Chris@14: $code .= <<container->getNormalizedIds(); Chris@14: ksort($normalizedIds); Chris@14: foreach ($normalizedIds as $id => $normalizedId) { Chris@14: if ($this->container->has($normalizedId)) { Chris@14: $code .= ' '.$this->doExport($id).' => '.$this->doExport($normalizedId).",\n"; Chris@14: } Chris@0: } Chris@0: Chris@17: return $code ? " \$this->normalizedIds = [\n".$code." ];\n" : ''; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Adds the syntheticIds definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@14: private function addSyntheticIds() Chris@0: { Chris@14: $code = ''; Chris@14: $definitions = $this->container->getDefinitions(); Chris@14: ksort($definitions); Chris@14: foreach ($definitions as $id => $definition) { Chris@14: if ($definition->isSynthetic() && 'service_container' !== $id) { Chris@14: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@14: } Chris@14: } Chris@0: Chris@17: return $code ? " \$this->syntheticIds = [\n{$code} ];\n" : ''; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Adds the removedIds definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@14: private function addRemovedIds() Chris@0: { Chris@14: if (!$ids = $this->container->getRemovedIds()) { Chris@14: return ''; Chris@14: } Chris@14: if ($this->asFiles) { Chris@14: $code = "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'"; Chris@14: } else { Chris@14: $code = ''; Chris@14: $ids = array_keys($ids); Chris@14: sort($ids); Chris@14: foreach ($ids as $id) { Chris@17: if (preg_match('/^\d+_[^~]++~[._a-zA-Z\d]{7}$/', $id)) { Chris@17: continue; Chris@17: } Chris@14: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@14: } Chris@14: Chris@17: $code = "[\n{$code} ]"; Chris@14: } Chris@14: Chris@0: return <<container->getDefinitions(); Chris@14: ksort($definitions); Chris@14: foreach ($definitions as $id => $definition) { Chris@14: if (!$definition->isSynthetic() && (!$this->asFiles || !$definition->isShared() || $this->isHotPath($definition))) { Chris@14: $code .= ' '.$this->doExport($id).' => '.$this->doExport($this->generateMethodName($id)).",\n"; Chris@14: } Chris@0: } Chris@0: Chris@17: return $code ? " \$this->methodMap = [\n{$code} ];\n" : ''; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Adds the fileMap property definition. Chris@14: * Chris@14: * @return string Chris@14: */ Chris@14: private function addFileMap() Chris@14: { Chris@14: $code = ''; Chris@14: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@14: if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) { Chris@14: $code .= sprintf(" %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id)); Chris@14: } Chris@0: } Chris@0: Chris@17: return $code ? " \$this->fileMap = [\n{$code} ];\n" : ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the privates property definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addPrivateServices() Chris@0: { Chris@14: $code = ''; Chris@14: Chris@14: $aliases = $this->container->getAliases(); Chris@14: ksort($aliases); Chris@14: foreach ($aliases as $id => $alias) { Chris@14: if ($alias->isPrivate()) { Chris@14: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@14: } Chris@0: } Chris@0: Chris@14: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if (!$definition->isPublic()) { Chris@14: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: if (empty($code)) { Chris@0: return ''; Chris@0: } Chris@0: Chris@17: $out = " \$this->privates = [\n"; Chris@0: $out .= $code; Chris@17: $out .= " ];\n"; Chris@0: Chris@0: return $out; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the aliases property definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addAliases() Chris@0: { Chris@0: if (!$aliases = $this->container->getAliases()) { Chris@17: return $this->container->isCompiled() ? "\n \$this->aliases = [];\n" : ''; Chris@0: } Chris@0: Chris@17: $code = " \$this->aliases = [\n"; Chris@0: ksort($aliases); Chris@0: foreach ($aliases as $alias => $id) { Chris@14: $id = $this->container->normalizeId($id); Chris@0: while (isset($aliases[$id])) { Chris@14: $id = $this->container->normalizeId($aliases[$id]); Chris@0: } Chris@14: $code .= ' '.$this->doExport($alias).' => '.$this->doExport($id).",\n"; Chris@0: } Chris@0: Chris@17: return $code." ];\n"; Chris@0: } Chris@0: Chris@14: private function addInlineRequires() Chris@14: { Chris@14: if (!$this->hotPathTag || !$this->inlineRequires) { Chris@14: return ''; Chris@14: } Chris@14: Chris@17: $lineage = []; Chris@14: Chris@14: foreach ($this->container->findTaggedServiceIds($this->hotPathTag) as $id => $tags) { Chris@14: $definition = $this->container->getDefinition($id); Chris@17: $inlinedDefinitions = $this->getDefinitionsFromArguments([$definition]); Chris@14: Chris@14: foreach ($inlinedDefinitions as $def) { Chris@17: if (\is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) { Chris@14: $this->collectLineage($class, $lineage); Chris@14: } Chris@14: } Chris@14: } Chris@14: Chris@14: $code = ''; Chris@14: Chris@14: foreach ($lineage as $file) { Chris@14: if (!isset($this->inlinedRequires[$file])) { Chris@14: $this->inlinedRequires[$file] = true; Chris@14: $code .= sprintf("\n include_once %s;", $file); Chris@14: } Chris@14: } Chris@14: Chris@14: return $code ? sprintf("\n \$this->privates['service_container'] = function () {%s\n };\n", $code) : ''; Chris@14: } Chris@14: Chris@0: /** Chris@0: * Adds default parameters method. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addDefaultParametersMethod() Chris@0: { Chris@0: if (!$this->container->getParameterBag()->all()) { Chris@0: return ''; Chris@0: } Chris@0: Chris@17: $php = []; Chris@17: $dynamicPhp = []; Chris@17: $normalizedParams = []; Chris@0: Chris@0: foreach ($this->container->getParameterBag()->all() as $key => $value) { Chris@0: if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) { Chris@0: throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: %s.', $resolvedKey)); Chris@0: } Chris@14: if ($key !== $lcKey = strtolower($key)) { Chris@14: $normalizedParams[] = sprintf(' %s => %s,', $this->export($lcKey), $this->export($key)); Chris@14: } Chris@17: $export = $this->exportParameters([$value]); Chris@17: $export = explode('0 => ', substr(rtrim($export, " ]\n"), 2, -1), 2); Chris@0: Chris@14: if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $export[1])) { Chris@0: $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]); Chris@0: } else { Chris@0: $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]); Chris@0: } Chris@0: } Chris@17: Chris@17: $parameters = sprintf("[\n%s\n%s]", implode("\n", $php), str_repeat(' ', 8)); Chris@0: Chris@0: $code = ''; Chris@14: if ($this->container->isCompiled()) { Chris@0: $code .= <<<'EOF' Chris@0: Chris@0: public function getParameter($name) Chris@0: { Chris@14: $name = (string) $name; Chris@14: if (isset($this->buildParameters[$name])) { Chris@14: return $this->buildParameters[$name]; Chris@14: } Chris@14: if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) { Chris@14: $name = $this->normalizeParameterName($name); Chris@0: Chris@14: if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) { Chris@14: throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); Chris@14: } Chris@0: } Chris@0: if (isset($this->loadedDynamicParameters[$name])) { Chris@0: return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name); Chris@0: } Chris@0: Chris@0: return $this->parameters[$name]; Chris@0: } Chris@0: Chris@0: public function hasParameter($name) Chris@0: { Chris@14: $name = (string) $name; Chris@14: if (isset($this->buildParameters[$name])) { Chris@14: return true; Chris@14: } Chris@14: $name = $this->normalizeParameterName($name); Chris@0: Chris@14: return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters); Chris@0: } Chris@0: Chris@0: public function setParameter($name, $value) Chris@0: { Chris@0: throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); Chris@0: } Chris@0: Chris@0: public function getParameterBag() Chris@0: { Chris@0: if (null === $this->parameterBag) { Chris@0: $parameters = $this->parameters; Chris@0: foreach ($this->loadedDynamicParameters as $name => $loaded) { Chris@0: $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name); Chris@0: } Chris@14: foreach ($this->buildParameters as $name => $value) { Chris@14: $parameters[$name] = $value; Chris@14: } Chris@0: $this->parameterBag = new FrozenParameterBag($parameters); Chris@0: } Chris@0: Chris@0: return $this->parameterBag; Chris@0: } Chris@0: Chris@0: EOF; Chris@14: if (!$this->asFiles) { Chris@14: $code = preg_replace('/^.*buildParameters.*\n.*\n.*\n/m', '', $code); Chris@0: } Chris@0: Chris@0: if ($dynamicPhp) { Chris@17: $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, \count($dynamicPhp), false)), '', 8); Chris@0: $getDynamicParameter = <<<'EOF' Chris@0: switch ($name) { Chris@0: %s Chris@0: default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name)); Chris@0: } Chris@0: $this->loadedDynamicParameters[$name] = true; Chris@0: Chris@0: return $this->dynamicParameters[$name] = $value; Chris@0: EOF; Chris@0: $getDynamicParameter = sprintf($getDynamicParameter, implode("\n", $dynamicPhp)); Chris@0: } else { Chris@17: $loadedDynamicParameters = '[]'; Chris@0: $getDynamicParameter = str_repeat(' ', 8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));'; Chris@0: } Chris@0: Chris@0: $code .= <<docStar} Chris@0: * Computes a dynamic parameter. Chris@0: * Chris@17: * @param string \$name The name of the dynamic parameter to load Chris@0: * Chris@0: * @return mixed The value of the dynamic parameter Chris@0: * Chris@0: * @throws InvalidArgumentException When the dynamic parameter does not exist Chris@0: */ Chris@0: private function getDynamicParameter(\$name) Chris@0: { Chris@0: {$getDynamicParameter} Chris@0: } Chris@0: Chris@14: Chris@14: EOF; Chris@14: Chris@17: $code .= ' private $normalizedParameterNames = '.($normalizedParams ? sprintf("[\n%s\n ];", implode("\n", $normalizedParams)) : '[];')."\n"; Chris@14: $code .= <<<'EOF' Chris@14: Chris@14: private function normalizeParameterName($name) Chris@14: { Chris@14: if (isset($this->normalizedParameterNames[$normalizedName = strtolower($name)]) || isset($this->parameters[$normalizedName]) || array_key_exists($normalizedName, $this->parameters)) { Chris@14: $normalizedName = isset($this->normalizedParameterNames[$normalizedName]) ? $this->normalizedParameterNames[$normalizedName] : $normalizedName; Chris@14: if ((string) $name !== $normalizedName) { Chris@14: @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); Chris@14: } Chris@14: } else { Chris@14: $normalizedName = $this->normalizedParameterNames[$normalizedName] = (string) $name; Chris@14: } Chris@14: Chris@14: return $normalizedName; Chris@14: } Chris@14: Chris@0: EOF; Chris@0: } elseif ($dynamicPhp) { Chris@0: throw new RuntimeException('You cannot dump a not-frozen container with dynamic parameters.'); Chris@0: } Chris@0: Chris@0: $code .= <<docStar} Chris@0: * Gets the default parameters. Chris@0: * Chris@0: * @return array An array of the default parameters Chris@0: */ Chris@0: protected function getDefaultParameters() Chris@0: { Chris@0: return $parameters; Chris@0: } Chris@0: Chris@0: EOF; Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Exports parameters. Chris@0: * Chris@0: * @param array $parameters Chris@0: * @param string $path Chris@0: * @param int $indent Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: */ Chris@0: private function exportParameters(array $parameters, $path = '', $indent = 12) Chris@0: { Chris@17: $php = []; Chris@0: foreach ($parameters as $key => $value) { Chris@17: if (\is_array($value)) { Chris@0: $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4); Chris@14: } elseif ($value instanceof ArgumentInterface) { Chris@17: throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain special arguments. "%s" found in "%s".', \get_class($value), $path.'/'.$key)); Chris@0: } elseif ($value instanceof Variable) { Chris@0: throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key)); Chris@0: } elseif ($value instanceof Definition) { Chris@0: 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)); Chris@0: } elseif ($value instanceof Reference) { Chris@0: 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)); Chris@0: } elseif ($value instanceof Expression) { Chris@0: throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key)); Chris@0: } else { Chris@0: $value = $this->export($value); Chris@0: } Chris@0: Chris@0: $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), $this->export($key), $value); Chris@0: } Chris@0: Chris@17: return sprintf("[\n%s\n%s]", implode("\n", $php), str_repeat(' ', $indent - 4)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Ends the class definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function endClass() Chris@0: { Chris@0: return <<<'EOF' Chris@0: } Chris@0: Chris@0: EOF; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Wraps the service conditionals. Chris@0: * Chris@0: * @param string $value Chris@0: * @param string $code Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function wrapServiceConditionals($value, $code) Chris@0: { Chris@14: if (!$condition = $this->getServiceConditionals($value)) { Chris@0: return $code; Chris@0: } Chris@0: Chris@14: // re-indent the wrapped code Chris@14: $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code))); Chris@14: Chris@14: return sprintf(" if (%s) {\n%s }\n", $condition, $code); Chris@14: } Chris@14: Chris@14: /** Chris@14: * Get the conditions to execute for conditional services. Chris@14: * Chris@14: * @param string $value Chris@14: * Chris@17: * @return string|null Chris@14: */ Chris@14: private function getServiceConditionals($value) Chris@14: { Chris@17: $conditions = []; Chris@14: foreach (ContainerBuilder::getInitializedConditionals($value) as $service) { Chris@14: if (!$this->container->hasDefinition($service)) { Chris@14: return 'false'; Chris@14: } Chris@18: $conditions[] = sprintf('isset($this->services[%s])', $this->doExport($service)); Chris@14: } Chris@14: foreach (ContainerBuilder::getServiceConditionals($value) as $service) { Chris@12: if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) { Chris@12: continue; Chris@12: } Chris@12: Chris@18: $conditions[] = sprintf('$this->has(%s)', $this->doExport($service)); Chris@0: } Chris@0: Chris@12: if (!$conditions) { Chris@14: return ''; Chris@12: } Chris@12: Chris@14: return implode(' && ', $conditions); Chris@0: } Chris@0: Chris@17: private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = []) Chris@0: { Chris@14: if (null === $definitions) { Chris@14: $definitions = new \SplObjectStorage(); Chris@0: } Chris@0: Chris@0: foreach ($arguments as $argument) { Chris@17: if (\is_array($argument)) { Chris@17: $this->getDefinitionsFromArguments($argument, $definitions, $calls); Chris@17: } elseif ($argument instanceof Reference) { Chris@17: $id = $this->container->normalizeId($argument); Chris@17: Chris@17: if (!isset($calls[$id])) { Chris@17: $calls[$id] = [0, $argument->getInvalidBehavior()]; Chris@17: } else { Chris@17: $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior()); Chris@17: } Chris@17: Chris@17: ++$calls[$id][0]; Chris@14: } elseif (!$argument instanceof Definition) { Chris@14: // no-op Chris@14: } elseif (isset($definitions[$argument])) { Chris@14: $definitions[$argument] = 1 + $definitions[$argument]; Chris@14: } else { Chris@14: $definitions[$argument] = 1; Chris@17: $arguments = [$argument->getArguments(), $argument->getFactory(), $argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()]; Chris@17: $this->getDefinitionsFromArguments($arguments, $definitions, $calls); Chris@0: } Chris@0: } Chris@0: Chris@0: return $definitions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Dumps values. Chris@0: * Chris@0: * @param mixed $value Chris@0: * @param bool $interpolate Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws RuntimeException Chris@0: */ Chris@0: private function dumpValue($value, $interpolate = true) Chris@0: { Chris@17: if (\is_array($value)) { Chris@14: if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) { Chris@14: return $this->dumpValue("%$param%"); Chris@14: } Chris@17: $code = []; Chris@0: foreach ($value as $k => $v) { Chris@0: $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)); Chris@0: } Chris@0: Chris@17: return sprintf('[%s]', implode(', ', $code)); Chris@14: } elseif ($value instanceof ArgumentInterface) { Chris@17: $scope = [$this->definitionVariables, $this->referenceVariables]; Chris@14: $this->definitionVariables = $this->referenceVariables = null; Chris@14: Chris@14: try { Chris@14: if ($value instanceof ServiceClosureArgument) { Chris@14: $value = $value->getValues()[0]; Chris@14: $code = $this->dumpValue($value, $interpolate); Chris@14: Chris@14: if ($value instanceof TypedReference) { Chris@14: $code = sprintf('$f = function (\\%s $v%s) { return $v; }; return $f(%s);', $value->getType(), ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $value->getInvalidBehavior() ? ' = null' : '', $code); Chris@14: } else { Chris@14: $code = sprintf('return %s;', $code); Chris@14: } Chris@14: Chris@14: return sprintf("function () {\n %s\n }", $code); Chris@14: } Chris@14: Chris@14: if ($value instanceof IteratorArgument) { Chris@17: $operands = [0]; Chris@17: $code = []; Chris@14: $code[] = 'new RewindableGenerator(function () {'; Chris@14: Chris@14: if (!$values = $value->getValues()) { Chris@14: $code[] = ' return new \EmptyIterator();'; Chris@14: } else { Chris@17: $countCode = []; Chris@14: $countCode[] = 'function () {'; Chris@14: Chris@14: foreach ($values as $k => $v) { Chris@14: ($c = $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0]; Chris@14: $v = $this->wrapServiceConditionals($v, sprintf(" yield %s => %s;\n", $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate))); Chris@14: foreach (explode("\n", $v) as $v) { Chris@14: if ($v) { Chris@14: $code[] = ' '.$v; Chris@14: } Chris@14: } Chris@14: } Chris@14: Chris@14: $countCode[] = sprintf(' return %s;', implode(' + ', $operands)); Chris@14: $countCode[] = ' }'; Chris@14: } Chris@14: Chris@17: $code[] = sprintf(' }, %s)', \count($operands) > 1 ? implode("\n", $countCode) : $operands[0]); Chris@14: Chris@14: return implode("\n", $code); Chris@14: } Chris@14: } finally { Chris@17: list($this->definitionVariables, $this->referenceVariables) = $scope; Chris@14: } Chris@0: } elseif ($value instanceof Definition) { Chris@0: if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { Chris@14: return $this->dumpValue($this->definitionVariables[$value], $interpolate); Chris@0: } Chris@0: if ($value->getMethodCalls()) { Chris@0: throw new RuntimeException('Cannot dump definitions which have method calls.'); Chris@0: } Chris@0: if ($value->getProperties()) { Chris@0: throw new RuntimeException('Cannot dump definitions which have properties.'); Chris@0: } Chris@0: if (null !== $value->getConfigurator()) { Chris@0: throw new RuntimeException('Cannot dump definitions which have a configurator.'); Chris@0: } Chris@0: Chris@17: $arguments = []; Chris@0: foreach ($value->getArguments() as $argument) { Chris@0: $arguments[] = $this->dumpValue($argument); Chris@0: } Chris@0: Chris@0: if (null !== $value->getFactory()) { Chris@0: $factory = $value->getFactory(); Chris@0: Chris@17: if (\is_string($factory)) { Chris@0: return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments)); Chris@0: } Chris@0: Chris@17: if (\is_array($factory)) { Chris@0: if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) { Chris@0: throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a')); Chris@0: } Chris@0: Chris@14: $class = $this->dumpValue($factory[0]); Chris@17: if (\is_string($factory[0])) { Chris@14: return sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $factory[1], implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: if ($factory[0] instanceof Definition) { Chris@14: if (0 === strpos($class, 'new ')) { Chris@14: return sprintf('(%s)->%s(%s)', $class, $factory[1], implode(', ', $arguments)); Chris@14: } Chris@14: Chris@17: return sprintf("\\call_user_func([%s, '%s']%s)", $class, $factory[1], \count($arguments) > 0 ? ', '.implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: if ($factory[0] instanceof Reference) { Chris@14: return sprintf('%s->%s(%s)', $class, $factory[1], implode(', ', $arguments)); Chris@0: } Chris@0: } Chris@0: Chris@0: throw new RuntimeException('Cannot dump definition because of invalid factory'); Chris@0: } Chris@0: Chris@0: $class = $value->getClass(); Chris@0: if (null === $class) { Chris@0: throw new RuntimeException('Cannot dump definitions which have no class nor factory.'); Chris@0: } Chris@0: Chris@0: return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments)); Chris@0: } elseif ($value instanceof Variable) { Chris@0: return '$'.$value; Chris@0: } elseif ($value instanceof Reference) { Chris@14: $id = $this->container->normalizeId($value); Chris@14: if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) { Chris@0: return $this->dumpValue($this->referenceVariables[$id], $interpolate); Chris@0: } Chris@0: Chris@14: return $this->getServiceCall($id, $value); Chris@0: } elseif ($value instanceof Expression) { Chris@17: return $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']); Chris@0: } elseif ($value instanceof Parameter) { Chris@0: return $this->dumpParameter($value); Chris@17: } elseif (true === $interpolate && \is_string($value)) { Chris@0: if (preg_match('/^%([^%]+)%$/', $value, $match)) { Chris@0: // we do this to deal with non string values (Boolean, integer, ...) Chris@0: // the preg_replace_callback converts them to strings Chris@14: return $this->dumpParameter($match[1]); Chris@0: } else { Chris@0: $replaceParameters = function ($match) { Chris@14: return "'.".$this->dumpParameter($match[2]).".'"; Chris@0: }; Chris@0: Chris@0: $code = str_replace('%%', '%', preg_replace_callback('/(?export($value))); Chris@0: Chris@0: return $code; Chris@0: } Chris@17: } elseif (\is_object($value) || \is_resource($value)) { Chris@0: throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); Chris@0: } Chris@0: Chris@0: return $this->export($value); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Dumps a string to a literal (aka PHP Code) class value. Chris@0: * Chris@0: * @param string $class Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws RuntimeException Chris@0: */ Chris@0: private function dumpLiteralClass($class) Chris@0: { Chris@0: if (false !== strpos($class, '$')) { Chris@0: return sprintf('${($_ = %s) && false ?: "_"}', $class); Chris@0: } Chris@12: 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)) { Chris@0: throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s)', $class ?: 'n/a')); Chris@0: } Chris@0: Chris@12: $class = substr(str_replace('\\\\', '\\', $class), 1, -1); Chris@12: Chris@12: return 0 === strpos($class, '\\') ? $class : '\\'.$class; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Dumps a parameter. Chris@0: * Chris@0: * @param string $name Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function dumpParameter($name) Chris@0: { Chris@18: $name = (string) $name; Chris@18: Chris@14: if ($this->container->isCompiled() && $this->container->hasParameter($name)) { Chris@14: $value = $this->container->getParameter($name); Chris@14: $dumpedValue = $this->dumpValue($value, false); Chris@14: Chris@17: if (!$value || !\is_array($value)) { Chris@14: return $dumpedValue; Chris@14: } Chris@14: Chris@14: if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) { Chris@18: return sprintf('$this->parameters[%s]', $this->doExport($name)); Chris@14: } Chris@0: } Chris@0: Chris@18: return sprintf('$this->getParameter(%s)', $this->doExport($name)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a service call. Chris@0: * Chris@0: * @param string $id Chris@0: * @param Reference $reference Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function getServiceCall($id, Reference $reference = null) Chris@0: { Chris@12: while ($this->container->hasAlias($id)) { Chris@12: $id = (string) $this->container->getAlias($id); Chris@12: } Chris@14: $id = $this->container->normalizeId($id); Chris@12: Chris@0: if ('service_container' === $id) { Chris@0: return '$this'; Chris@0: } Chris@0: Chris@17: if ($this->container->hasDefinition($id) && $definition = $this->container->getDefinition($id)) { Chris@17: if ($definition->isSynthetic()) { Chris@18: $code = sprintf('$this->get(%s%s)', $this->doExport($id), null !== $reference ? ', '.$reference->getInvalidBehavior() : ''); Chris@17: } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) { Chris@14: $code = 'null'; Chris@16: if (!$definition->isShared()) { Chris@16: return $code; Chris@16: } Chris@14: } elseif ($this->isTrivialInstance($definition)) { Chris@14: $code = substr($this->addNewInstance($definition, '', '', $id), 8, -2); Chris@14: if ($definition->isShared()) { Chris@18: $code = sprintf('$this->services[%s] = %s', $this->doExport($id), $code); Chris@14: } Chris@17: $code = "($code)"; Chris@14: } elseif ($this->asFiles && $definition->isShared() && !$this->isHotPath($definition)) { Chris@14: $code = sprintf("\$this->load('%s.php')", $this->generateMethodName($id)); Chris@14: } else { Chris@14: $code = sprintf('$this->%s()', $this->generateMethodName($id)); Chris@14: } Chris@14: } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) { Chris@14: return 'null'; Chris@14: } elseif (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { Chris@18: $code = sprintf('$this->get(%s, /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $this->doExport($id), ContainerInterface::NULL_ON_INVALID_REFERENCE); Chris@14: } else { Chris@18: $code = sprintf('$this->get(%s)', $this->doExport($id)); Chris@0: } Chris@0: Chris@14: // The following is PHP 5.5 syntax for what could be written as "(\$this->services['$id'] ?? $code)" on PHP>=7.0 Chris@14: Chris@18: return sprintf("\${(\$_ = isset(\$this->services[%s]) ? \$this->services[%1\$s] : %s) && false ?: '_'}", $this->doExport($id), $code); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Initializes the method names map to avoid conflicts with the Container methods. Chris@0: * Chris@0: * @param string $class the container base class Chris@0: */ Chris@0: private function initializeMethodNamesMap($class) Chris@0: { Chris@17: $this->serviceIdToMethodNameMap = []; Chris@17: $this->usedMethodNames = []; Chris@0: Chris@14: if ($reflectionClass = $this->container->getReflectionClass($class)) { Chris@0: foreach ($reflectionClass->getMethods() as $method) { Chris@0: $this->usedMethodNames[strtolower($method->getName())] = true; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Convert a service id to a valid PHP method name. Chris@0: * Chris@0: * @param string $id Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: */ Chris@0: private function generateMethodName($id) Chris@0: { Chris@0: if (isset($this->serviceIdToMethodNameMap[$id])) { Chris@0: return $this->serviceIdToMethodNameMap[$id]; Chris@0: } Chris@0: Chris@14: $i = strrpos($id, '\\'); Chris@14: $name = Container::camelize(false !== $i && isset($id[1 + $i]) ? substr($id, 1 + $i) : $id); Chris@0: $name = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '', $name); Chris@0: $methodName = 'get'.$name.'Service'; Chris@0: $suffix = 1; Chris@0: Chris@0: while (isset($this->usedMethodNames[strtolower($methodName)])) { Chris@0: ++$suffix; Chris@0: $methodName = 'get'.$name.$suffix.'Service'; Chris@0: } Chris@0: Chris@0: $this->serviceIdToMethodNameMap[$id] = $methodName; Chris@0: $this->usedMethodNames[strtolower($methodName)] = true; Chris@0: Chris@0: return $methodName; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the next name to use. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function getNextVariableName() Chris@0: { Chris@0: $firstChars = self::FIRST_CHARS; Chris@17: $firstCharsLength = \strlen($firstChars); Chris@0: $nonFirstChars = self::NON_FIRST_CHARS; Chris@17: $nonFirstCharsLength = \strlen($nonFirstChars); Chris@0: Chris@0: while (true) { Chris@0: $name = ''; Chris@0: $i = $this->variableCount; Chris@0: Chris@0: if ('' === $name) { Chris@0: $name .= $firstChars[$i % $firstCharsLength]; Chris@0: $i = (int) ($i / $firstCharsLength); Chris@0: } Chris@0: Chris@0: while ($i > 0) { Chris@0: --$i; Chris@0: $name .= $nonFirstChars[$i % $nonFirstCharsLength]; Chris@0: $i = (int) ($i / $nonFirstCharsLength); Chris@0: } Chris@0: Chris@0: ++$this->variableCount; Chris@0: Chris@0: // check that the name is not reserved Chris@17: if (\in_array($name, $this->reservedVariables, true)) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: return $name; Chris@0: } Chris@0: } Chris@0: Chris@0: private function getExpressionLanguage() Chris@0: { Chris@0: if (null === $this->expressionLanguage) { Chris@0: if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { Chris@0: throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); Chris@0: } Chris@0: $providers = $this->container->getExpressionLanguageProviders(); Chris@12: $this->expressionLanguage = new ExpressionLanguage(null, $providers, function ($arg) { Chris@12: $id = '""' === substr_replace($arg, '', 1, -1) ? stripcslashes(substr($arg, 1, -1)) : null; Chris@12: Chris@12: if (null !== $id && ($this->container->hasAlias($id) || $this->container->hasDefinition($id))) { Chris@12: return $this->getServiceCall($id); Chris@12: } Chris@12: Chris@12: return sprintf('$this->get(%s)', $arg); Chris@12: }); Chris@0: Chris@0: if ($this->container->isTrackingResources()) { Chris@0: foreach ($providers as $provider) { Chris@0: $this->container->addObjectResource($provider); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: return $this->expressionLanguage; Chris@0: } Chris@0: Chris@14: private function isHotPath(Definition $definition) Chris@0: { Chris@14: return $this->hotPathTag && $definition->hasTag($this->hotPathTag) && !$definition->isDeprecated(); Chris@0: } Chris@0: Chris@0: private function export($value) Chris@0: { Chris@17: if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) { Chris@14: $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1]), true).'.' : ''; Chris@17: $suffix = $matches[0][1] + \strlen($matches[0][0]); Chris@14: $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : ''; Chris@14: $dirname = $this->asFiles ? '$this->containerDir' : '__DIR__'; Chris@17: $offset = 1 + $this->targetDirMaxMatches - \count($matches); Chris@0: Chris@14: if ($this->asFiles || 0 < $offset) { Chris@0: $dirname = sprintf('$this->targetDirs[%d]', $offset); Chris@0: } Chris@0: Chris@0: if ($prefix || $suffix) { Chris@0: return sprintf('(%s%s%s)', $prefix, $dirname, $suffix); Chris@0: } Chris@0: Chris@0: return $dirname; Chris@0: } Chris@0: Chris@14: return $this->doExport($value, true); Chris@0: } Chris@0: Chris@14: private function doExport($value, $resolveEnv = false) Chris@0: { Chris@17: if (\is_string($value) && false !== strpos($value, "\n")) { Chris@14: $cleanParts = explode("\n", $value); Chris@14: $cleanParts = array_map(function ($part) { return var_export($part, true); }, $cleanParts); Chris@14: $export = implode('."\n".', $cleanParts); Chris@14: } else { Chris@14: $export = var_export($value, true); Chris@14: } Chris@0: Chris@14: if ($resolveEnv && "'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('string:%s').'")) { Chris@0: $export = $resolvedExport; Chris@14: if (".''" === substr($export, -3)) { Chris@14: $export = substr($export, 0, -3); Chris@14: if ("'" === $export[1]) { Chris@14: $export = substr_replace($export, '', 18, 7); Chris@14: } Chris@14: } Chris@0: if ("'" === $export[1]) { Chris@0: $export = substr($export, 3); Chris@0: } Chris@0: } Chris@0: Chris@0: return $export; Chris@0: } Chris@0: }