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@0: use Symfony\Component\DependencyInjection\Argument\ArgumentInterface; Chris@0: use Symfony\Component\DependencyInjection\Argument\IteratorArgument; Chris@0: use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; Chris@0: use Symfony\Component\DependencyInjection\Variable; Chris@0: use Symfony\Component\DependencyInjection\Definition; Chris@0: use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass; Chris@0: use Symfony\Component\DependencyInjection\ContainerBuilder; Chris@0: use Symfony\Component\DependencyInjection\Container; Chris@0: use Symfony\Component\DependencyInjection\ContainerInterface; Chris@0: use Symfony\Component\DependencyInjection\Reference; Chris@0: use Symfony\Component\DependencyInjection\TypedReference; Chris@0: use Symfony\Component\DependencyInjection\Parameter; 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@0: use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; Chris@0: use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; Chris@0: use Symfony\Component\DependencyInjection\ExpressionLanguage; 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@0: private $reservedVariables = array('instance', 'class'); 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@0: private $namespace; Chris@0: private $asFiles; Chris@0: private $hotPathTag; Chris@0: private $inlineRequires; Chris@0: private $inlinedRequires = array(); Chris@0: private $circularReferences = array(); Chris@0: Chris@0: /** Chris@0: * @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@0: if (!$container->isCompiled()) { Chris@0: @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@0: } Chris@0: 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@0: * * as_files: To split the container in several files Chris@0: * Chris@0: * @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@0: public function dump(array $options = array()) Chris@0: { Chris@0: $this->targetDirRegex = null; Chris@0: $this->inlinedRequires = array(); Chris@0: $options = array_merge(array( Chris@0: 'class' => 'ProjectServiceContainer', Chris@0: 'base_class' => 'Container', Chris@0: 'namespace' => '', Chris@0: 'as_files' => false, Chris@0: 'debug' => true, Chris@0: 'hot_path_tag' => 'container.hot_path', Chris@0: 'inline_class_loader_parameter' => 'container.dumper.inline_class_loader', Chris@0: 'build_time' => time(), Chris@0: ), $options); Chris@0: Chris@0: $this->namespace = $options['namespace']; Chris@0: $this->asFiles = $options['as_files']; Chris@0: $this->hotPathTag = $options['hot_path_tag']; Chris@0: $this->inlineRequires = $options['inline_class_loader_parameter'] && $this->container->hasParameter($options['inline_class_loader_parameter']) && $this->container->getParameter($options['inline_class_loader_parameter']); Chris@0: Chris@0: if (0 !== strpos($baseClass = $options['base_class'], '\\') && 'Container' !== $baseClass) { Chris@0: $baseClass = sprintf('%s\%s', $options['namespace'] ? '\\'.$options['namespace'] : '', $baseClass); Chris@0: $baseClassWithNamespace = $baseClass; Chris@0: } elseif ('Container' === $baseClass) { Chris@0: $baseClassWithNamespace = Container::class; Chris@0: } else { Chris@0: $baseClassWithNamespace = $baseClass; Chris@0: } Chris@0: Chris@0: $this->initializeMethodNamesMap('Container' === $baseClass ? Container::class : $baseClass); Chris@0: Chris@0: (new AnalyzeServiceReferencesPass())->process($this->container); Chris@0: $this->circularReferences = array(); Chris@0: $checkedNodes = array(); Chris@0: foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) { Chris@0: $currentPath = array($id => $id); Chris@0: $this->analyzeCircularReferences($node->getOutEdges(), $checkedNodes, $currentPath); Chris@0: } Chris@0: $this->container->getCompiler()->getServiceReferenceGraph()->clear(); Chris@0: Chris@0: $this->docStar = $options['debug'] ? '*' : ''; Chris@0: Chris@0: 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@0: $dir = explode(DIRECTORY_SEPARATOR, realpath($dir)); Chris@0: $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@0: $regex = sprintf('(%s%s)?', preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex); Chris@0: } Chris@0: Chris@0: do { Chris@0: $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@0: $code = Chris@0: $this->startClass($options['class'], $baseClass, $baseClassWithNamespace). Chris@0: $this->addServices(). Chris@0: $this->addDefaultParametersMethod(). Chris@0: $this->endClass() Chris@0: ; Chris@0: Chris@0: if ($this->asFiles) { Chris@0: $fileStart = <<container->getRemovedIds())) { Chris@0: sort($ids); Chris@0: $c = "doExport($id)." => true,\n"; Chris@0: } Chris@0: $files['removed-ids.php'] = $c .= ");\n"; Chris@0: } Chris@0: Chris@0: foreach ($this->generateServiceFiles() as $file => $c) { Chris@0: $files[$file] = $fileStart.$c; Chris@0: } Chris@0: foreach ($this->generateProxyClasses() as $file => $c) { Chris@0: $files[$file] = " $c) { Chris@0: $code["Container{$hash}/{$file}"] = $c; Chris@0: } Chris@0: array_pop($code); Chris@0: $code["Container{$hash}/{$options['class']}.php"] = substr_replace($files[$options['class'].'.php'], "namespace ? "\nnamespace {$this->namespace};\n" : ''; Chris@0: $time = $options['build_time']; Chris@0: $id = hash('crc32', $hash.$time); Chris@0: Chris@0: $code[$options['class'].'.php'] = << '$hash', Chris@0: 'container.build_id' => '$id', Chris@0: 'container.build_time' => $time, Chris@0: ), __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}'); Chris@0: Chris@0: EOF; Chris@0: } else { Chris@0: foreach ($this->generateProxyClasses() as $c) { Chris@0: $code .= $c; Chris@0: } Chris@0: } Chris@0: Chris@0: $this->targetDirRegex = null; Chris@0: $this->inlinedRequires = array(); Chris@0: $this->circularReferences = array(); Chris@0: Chris@0: $unusedEnvs = array(); 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@0: 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@0: /** Chris@0: * Generates Service local temp variables. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addServiceLocalTempVariables($cId, Definition $definition, \SplObjectStorage $inlinedDefinitions, \SplObjectStorage $allInlinedDefinitions) Chris@0: { Chris@0: $allCalls = $calls = $behavior = array(); Chris@0: Chris@0: foreach ($allInlinedDefinitions as $def) { Chris@0: $arguments = array($def->getArguments(), $def->getFactory(), $def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()); Chris@0: $this->getServiceCallsFromArguments($arguments, $allCalls, false, $cId, $behavior, $allInlinedDefinitions[$def]); Chris@0: } Chris@0: Chris@0: $isPreInstance = isset($inlinedDefinitions[$definition]) && isset($this->circularReferences[$cId]) && !$this->getProxyDumper()->isProxyCandidate($definition) && $definition->isShared(); Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: $this->getServiceCallsFromArguments(array($def->getArguments(), $def->getFactory()), $calls, $isPreInstance, $cId); Chris@0: if ($def !== $definition) { Chris@0: $arguments = array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()); Chris@0: $this->getServiceCallsFromArguments($arguments, $calls, $isPreInstance && !$this->hasReference($cId, $arguments, true), $cId); Chris@0: } Chris@0: } Chris@0: if (!isset($inlinedDefinitions[$definition])) { Chris@0: $arguments = array($definition->getProperties(), $definition->getMethodCalls(), $definition->getConfigurator()); Chris@0: $this->getServiceCallsFromArguments($arguments, $calls, false, $cId); Chris@0: } Chris@0: Chris@0: $code = ''; Chris@0: foreach ($calls as $id => $callCount) { Chris@0: if ('service_container' === $id || $id === $cId || isset($this->referenceVariables[$id])) { Chris@0: continue; Chris@0: } Chris@0: if ($callCount <= 1 && $allCalls[$id] <= 1) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $name = $this->getNextVariableName(); Chris@0: $this->referenceVariables[$id] = new Variable($name); Chris@0: Chris@0: $reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id] ? new Reference($id, $behavior[$id]) : null; Chris@0: $code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($id, $reference)); Chris@0: } Chris@0: Chris@0: if ('' !== $code) { Chris@0: if ($isPreInstance) { Chris@0: $code .= <<services['$cId'])) { Chris@0: return \$this->services['$cId']; Chris@0: } Chris@0: Chris@0: EOTXT; Chris@0: } Chris@0: Chris@0: $code .= "\n"; Chris@0: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: private function analyzeCircularReferences(array $edges, &$checkedNodes, &$currentPath) Chris@0: { Chris@0: foreach ($edges as $edge) { Chris@0: $node = $edge->getDestNode(); Chris@0: $id = $node->getId(); Chris@0: Chris@0: if ($node->getValue() && ($edge->isLazy() || $edge->isWeak())) { Chris@0: // no-op Chris@0: } elseif (isset($currentPath[$id])) { Chris@0: foreach (array_reverse($currentPath) as $parentId) { Chris@0: $this->circularReferences[$parentId][$id] = $id; Chris@0: $id = $parentId; Chris@0: } Chris@0: } elseif (!isset($checkedNodes[$id])) { Chris@0: $checkedNodes[$id] = true; Chris@0: $currentPath[$id] = $id; Chris@0: $this->analyzeCircularReferences($node->getOutEdges(), $checkedNodes, $currentPath); Chris@0: unset($currentPath[$id]); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: private function collectLineage($class, array &$lineage) Chris@0: { Chris@0: if (isset($lineage[$class])) { Chris@0: return; Chris@0: } Chris@0: if (!$r = $this->container->getReflectionClass($class, false)) { Chris@0: return; Chris@0: } Chris@0: if ($this->container instanceof $class) { Chris@0: return; Chris@0: } Chris@0: $file = $r->getFileName(); Chris@0: if (!$file || $this->doExport($file) === $exportedFile = $this->export($file)) { Chris@0: return; Chris@0: } Chris@0: Chris@0: if ($parent = $r->getParentClass()) { Chris@0: $this->collectLineage($parent->name, $lineage); Chris@0: } Chris@0: Chris@0: foreach ($r->getInterfaces() as $parent) { Chris@0: $this->collectLineage($parent->name, $lineage); Chris@0: } Chris@0: Chris@0: foreach ($r->getTraits() as $parent) { Chris@0: $this->collectLineage($parent->name, $lineage); Chris@0: } Chris@0: Chris@0: $lineage[$class] = substr($exportedFile, 1, -1); Chris@0: } Chris@0: Chris@0: private function generateProxyClasses() Chris@0: { Chris@0: $definitions = $this->container->getDefinitions(); Chris@0: $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments'); Chris@0: $proxyDumper = $this->getProxyDumper(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $definition) { Chris@0: if (!$proxyDumper->isProxyCandidate($definition)) { Chris@0: continue; Chris@0: } Chris@0: // register class' reflector for resource tracking Chris@0: $this->container->getReflectionClass($definition->getClass()); Chris@0: $proxyCode = "\n".$proxyDumper->getProxyCode($definition); 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@0: private function addServiceInclude($cId, Definition $definition, \SplObjectStorage $inlinedDefinitions) Chris@0: { Chris@0: $code = ''; Chris@0: Chris@0: if ($this->inlineRequires && !$this->isHotPath($definition)) { Chris@0: $lineage = $calls = $behavior = array(); Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: if (!$def->isDeprecated() && is_string($class = is_array($factory = $def->getFactory()) && is_string($factory[0]) ? $factory[0] : $def->getClass())) { Chris@0: $this->collectLineage($class, $lineage); Chris@0: } Chris@0: $arguments = array($def->getArguments(), $def->getFactory(), $def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()); Chris@0: $this->getServiceCallsFromArguments($arguments, $calls, false, $cId, $behavior, $inlinedDefinitions[$def]); Chris@0: } Chris@0: Chris@0: foreach ($calls as $id => $callCount) { Chris@0: if ('service_container' !== $id && $id !== $cId Chris@0: && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior[$id] Chris@0: && $this->container->has($id) Chris@0: && $this->isTrivialInstance($def = $this->container->findDefinition($id)) Chris@0: && is_string($class = is_array($factory = $def->getFactory()) && is_string($factory[0]) ? $factory[0] : $def->getClass()) Chris@0: ) { Chris@0: $this->collectLineage($class, $lineage); Chris@0: } Chris@0: } Chris@0: Chris@0: foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) { Chris@0: $code .= sprintf(" include_once %s;\n", $file); Chris@0: } Chris@0: } Chris@0: Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: if ($file = $def->getFile()) { Chris@0: $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 inline definition of a service. Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws RuntimeException When the factory definition is incomplete Chris@0: * @throws ServiceCircularReferenceException When a circular reference is detected Chris@0: */ Chris@0: private function addServiceInlinedDefinitions($id, Definition $definition, \SplObjectStorage $inlinedDefinitions, &$isSimpleInstance) Chris@0: { Chris@0: $code = ''; Chris@0: Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: if ($definition === $def) { Chris@0: continue; Chris@0: } Chris@0: if ($inlinedDefinitions[$def] <= 1 && !$def->getMethodCalls() && !$def->getProperties() && !$def->getConfigurator() && false === strpos($this->dumpValue($def->getClass()), '$')) { Chris@0: continue; Chris@0: } Chris@0: if (isset($this->definitionVariables[$def])) { Chris@0: $name = $this->definitionVariables[$def]; Chris@0: } else { Chris@0: $name = $this->getNextVariableName(); Chris@0: $this->definitionVariables[$def] = new Variable($name); Chris@0: } Chris@0: Chris@0: // a construct like: Chris@0: // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a); Chris@0: // this is an indication for a wrong implementation, you can circumvent this problem Chris@0: // by setting up your service structure like this: Chris@0: // $b = new ServiceB(); Chris@0: // $a = new ServiceA(ServiceB $b); Chris@0: // $b->setServiceA(ServiceA $a); Chris@0: if (isset($inlinedDefinition[$definition]) && $this->hasReference($id, array($def->getArguments(), $def->getFactory()))) { Chris@0: throw new ServiceCircularReferenceException($id, array($id)); Chris@0: } Chris@0: Chris@0: $code .= $this->addNewInstance($def, '$'.$name, ' = ', $id); Chris@0: Chris@0: if (!$this->hasReference($id, array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()), true)) { Chris@0: $code .= $this->addServiceProperties($def, $name); Chris@0: $code .= $this->addServiceMethodCalls($def, $name); Chris@0: $code .= $this->addServiceConfigurator($def, $name); Chris@0: } else { Chris@0: $isSimpleInstance = false; Chris@0: } Chris@0: 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@0: * @param bool $isSimpleInstance Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: * @throws RuntimeException Chris@0: */ Chris@0: private function addServiceInstance($id, Definition $definition, $isSimpleInstance) Chris@0: { Chris@0: $class = $this->dumpValue($definition->getClass()); Chris@0: Chris@0: 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@0: $instantiation = "\$this->services['$id'] = ".($isSimpleInstance ? '' : '$instance'); Chris@0: } elseif (!$isSimpleInstance) { Chris@0: $instantiation = '$instance'; Chris@0: } Chris@0: Chris@0: $return = ''; Chris@0: if ($isSimpleInstance) { Chris@0: $return = 'return '; Chris@0: } else { Chris@0: $instantiation .= ' = '; Chris@0: } Chris@0: Chris@0: $code = $this->addNewInstance($definition, $return, $instantiation, $id); Chris@0: Chris@0: if (!$isSimpleInstance) { Chris@0: $code .= "\n"; Chris@0: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks if the definition is a trivial instance. Chris@0: * Chris@0: * @param Definition $definition Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function isTrivialInstance(Definition $definition) Chris@0: { Chris@0: if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) { Chris@0: return false; Chris@0: } Chris@0: if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < count($definition->getArguments())) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: foreach ($definition->getArguments() as $arg) { Chris@0: if (!$arg || $arg instanceof Parameter) { Chris@0: continue; Chris@0: } Chris@0: if (is_array($arg) && 3 >= count($arg)) { Chris@0: foreach ($arg as $k => $v) { Chris@0: if ($this->dumpValue($k) !== $this->dumpValue($k, false)) { Chris@0: return false; Chris@0: } Chris@0: if (!$v || $v instanceof Parameter) { Chris@0: continue; Chris@0: } Chris@0: if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) { Chris@0: continue; Chris@0: } Chris@0: if (!is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($v, false)) { Chris@0: return false; Chris@0: } Chris@0: } Chris@0: } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) { Chris@0: continue; Chris@0: } elseif (!is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($arg, false)) { Chris@0: return false; Chris@0: } Chris@0: } Chris@0: Chris@0: if (false !== strpos($this->dumpLiteralClass($this->dumpValue($definition->getClass())), '$')) { Chris@0: return false; 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@0: private function addServiceMethodCalls(Definition $definition, $variableName = 'instance') Chris@0: { Chris@0: $calls = ''; Chris@0: foreach ($definition->getMethodCalls() as $call) { Chris@0: $arguments = array(); 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@0: 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: * Generates the inline definition setup. Chris@0: * Chris@0: * @return string Chris@0: * Chris@0: * @throws ServiceCircularReferenceException when the container contains a circular reference Chris@0: */ Chris@0: private function addServiceInlinedDefinitionsSetup($id, Definition $definition, \SplObjectStorage $inlinedDefinitions, $isSimpleInstance) Chris@0: { Chris@0: $this->referenceVariables[$id] = new Variable('instance'); Chris@0: Chris@0: $code = ''; Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: if ($definition === $def || !$this->hasReference($id, array($def->getProperties(), $def->getMethodCalls(), $def->getConfigurator()), true)) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // if the instance is simple, the return statement has already been generated Chris@0: // so, the only possible way to get there is because of a circular reference Chris@0: if ($isSimpleInstance) { Chris@0: throw new ServiceCircularReferenceException($id, array($id)); Chris@0: } Chris@0: Chris@0: $name = (string) $this->definitionVariables[$def]; Chris@0: $code .= $this->addServiceProperties($def, $name); Chris@0: $code .= $this->addServiceMethodCalls($def, $name); Chris@0: $code .= $this->addServiceConfigurator($def, $name); Chris@0: } Chris@0: Chris@0: if ('' !== $code && ($definition->getProperties() || $definition->getMethodCalls() || $definition->getConfigurator())) { Chris@0: $code .= "\n"; 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@0: private function addServiceConfigurator(Definition $definition, $variableName = 'instance') Chris@0: { Chris@0: if (!$callable = $definition->getConfigurator()) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: if (is_array($callable)) { Chris@0: if ($callable[0] instanceof Reference Chris@0: || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { 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@0: return sprintf(" \\call_user_func(array(%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@0: * @param string &$file Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addService($id, Definition $definition, &$file = null) Chris@0: { Chris@0: $this->definitionVariables = new \SplObjectStorage(); Chris@0: $this->referenceVariables = array(); Chris@0: $this->variableCount = 0; Chris@0: Chris@0: $return = array(); Chris@0: Chris@0: if ($class = $definition->getClass()) { Chris@0: $class = $this->container->resolveEnvPlaceholders($class); Chris@0: $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@0: if (is_string($factory)) { Chris@0: $return[] = sprintf('@return object An instance returned by %s()', $factory); Chris@0: } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) { Chris@0: if (is_string($factory[0]) || $factory[0] instanceof Reference) { Chris@0: $return[] = sprintf('@return object An instance returned by %s::%s()', (string) $factory[0], $factory[1]); Chris@0: } elseif ($factory[0] instanceof Definition) { Chris@0: $return[] = sprintf('@return object An instance returned by %s::%s()', $factory[0]->getClass(), $factory[1]); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: if ($definition->isDeprecated()) { Chris@0: 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@0: $shared = $definition->isShared() ? ' shared' : ''; Chris@0: $public = $definition->isPublic() ? 'public' : 'private'; Chris@0: $autowired = $definition->isAutowired() ? ' autowired' : ''; Chris@0: Chris@0: if ($definition->isLazy()) { Chris@0: $lazyInitialization = '$lazyLoad = true'; Chris@0: } else { Chris@0: $lazyInitialization = ''; Chris@0: } Chris@0: Chris@0: $asFile = $this->asFiles && $definition->isShared() && !$this->isHotPath($definition); Chris@0: $methodName = $this->generateMethodName($id); Chris@0: if ($asFile) { Chris@0: $file = $methodName.'.php'; Chris@0: $code = " // Returns the $public '$id'$shared$autowired service.\n\n"; Chris@0: } else { Chris@0: $code = <<docStar} Chris@0: * Gets the $public '$id'$shared$autowired service. Chris@0: * Chris@0: * $return Chris@0: */ Chris@0: protected function {$methodName}($lazyInitialization) Chris@0: { Chris@0: Chris@0: EOF; Chris@0: } Chris@0: Chris@0: if ($this->getProxyDumper()->isProxyCandidate($definition)) { Chris@0: $factoryCode = $asFile ? "\$this->load('%s.php', false)" : '$this->%s(false)'; Chris@0: $code .= $this->getProxyDumper()->getProxyFactoryCode($definition, $id, sprintf($factoryCode, $methodName)); Chris@0: } Chris@0: Chris@0: if ($definition->isDeprecated()) { Chris@0: $code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id))); Chris@0: } Chris@0: Chris@0: $inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition)); Chris@0: $constructorDefinitions = $this->getDefinitionsFromArguments(array($definition->getArguments(), $definition->getFactory())); Chris@0: $otherDefinitions = new \SplObjectStorage(); Chris@0: Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: if ($def === $definition || isset($constructorDefinitions[$def])) { Chris@0: $constructorDefinitions[$def] = $inlinedDefinitions[$def]; Chris@0: } else { Chris@0: $otherDefinitions[$def] = $inlinedDefinitions[$def]; Chris@0: } Chris@0: } Chris@0: Chris@0: $isSimpleInstance = !$definition->getProperties() && !$definition->getMethodCalls() && !$definition->getConfigurator(); Chris@0: Chris@0: $code .= Chris@0: $this->addServiceInclude($id, $definition, $inlinedDefinitions). Chris@0: $this->addServiceLocalTempVariables($id, $definition, $constructorDefinitions, $inlinedDefinitions). Chris@0: $this->addServiceInlinedDefinitions($id, $definition, $constructorDefinitions, $isSimpleInstance). Chris@0: $this->addServiceInstance($id, $definition, $isSimpleInstance). Chris@0: $this->addServiceLocalTempVariables($id, $definition, $otherDefinitions, $inlinedDefinitions). Chris@0: $this->addServiceInlinedDefinitions($id, $definition, $otherDefinitions, $isSimpleInstance). Chris@0: $this->addServiceInlinedDefinitionsSetup($id, $definition, $inlinedDefinitions, $isSimpleInstance). Chris@0: $this->addServiceProperties($definition). Chris@0: $this->addServiceMethodCalls($definition). Chris@0: $this->addServiceConfigurator($definition). Chris@0: (!$isSimpleInstance ? "\n return \$instance;\n" : '') Chris@0: ; Chris@0: Chris@0: if ($asFile) { Chris@0: $code = implode("\n", array_map(function ($line) { return $line ? substr($line, 8) : $line; }, explode("\n", $code))); Chris@0: } else { Chris@0: $code .= " }\n"; Chris@0: } Chris@0: Chris@0: $this->definitionVariables = null; Chris@0: $this->referenceVariables = null; 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@0: if ($definition->isSynthetic() || ($this->asFiles && $definition->isShared() && !$this->isHotPath($definition))) { Chris@0: continue; Chris@0: } 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@0: private function generateServiceFiles() Chris@0: { Chris@0: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) { Chris@0: $code = $this->addService($id, $definition, $file); Chris@0: yield $file => $code; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: private function addNewInstance(Definition $definition, $return, $instantiation, $id) Chris@0: { Chris@0: $class = $this->dumpValue($definition->getClass()); Chris@0: $return = ' '.$return.$instantiation; Chris@0: Chris@0: $arguments = array(); 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@0: 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@0: 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@0: 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@0: return $return.sprintf("(%s)->%s(%s);\n", $class, $callable[1], $arguments ? implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: return $return.sprintf("\\call_user_func(array(%s, '%s')%s);\n", $class, $callable[1], $arguments ? ', '.implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: 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@0: return sprintf(" \$class = %s;\n\n%snew \$class(%s);\n", $class, $return, implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: 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@0: * @param string $class Class name Chris@0: * @param string $baseClass The name of the base class Chris@0: * @param string $baseClassWithNamespace Fully qualified base class name Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function startClass($class, $baseClass, $baseClassWithNamespace) Chris@0: { Chris@0: $bagClass = $this->container->isCompiled() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;'; Chris@0: $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : ''; Chris@0: Chris@0: $code = <<docStar} Chris@0: * This class has been auto-generated Chris@0: * by the Symfony Dependency Injection Component. Chris@0: * Chris@0: * @final since Symfony 3.3 Chris@0: */ Chris@0: class $class extends $baseClass Chris@0: { Chris@0: private \$parameters; Chris@0: private \$targetDirs = array(); Chris@0: Chris@0: public function __construct() Chris@0: { Chris@0: Chris@0: EOF; Chris@0: if (null !== $this->targetDirRegex) { Chris@0: $dir = $this->asFiles ? '$this->targetDirs[0] = \\dirname($containerDir)' : '__DIR__'; Chris@0: $code .= <<targetDirMaxMatches}; ++\$i) { Chris@0: \$this->targetDirs[\$i] = \$dir = \\dirname(\$dir); Chris@0: } Chris@0: Chris@0: EOF; Chris@0: } Chris@0: if ($this->asFiles) { Chris@0: $code = str_replace('$parameters', "\$buildParameters;\n private \$containerDir;\n private \$parameters", $code); Chris@0: $code = str_replace('__construct()', '__construct(array $buildParameters = array(), $containerDir = __DIR__)', $code); Chris@0: $code .= " \$this->buildParameters = \$buildParameters;\n"; Chris@0: $code .= " \$this->containerDir = \$containerDir;\n"; Chris@0: } Chris@0: Chris@0: if ($this->container->isCompiled()) { Chris@0: if (Container::class !== $baseClassWithNamespace) { Chris@0: $r = $this->container->getReflectionClass($baseClassWithNamespace, false); Chris@0: if (null !== $r Chris@0: && (null !== $constructor = $r->getConstructor()) Chris@0: && 0 === $constructor->getNumberOfRequiredParameters() Chris@0: && Container::class !== $constructor->getDeclaringClass()->name Chris@0: ) { Chris@0: $code .= " parent::__construct();\n"; Chris@0: $code .= " \$this->parameterBag = null;\n\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: if ($this->container->getParameterBag()->all()) { Chris@0: $code .= " \$this->parameters = \$this->getDefaultParameters();\n\n"; Chris@0: } Chris@0: Chris@0: $code .= " \$this->services = array();\n"; Chris@0: } else { Chris@0: $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null; Chris@0: $code .= " parent::__construct($arguments);\n"; Chris@0: } Chris@0: Chris@0: $code .= $this->addNormalizedIds(); Chris@0: $code .= $this->addSyntheticIds(); Chris@0: $code .= $this->addMethodMap(); Chris@0: $code .= $this->asFiles ? $this->addFileMap() : ''; Chris@0: $code .= $this->addPrivateServices(); Chris@0: $code .= $this->addAliases(); Chris@0: $code .= $this->addInlineRequires(); Chris@0: $code .= <<<'EOF' Chris@0: } Chris@0: Chris@0: EOF; Chris@0: $code .= $this->addRemovedIds(); Chris@0: Chris@0: if ($this->container->isCompiled()) { Chris@0: $code .= <<asFiles) { Chris@0: $code .= <<containerDir.\\DIRECTORY_SEPARATOR.\$file; Chris@0: } Chris@0: Chris@0: EOF; Chris@0: } Chris@0: Chris@0: $proxyDumper = $this->getProxyDumper(); Chris@0: foreach ($this->container->getDefinitions() as $definition) { Chris@0: if (!$proxyDumper->isProxyCandidate($definition)) { Chris@0: continue; Chris@0: } Chris@0: if ($this->asFiles) { Chris@0: $proxyLoader = '$this->load("{$class}.php")'; Chris@0: } elseif ($this->namespace) { Chris@0: $proxyLoader = 'class_alias("'.$this->namespace.'\\\\{$class}", $class, false)'; Chris@0: } else { Chris@0: $proxyLoader = ''; Chris@0: } Chris@0: if ($proxyLoader) { Chris@0: $proxyLoader = "class_exists(\$class, false) || {$proxyLoader};\n\n "; Chris@0: } Chris@0: $code .= <<container->getNormalizedIds(); Chris@0: ksort($normalizedIds); Chris@0: foreach ($normalizedIds as $id => $normalizedId) { Chris@0: if ($this->container->has($normalizedId)) { Chris@0: $code .= ' '.$this->doExport($id).' => '.$this->doExport($normalizedId).",\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: return $code ? " \$this->normalizedIds = array(\n".$code." );\n" : ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the syntheticIds definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addSyntheticIds() Chris@0: { Chris@0: $code = ''; Chris@0: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if ($definition->isSynthetic() && 'service_container' !== $id) { Chris@0: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: return $code ? " \$this->syntheticIds = array(\n{$code} );\n" : ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the removedIds definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addRemovedIds() Chris@0: { Chris@0: if (!$ids = $this->container->getRemovedIds()) { Chris@0: return ''; Chris@0: } Chris@0: if ($this->asFiles) { Chris@0: $code = "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'"; Chris@0: } else { Chris@0: $code = ''; Chris@0: $ids = array_keys($ids); Chris@0: sort($ids); Chris@0: foreach ($ids as $id) { Chris@0: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@0: } Chris@0: Chris@0: $code = "array(\n{$code} )"; Chris@0: } Chris@0: Chris@0: return <<container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if (!$definition->isSynthetic() && (!$this->asFiles || !$definition->isShared() || $this->isHotPath($definition))) { Chris@0: $code .= ' '.$this->doExport($id).' => '.$this->doExport($this->generateMethodName($id)).",\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: return $code ? " \$this->methodMap = array(\n{$code} );\n" : ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the fileMap property definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addFileMap() Chris@0: { Chris@0: $code = ''; Chris@0: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) { Chris@0: $code .= sprintf(" %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id)); Chris@0: } Chris@0: } Chris@0: Chris@0: return $code ? " \$this->fileMap = array(\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@0: $code = ''; Chris@0: Chris@0: $aliases = $this->container->getAliases(); Chris@0: ksort($aliases); Chris@0: foreach ($aliases as $id => $alias) { Chris@0: if ($alias->isPrivate()) { Chris@0: $code .= ' '.$this->doExport($id)." => true,\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: $definitions = $this->container->getDefinitions(); Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if (!$definition->isPublic()) { Chris@0: $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@0: $out = " \$this->privates = array(\n"; Chris@0: $out .= $code; Chris@0: $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@0: return $this->container->isCompiled() ? "\n \$this->aliases = array();\n" : ''; Chris@0: } Chris@0: Chris@0: $code = " \$this->aliases = array(\n"; Chris@0: ksort($aliases); Chris@0: foreach ($aliases as $alias => $id) { Chris@0: $id = $this->container->normalizeId($id); Chris@0: while (isset($aliases[$id])) { Chris@0: $id = $this->container->normalizeId($aliases[$id]); Chris@0: } Chris@0: $code .= ' '.$this->doExport($alias).' => '.$this->doExport($id).",\n"; Chris@0: } Chris@0: Chris@0: return $code." );\n"; Chris@0: } Chris@0: Chris@0: private function addInlineRequires() Chris@0: { Chris@0: if (!$this->hotPathTag || !$this->inlineRequires) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: $lineage = array(); Chris@0: Chris@0: foreach ($this->container->findTaggedServiceIds($this->hotPathTag) as $id => $tags) { Chris@0: $definition = $this->container->getDefinition($id); Chris@0: $inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition)); Chris@0: Chris@0: foreach ($inlinedDefinitions as $def) { Chris@0: if (is_string($class = is_array($factory = $def->getFactory()) && is_string($factory[0]) ? $factory[0] : $def->getClass())) { Chris@0: $this->collectLineage($class, $lineage); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $code = ''; Chris@0: Chris@0: foreach ($lineage as $file) { Chris@0: if (!isset($this->inlinedRequires[$file])) { Chris@0: $this->inlinedRequires[$file] = true; Chris@0: $code .= sprintf("\n include_once %s;", $file); Chris@0: } Chris@0: } Chris@0: Chris@0: return $code ? sprintf("\n \$this->privates['service_container'] = function () {%s\n };\n", $code) : ''; Chris@0: } Chris@0: 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@0: $php = array(); Chris@0: $dynamicPhp = array(); Chris@0: $normalizedParams = array(); 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@0: if ($key !== $lcKey = strtolower($key)) { Chris@0: $normalizedParams[] = sprintf(' %s => %s,', $this->export($lcKey), $this->export($key)); Chris@0: } Chris@0: $export = $this->exportParameters(array($value)); Chris@0: $export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2); Chris@0: Chris@0: 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@0: $parameters = sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', 8)); Chris@0: Chris@0: $code = ''; Chris@0: if ($this->container->isCompiled()) { Chris@0: $code .= <<<'EOF' Chris@0: Chris@0: public function getParameter($name) Chris@0: { Chris@0: $name = (string) $name; Chris@0: if (isset($this->buildParameters[$name])) { Chris@0: return $this->buildParameters[$name]; Chris@0: } Chris@0: if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) { Chris@0: $name = $this->normalizeParameterName($name); Chris@0: Chris@0: if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || array_key_exists($name, $this->parameters))) { Chris@0: throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); Chris@0: } 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@0: $name = (string) $name; Chris@0: if (isset($this->buildParameters[$name])) { Chris@0: return true; Chris@0: } Chris@0: $name = $this->normalizeParameterName($name); Chris@0: Chris@0: 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@0: foreach ($this->buildParameters as $name => $value) { Chris@0: $parameters[$name] = $value; Chris@0: } Chris@0: $this->parameterBag = new FrozenParameterBag($parameters); Chris@0: } Chris@0: Chris@0: return $this->parameterBag; Chris@0: } Chris@0: Chris@0: EOF; Chris@0: if (!$this->asFiles) { Chris@0: $code = preg_replace('/^.*buildParameters.*\n.*\n.*\n/m', '', $code); Chris@0: } Chris@0: Chris@0: if ($dynamicPhp) { Chris@0: $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@0: $loadedDynamicParameters = 'array()'; 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@0: * @param string 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@0: Chris@0: EOF; Chris@0: Chris@0: $code .= ' private $normalizedParameterNames = '.($normalizedParams ? sprintf("array(\n%s\n );", implode("\n", $normalizedParams)) : 'array();')."\n"; Chris@0: $code .= <<<'EOF' Chris@0: Chris@0: private function normalizeParameterName($name) Chris@0: { Chris@0: if (isset($this->normalizedParameterNames[$normalizedName = strtolower($name)]) || isset($this->parameters[$normalizedName]) || array_key_exists($normalizedName, $this->parameters)) { Chris@0: $normalizedName = isset($this->normalizedParameterNames[$normalizedName]) ? $this->normalizedParameterNames[$normalizedName] : $normalizedName; Chris@0: if ((string) $name !== $normalizedName) { Chris@0: @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@0: } Chris@0: } else { Chris@0: $normalizedName = $this->normalizedParameterNames[$normalizedName] = (string) $name; Chris@0: } Chris@0: Chris@0: return $normalizedName; Chris@0: } Chris@0: 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@0: $php = array(); Chris@0: foreach ($parameters as $key => $value) { Chris@0: if (is_array($value)) { Chris@0: $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4); Chris@0: } elseif ($value instanceof ArgumentInterface) { Chris@0: 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@0: return sprintf("array(\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@0: if (!$condition = $this->getServiceConditionals($value)) { Chris@0: return $code; Chris@0: } Chris@0: Chris@0: // re-indent the wrapped code Chris@0: $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code))); Chris@0: Chris@0: return sprintf(" if (%s) {\n%s }\n", $condition, $code); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the conditions to execute for conditional services. Chris@0: * Chris@0: * @param string $value Chris@0: * Chris@0: * @return null|string Chris@0: */ Chris@0: private function getServiceConditionals($value) Chris@0: { Chris@0: $conditions = array(); Chris@0: foreach (ContainerBuilder::getInitializedConditionals($value) as $service) { Chris@0: if (!$this->container->hasDefinition($service)) { Chris@0: return 'false'; Chris@0: } Chris@0: $conditions[] = sprintf("isset(\$this->services['%s'])", $service); Chris@0: } Chris@0: foreach (ContainerBuilder::getServiceConditionals($value) as $service) { Chris@0: if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $conditions[] = sprintf("\$this->has('%s')", $service); Chris@0: } Chris@0: Chris@0: if (!$conditions) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: return implode(' && ', $conditions); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Builds service calls from arguments. Chris@0: */ Chris@0: private function getServiceCallsFromArguments(array $arguments, array &$calls, $isPreInstance, $callerId, array &$behavior = array(), $step = 1) Chris@0: { Chris@0: foreach ($arguments as $argument) { Chris@0: if (is_array($argument)) { Chris@0: $this->getServiceCallsFromArguments($argument, $calls, $isPreInstance, $callerId, $behavior, $step); Chris@0: } elseif ($argument instanceof Reference) { Chris@0: $id = $this->container->normalizeId($argument); Chris@0: Chris@0: if (!isset($calls[$id])) { Chris@0: $calls[$id] = (int) ($isPreInstance && isset($this->circularReferences[$callerId][$id])); Chris@0: } Chris@0: if (!isset($behavior[$id])) { Chris@0: $behavior[$id] = $argument->getInvalidBehavior(); Chris@0: } else { Chris@0: $behavior[$id] = min($behavior[$id], $argument->getInvalidBehavior()); Chris@0: } Chris@0: Chris@0: $calls[$id] += $step; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null) Chris@0: { Chris@0: if (null === $definitions) { Chris@0: $definitions = new \SplObjectStorage(); Chris@0: } Chris@0: Chris@0: foreach ($arguments as $argument) { Chris@0: if (is_array($argument)) { Chris@0: $this->getDefinitionsFromArguments($argument, $definitions); Chris@0: } elseif (!$argument instanceof Definition) { Chris@0: // no-op Chris@0: } elseif (isset($definitions[$argument])) { Chris@0: $definitions[$argument] = 1 + $definitions[$argument]; Chris@0: } else { Chris@0: $definitions[$argument] = 1; Chris@0: $this->getDefinitionsFromArguments($argument->getArguments(), $definitions); Chris@0: $this->getDefinitionsFromArguments(array($argument->getFactory()), $definitions); Chris@0: $this->getDefinitionsFromArguments($argument->getProperties(), $definitions); Chris@0: $this->getDefinitionsFromArguments($argument->getMethodCalls(), $definitions); Chris@0: $this->getDefinitionsFromArguments(array($argument->getConfigurator()), $definitions); Chris@0: // move current definition last in the list Chris@0: $nbOccurences = $definitions[$argument]; Chris@0: unset($definitions[$argument]); Chris@0: $definitions[$argument] = $nbOccurences; Chris@0: } Chris@0: } Chris@0: Chris@0: return $definitions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks if a service id has a reference. Chris@0: * Chris@0: * @param string $id Chris@0: * @param array $arguments Chris@0: * @param bool $deep Chris@0: * @param array $visited Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function hasReference($id, array $arguments, $deep = false, array &$visited = array()) Chris@0: { Chris@0: if (!isset($this->circularReferences[$id])) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: foreach ($arguments as $argument) { Chris@0: if (is_array($argument)) { Chris@0: if ($this->hasReference($id, $argument, $deep, $visited)) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: continue; Chris@0: } elseif ($argument instanceof Reference) { Chris@0: $argumentId = $this->container->normalizeId($argument); Chris@0: if ($id === $argumentId) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if (!$deep || isset($visited[$argumentId]) || !isset($this->circularReferences[$id][$argumentId])) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $visited[$argumentId] = true; Chris@0: Chris@0: $service = $this->container->getDefinition($argumentId); Chris@0: } elseif ($argument instanceof Definition) { Chris@0: $service = $argument; Chris@0: } else { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // if the proxy manager is enabled, disable searching for references in lazy services, Chris@0: // as these services will be instantiated lazily and don't have direct related references. Chris@0: if ($service->isLazy() && !$this->getProxyDumper() instanceof NullDumper) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($this->hasReference($id, array($service->getArguments(), $service->getFactory(), $service->getProperties(), $service->getMethodCalls(), $service->getConfigurator()), $deep, $visited)) { Chris@0: return true; Chris@0: } Chris@0: } Chris@0: Chris@0: return false; 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@0: if (is_array($value)) { Chris@0: if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) { Chris@0: return $this->dumpValue("%$param%"); Chris@0: } Chris@0: $code = array(); 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@0: return sprintf('array(%s)', implode(', ', $code)); Chris@0: } elseif ($value instanceof ArgumentInterface) { Chris@0: $scope = array($this->definitionVariables, $this->referenceVariables, $this->variableCount); Chris@0: $this->definitionVariables = $this->referenceVariables = null; Chris@0: Chris@0: try { Chris@0: if ($value instanceof ServiceClosureArgument) { Chris@0: $value = $value->getValues()[0]; Chris@0: $code = $this->dumpValue($value, $interpolate); Chris@0: Chris@0: if ($value instanceof TypedReference) { Chris@0: $code = sprintf('$f = function (\\%s $v%s) { return $v; }; return $f(%s);', $value->getType(), ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $value->getInvalidBehavior() ? ' = null' : '', $code); Chris@0: } else { Chris@0: $code = sprintf('return %s;', $code); Chris@0: } Chris@0: Chris@0: return sprintf("function () {\n %s\n }", $code); Chris@0: } Chris@0: Chris@0: if ($value instanceof IteratorArgument) { Chris@0: $operands = array(0); Chris@0: $code = array(); Chris@0: $code[] = 'new RewindableGenerator(function () {'; Chris@0: Chris@0: if (!$values = $value->getValues()) { Chris@0: $code[] = ' return new \EmptyIterator();'; Chris@0: } else { Chris@0: $countCode = array(); Chris@0: $countCode[] = 'function () {'; Chris@0: Chris@0: foreach ($values as $k => $v) { Chris@0: ($c = $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0]; Chris@0: $v = $this->wrapServiceConditionals($v, sprintf(" yield %s => %s;\n", $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate))); Chris@0: foreach (explode("\n", $v) as $v) { Chris@0: if ($v) { Chris@0: $code[] = ' '.$v; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $countCode[] = sprintf(' return %s;', implode(' + ', $operands)); Chris@0: $countCode[] = ' }'; Chris@0: } Chris@0: Chris@0: $code[] = sprintf(' }, %s)', count($operands) > 1 ? implode("\n", $countCode) : $operands[0]); Chris@0: Chris@0: return implode("\n", $code); Chris@0: } Chris@0: } finally { Chris@0: list($this->definitionVariables, $this->referenceVariables, $this->variableCount) = $scope; Chris@0: } Chris@0: } elseif ($value instanceof Definition) { Chris@0: if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { Chris@0: 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@0: $arguments = array(); 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@0: if (is_string($factory)) { Chris@0: return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: 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@0: $class = $this->dumpValue($factory[0]); Chris@0: if (is_string($factory[0])) { Chris@0: return sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $factory[1], implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: if ($factory[0] instanceof Definition) { Chris@0: if (0 === strpos($class, 'new ')) { Chris@0: return sprintf('(%s)->%s(%s)', $class, $factory[1], implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: return sprintf("\\call_user_func(array(%s, '%s')%s)", $class, $factory[1], count($arguments) > 0 ? ', '.implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: if ($factory[0] instanceof Reference) { Chris@0: 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@0: $id = $this->container->normalizeId($value); Chris@0: if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) { Chris@0: return $this->dumpValue($this->referenceVariables[$id], $interpolate); Chris@0: } Chris@0: Chris@0: return $this->getServiceCall($id, $value); Chris@0: } elseif ($value instanceof Expression) { Chris@0: return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container')); Chris@0: } elseif ($value instanceof Parameter) { Chris@0: return $this->dumpParameter($value); Chris@0: } 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@0: return $this->dumpParameter($match[1]); Chris@0: } else { Chris@0: $replaceParameters = function ($match) { Chris@0: 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@0: } 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@0: 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@0: $class = substr(str_replace('\\\\', '\\', $class), 1, -1); Chris@0: Chris@0: 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@0: if ($this->container->isCompiled() && $this->container->hasParameter($name)) { Chris@0: $value = $this->container->getParameter($name); Chris@0: $dumpedValue = $this->dumpValue($value, false); Chris@0: Chris@0: if (!$value || !is_array($value)) { Chris@0: return $dumpedValue; Chris@0: } Chris@0: Chris@0: if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) { Chris@0: return sprintf("\$this->parameters['%s']", $name); Chris@0: } Chris@0: } Chris@0: Chris@0: return sprintf("\$this->getParameter('%s')", $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@0: while ($this->container->hasAlias($id)) { Chris@0: $id = (string) $this->container->getAlias($id); Chris@0: } Chris@0: $id = $this->container->normalizeId($id); Chris@0: Chris@0: if ('service_container' === $id) { Chris@0: return '$this'; Chris@0: } Chris@0: Chris@0: if ($this->container->hasDefinition($id) && ($definition = $this->container->getDefinition($id)) && !$definition->isSynthetic()) { Chris@0: if (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) { Chris@0: $code = 'null'; Chris@0: if (!$definition->isShared()) { Chris@0: return $code; Chris@0: } Chris@0: } elseif ($this->isTrivialInstance($definition)) { Chris@0: $code = substr($this->addNewInstance($definition, '', '', $id), 8, -2); Chris@0: if ($definition->isShared()) { Chris@0: $code = sprintf('$this->services[\'%s\'] = %s', $id, $code); Chris@0: } Chris@0: } elseif ($this->asFiles && $definition->isShared() && !$this->isHotPath($definition)) { Chris@0: $code = sprintf("\$this->load('%s.php')", $this->generateMethodName($id)); Chris@0: } else { Chris@0: $code = sprintf('$this->%s()', $this->generateMethodName($id)); Chris@0: } Chris@0: } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) { Chris@0: return 'null'; Chris@0: } elseif (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { Chris@0: $code = sprintf('$this->get(\'%s\', /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $id, ContainerInterface::NULL_ON_INVALID_REFERENCE); Chris@0: } else { Chris@0: $code = sprintf('$this->get(\'%s\')', $id); Chris@0: } Chris@0: Chris@0: // The following is PHP 5.5 syntax for what could be written as "(\$this->services['$id'] ?? $code)" on PHP>=7.0 Chris@0: Chris@0: return "\${(\$_ = isset(\$this->services['$id']) ? \$this->services['$id'] : $code) && false ?: '_'}"; 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@0: $this->serviceIdToMethodNameMap = array(); Chris@0: $this->usedMethodNames = array(); Chris@0: Chris@0: 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@0: $i = strrpos($id, '\\'); Chris@0: $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@0: $firstCharsLength = strlen($firstChars); Chris@0: $nonFirstChars = self::NON_FIRST_CHARS; Chris@0: $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@0: 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@0: $this->expressionLanguage = new ExpressionLanguage(null, $providers, function ($arg) { Chris@0: $id = '""' === substr_replace($arg, '', 1, -1) ? stripcslashes(substr($arg, 1, -1)) : null; Chris@0: Chris@0: if (null !== $id && ($this->container->hasAlias($id) || $this->container->hasDefinition($id))) { Chris@0: return $this->getServiceCall($id); Chris@0: } Chris@0: Chris@0: return sprintf('$this->get(%s)', $arg); Chris@0: }); 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@0: private function isHotPath(Definition $definition) Chris@0: { Chris@0: return $this->hotPathTag && $definition->hasTag($this->hotPathTag) && !$definition->isDeprecated(); Chris@0: } Chris@0: Chris@0: private function export($value) Chris@0: { Chris@0: if (null !== $this->targetDirRegex && is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) { Chris@0: $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1]), true).'.' : ''; Chris@0: $suffix = $matches[0][1] + strlen($matches[0][0]); Chris@0: $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : ''; Chris@0: $dirname = $this->asFiles ? '$this->containerDir' : '__DIR__'; Chris@0: $offset = 1 + $this->targetDirMaxMatches - count($matches); Chris@0: Chris@0: 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@0: return $this->doExport($value, true); Chris@0: } Chris@0: Chris@0: private function doExport($value, $resolveEnv = false) Chris@0: { Chris@0: if (is_string($value) && false !== strpos($value, "\n")) { Chris@0: $cleanParts = explode("\n", $value); Chris@0: $cleanParts = array_map(function ($part) { return var_export($part, true); }, $cleanParts); Chris@0: $export = implode('."\n".', $cleanParts); Chris@0: } else { Chris@0: $export = var_export($value, true); Chris@0: } Chris@0: Chris@0: if ($resolveEnv && "'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('string:%s').'")) { Chris@0: $export = $resolvedExport; Chris@0: if (".''" === substr($export, -3)) { Chris@0: $export = substr($export, 0, -3); Chris@0: if ("'" === $export[1]) { Chris@0: $export = substr_replace($export, '', 18, 7); Chris@0: } Chris@0: } 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: }