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\Variable; Chris@0: use Symfony\Component\DependencyInjection\Definition; 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\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: * @var string 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: * @var string Chris@0: */ Chris@0: const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_'; Chris@0: Chris@0: private $inlinedDefinitions; 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: Chris@0: /** Chris@0: * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface 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: parent::__construct($container); Chris@0: Chris@0: $this->inlinedDefinitions = new \SplObjectStorage(); 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: * @param ProxyDumper $proxyDumper 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: * Chris@0: * @param array $options An array of options Chris@0: * Chris@0: * @return string A PHP class representing of the service container 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: $options = array_merge(array( Chris@0: 'class' => 'ProjectServiceContainer', Chris@0: 'base_class' => 'Container', Chris@0: 'namespace' => '', Chris@0: 'debug' => true, Chris@0: ), $options); Chris@0: Chris@0: $this->initializeMethodNamesMap($options['base_class']); 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 = $this->startClass($options['class'], $options['base_class'], $options['namespace']); Chris@0: Chris@0: if ($this->container->isFrozen()) { Chris@0: $code .= $this->addFrozenConstructor(); Chris@0: $code .= $this->addFrozenCompile(); Chris@0: $code .= $this->addIsFrozenMethod(); Chris@0: } else { Chris@0: $code .= $this->addConstructor(); Chris@0: } Chris@0: Chris@0: $code .= Chris@0: $this->addServices(). Chris@0: $this->addDefaultParametersMethod(). Chris@0: $this->endClass(). Chris@0: $this->addProxyClasses() Chris@0: ; Chris@0: $this->targetDirRegex = null; 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); 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: * @param string $cId Chris@0: * @param string $definition Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addServiceLocalTempVariables($cId, $definition) Chris@0: { Chris@0: static $template = " \$%s = %s;\n"; Chris@0: Chris@0: $localDefinitions = array_merge( Chris@0: array($definition), Chris@0: $this->getInlinedDefinitions($definition) Chris@0: ); Chris@0: Chris@0: $calls = $behavior = array(); Chris@0: foreach ($localDefinitions as $iDefinition) { Chris@0: $this->getServiceCallsFromArguments($iDefinition->getArguments(), $calls, $behavior); Chris@0: $this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior); Chris@0: $this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior); Chris@0: $this->getServiceCallsFromArguments(array($iDefinition->getConfigurator()), $calls, $behavior); Chris@0: $this->getServiceCallsFromArguments(array($iDefinition->getFactory()), $calls, $behavior); Chris@0: } Chris@0: Chris@0: $code = ''; Chris@0: foreach ($calls as $id => $callCount) { Chris@0: if ('service_container' === $id || $id === $cId) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($callCount > 1) { Chris@0: $name = $this->getNextVariableName(); Chris@0: $this->referenceVariables[$id] = new Variable($name); Chris@0: Chris@0: if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id]) { Chris@0: $code .= sprintf($template, $name, $this->getServiceCall($id)); Chris@0: } else { Chris@0: $code .= sprintf($template, $name, $this->getServiceCall($id, new Reference($id, ContainerInterface::NULL_ON_INVALID_REFERENCE))); Chris@0: } 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 code for the proxies to be attached after the container class. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addProxyClasses() Chris@0: { Chris@0: /* @var $definitions Definition[] */ Chris@0: $definitions = array_filter( Chris@0: $this->container->getDefinitions(), Chris@0: array($this->getProxyDumper(), 'isProxyCandidate') Chris@0: ); Chris@0: $code = ''; Chris@0: $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments'); Chris@0: Chris@0: foreach ($definitions as $definition) { Chris@0: $proxyCode = "\n".$this->getProxyDumper()->getProxyCode($definition); Chris@0: if ($strip) { Chris@0: $proxyCode = "getFile()) { Chris@0: $code .= sprintf($template, $this->dumpValue($file)); Chris@0: } Chris@0: Chris@0: foreach ($this->getInlinedDefinitions($definition) as $definition) { Chris@0: if (null !== $file = $definition->getFile()) { Chris@0: $code .= sprintf($template, $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: * @param string $id Chris@0: * @param Definition $definition 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) Chris@0: { Chris@0: $code = ''; Chris@0: $variableMap = $this->definitionVariables; Chris@0: $nbOccurrences = new \SplObjectStorage(); Chris@0: $processed = new \SplObjectStorage(); Chris@0: $inlinedDefinitions = $this->getInlinedDefinitions($definition); Chris@0: Chris@0: foreach ($inlinedDefinitions as $definition) { Chris@0: if (false === $nbOccurrences->contains($definition)) { Chris@0: $nbOccurrences->offsetSet($definition, 1); Chris@0: } else { Chris@0: $i = $nbOccurrences->offsetGet($definition); Chris@0: $nbOccurrences->offsetSet($definition, $i + 1); Chris@0: } Chris@0: } Chris@0: Chris@0: foreach ($inlinedDefinitions as $sDefinition) { Chris@0: if ($processed->contains($sDefinition)) { Chris@0: continue; Chris@0: } Chris@0: $processed->offsetSet($sDefinition); Chris@0: Chris@0: $class = $this->dumpValue($sDefinition->getClass()); Chris@0: if ($nbOccurrences->offsetGet($sDefinition) > 1 || $sDefinition->getMethodCalls() || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) { Chris@0: $name = $this->getNextVariableName(); Chris@0: $variableMap->offsetSet($sDefinition, new Variable($name)); 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 ($this->hasReference($id, $sDefinition->getArguments())) { Chris@0: throw new ServiceCircularReferenceException($id, array($id)); Chris@0: } Chris@0: Chris@0: $code .= $this->addNewInstance($sDefinition, '$'.$name, ' = ', $id); Chris@0: Chris@0: if (!$this->hasReference($id, $sDefinition->getMethodCalls(), true) && !$this->hasReference($id, $sDefinition->getProperties(), true)) { Chris@0: $code .= $this->addServiceProperties(null, $sDefinition, $name); Chris@0: $code .= $this->addServiceMethodCalls(null, $sDefinition, $name); Chris@0: $code .= $this->addServiceConfigurator(null, $sDefinition, $name); Chris@0: } Chris@0: Chris@0: $code .= "\n"; Chris@0: } Chris@0: } Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the service return statement. Chris@0: * Chris@0: * @param string $id Service id Chris@0: * @param Definition $definition Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addServiceReturn($id, $definition) Chris@0: { Chris@0: if ($this->isSimpleInstance($id, $definition)) { Chris@0: return " }\n"; Chris@0: } Chris@0: Chris@0: return "\n return \$instance;\n }\n"; 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: * Chris@0: * @return string Chris@0: * Chris@0: * @throws InvalidArgumentException Chris@0: * @throws RuntimeException Chris@0: */ Chris@0: private function addServiceInstance($id, Definition $definition) Chris@0: { Chris@0: $class = $definition->getClass(); Chris@0: Chris@0: if ('\\' === substr($class, 0, 1)) { Chris@0: $class = substr($class, 1); Chris@0: } Chris@0: Chris@0: $class = $this->dumpValue($class); Chris@0: Chris@0: if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'[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: $simple = $this->isSimpleInstance($id, $definition); Chris@0: $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); Chris@0: $instantiation = ''; Chris@0: Chris@0: if (!$isProxyCandidate && $definition->isShared()) { Chris@0: $instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance'); Chris@0: } elseif (!$simple) { Chris@0: $instantiation = '$instance'; Chris@0: } Chris@0: Chris@0: $return = ''; Chris@0: if ($simple) { 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 (!$simple) { 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 simple instance. Chris@0: * Chris@0: * @param string $id Chris@0: * @param Definition $definition Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: private function isSimpleInstance($id, Definition $definition) Chris@0: { Chris@0: foreach (array_merge(array($definition), $this->getInlinedDefinitions($definition)) as $sDefinition) { Chris@0: if ($definition !== $sDefinition && !$this->hasReference($id, $sDefinition->getMethodCalls())) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if ($sDefinition->getMethodCalls() || $sDefinition->getProperties() || $sDefinition->getConfigurator()) { 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 string $id Chris@0: * @param Definition $definition Chris@0: * @param string $variableName Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addServiceMethodCalls($id, 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($id, 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: * @param string $id Chris@0: * @param Definition $definition 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) Chris@0: { Chris@0: $this->referenceVariables[$id] = new Variable('instance'); Chris@0: Chris@0: $code = ''; Chris@0: $processed = new \SplObjectStorage(); Chris@0: foreach ($this->getInlinedDefinitions($definition) as $iDefinition) { Chris@0: if ($processed->contains($iDefinition)) { Chris@0: continue; Chris@0: } Chris@0: $processed->offsetSet($iDefinition); Chris@0: Chris@0: if (!$this->hasReference($id, $iDefinition->getMethodCalls(), true) && !$this->hasReference($id, $iDefinition->getProperties(), 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 ($this->isSimpleInstance($id, $definition)) { Chris@0: throw new ServiceCircularReferenceException($id, array($id)); Chris@0: } Chris@0: Chris@0: $name = (string) $this->definitionVariables->offsetGet($iDefinition); Chris@0: $code .= $this->addServiceProperties(null, $iDefinition, $name); Chris@0: $code .= $this->addServiceMethodCalls(null, $iDefinition, $name); Chris@0: $code .= $this->addServiceConfigurator(null, $iDefinition, $name); 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: * Adds configurator definition. Chris@0: * Chris@0: * @param string $id Chris@0: * @param Definition $definition Chris@0: * @param string $variableName Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addServiceConfigurator($id, 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: * Chris@0: * @return string Chris@0: */ Chris@0: private function addService($id, Definition $definition) 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 ($definition->isSynthetic()) { Chris@0: $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically'; Chris@0: } elseif ($class = $definition->getClass()) { Chris@0: $class = $this->container->resolveEnvPlaceholders($class); Chris@0: $return[] = sprintf('@return %s A %s instance', 0 === strpos($class, '%') ? 'object' : '\\'.ltrim($class, '\\'), 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: $doc = ''; Chris@0: if ($definition->isShared()) { Chris@0: $doc .= <<<'EOF' Chris@0: Chris@0: * Chris@0: * This service is shared. Chris@0: * This method always returns the same instance of the service. Chris@0: EOF; Chris@0: } Chris@0: Chris@0: if (!$definition->isPublic()) { Chris@0: $doc .= <<<'EOF' Chris@0: Chris@0: * Chris@0: * This service is private. Chris@0: * If you want to be able to request this service from the container directly, Chris@0: * make it public, otherwise you might end up with broken code. Chris@0: EOF; Chris@0: } Chris@0: Chris@0: if ($definition->isAutowired()) { Chris@0: $doc .= <<isLazy()) { Chris@0: $lazyInitialization = '$lazyLoad = true'; Chris@0: $lazyInitializationDoc = "\n * @param bool \$lazyLoad whether to try lazy-loading the service with a proxy\n *"; Chris@0: } else { Chris@0: $lazyInitialization = ''; Chris@0: $lazyInitializationDoc = ''; Chris@0: } Chris@0: Chris@0: // with proxies, for 5.3.3 compatibility, the getter must be public to be accessible to the initializer Chris@0: $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); Chris@0: $visibility = $isProxyCandidate ? 'public' : 'protected'; Chris@0: $methodName = $this->generateMethodName($id); Chris@0: $code = <<docStar} Chris@0: * Gets the '$id' service.$doc Chris@0: *$lazyInitializationDoc Chris@0: * $return Chris@0: */ Chris@0: {$visibility} function {$methodName}($lazyInitialization) Chris@0: { Chris@0: Chris@0: EOF; Chris@0: Chris@0: $code .= $isProxyCandidate ? $this->getProxyDumper()->getProxyFactoryCode($definition, $id, $methodName) : ''; Chris@0: Chris@0: if ($definition->isSynthetic()) { Chris@0: $code .= sprintf(" throw new RuntimeException('You have requested a synthetic service (\"%s\"). The DIC does not know how to construct this service.');\n }\n", $id); Chris@0: } else { 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: $code .= Chris@0: $this->addServiceInclude($id, $definition). Chris@0: $this->addServiceLocalTempVariables($id, $definition). Chris@0: $this->addServiceInlinedDefinitions($id, $definition). Chris@0: $this->addServiceInstance($id, $definition). Chris@0: $this->addServiceInlinedDefinitionsSetup($id, $definition). Chris@0: $this->addServiceProperties($id, $definition). Chris@0: $this->addServiceMethodCalls($id, $definition). Chris@0: $this->addServiceConfigurator($id, $definition). Chris@0: $this->addServiceReturn($id, $definition) Chris@0: ; 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->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 addNewInstance(Definition $definition, $return, $instantiation, $id) Chris@0: { Chris@0: $class = $this->dumpValue($definition->getClass()); 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 sprintf(" $return{$instantiation}%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 sprintf(" $return{$instantiation}%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 sprintf(" $return{$instantiation}(%s)->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? ', '.implode(', ', $arguments) : ''); Chris@0: } Chris@0: Chris@0: return sprintf(" $return{$instantiation}%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 $return{$instantiation}new \$class(%s);\n", $class, implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: return sprintf(" $return{$instantiation}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 $namespace The class namespace Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function startClass($class, $baseClass, $namespace) Chris@0: { Chris@0: $bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;'; Chris@0: $namespaceLine = $namespace ? "namespace $namespace;\n" : ''; Chris@0: Chris@0: return <<docStar} Chris@0: * $class. Chris@0: * Chris@0: * This class has been auto-generated Chris@0: * by the Symfony Dependency Injection Component. Chris@0: */ Chris@0: class $class extends $baseClass Chris@0: { Chris@0: private \$parameters; Chris@0: private \$targetDirs = array(); Chris@0: Chris@0: EOF; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the constructor. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addConstructor() Chris@0: { Chris@0: $targetDirs = $this->exportTargetDirs(); Chris@0: $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null; Chris@0: Chris@0: $code = <<docStar} Chris@0: * Constructor. Chris@0: */ Chris@0: public function __construct() Chris@0: {{$targetDirs} Chris@0: parent::__construct($arguments); Chris@0: Chris@0: EOF; Chris@0: Chris@0: $code .= $this->addMethodMap(); Chris@0: $code .= $this->addPrivateServices(); Chris@0: $code .= $this->addAliases(); Chris@0: Chris@0: $code .= <<<'EOF' Chris@0: } Chris@0: Chris@0: EOF; Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the constructor for a frozen container. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addFrozenConstructor() Chris@0: { Chris@0: $targetDirs = $this->exportTargetDirs(); Chris@0: Chris@0: $code = <<docStar} Chris@0: * Constructor. Chris@0: */ Chris@0: public function __construct() Chris@0: {{$targetDirs} Chris@0: EOF; Chris@0: Chris@0: if ($this->container->getParameterBag()->all()) { Chris@0: $code .= "\n \$this->parameters = \$this->getDefaultParameters();\n"; Chris@0: } Chris@0: Chris@0: $code .= "\n \$this->services = array();\n"; Chris@0: $code .= $this->addMethodMap(); Chris@0: $code .= $this->addPrivateServices(); Chris@0: $code .= $this->addAliases(); Chris@0: Chris@0: $code .= <<<'EOF' Chris@0: } Chris@0: Chris@0: EOF; Chris@0: Chris@0: return $code; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the constructor for a frozen container. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addFrozenCompile() Chris@0: { Chris@0: return <<docStar} Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function compile() Chris@0: { Chris@0: throw new LogicException('You cannot compile a dumped frozen container.'); Chris@0: } Chris@0: Chris@0: EOF; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the isFrozen method for a frozen container. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addIsFrozenMethod() Chris@0: { Chris@0: return <<docStar} Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function isFrozen() Chris@0: { Chris@0: return true; Chris@0: } Chris@0: Chris@0: EOF; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds the methodMap property definition. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: private function addMethodMap() Chris@0: { Chris@0: if (!$definitions = $this->container->getDefinitions()) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: $code = " \$this->methodMap = array(\n"; Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: $code .= ' '.$this->export($id).' => '.$this->export($this->generateMethodName($id)).",\n"; Chris@0: } Chris@0: Chris@0: return $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: if (!$definitions = $this->container->getDefinitions()) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: $code = ''; Chris@0: ksort($definitions); Chris@0: foreach ($definitions as $id => $definition) { Chris@0: if (!$definition->isPublic()) { Chris@0: $code .= ' '.$this->export($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->isFrozen() ? "\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 = (string) $id; Chris@0: while (isset($aliases[$id])) { Chris@0: $id = (string) $aliases[$id]; Chris@0: } Chris@0: $code .= ' '.$this->export($alias).' => '.$this->export($id).",\n"; Chris@0: } Chris@0: Chris@0: return $code." );\n"; 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: 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: $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++'\)|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->isFrozen()) { Chris@0: $code .= <<<'EOF' Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getParameter($name) Chris@0: { Chris@0: $name = strtolower($name); Chris@0: Chris@0: if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters) || isset($this->loadedDynamicParameters[$name]))) { Chris@0: throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); 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: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function hasParameter($name) Chris@0: { Chris@0: $name = strtolower($name); Chris@0: Chris@0: return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters) || isset($this->loadedDynamicParameters[$name]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} 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: /** Chris@0: * {@inheritdoc} 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: $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->docStar) { Chris@0: $code = str_replace('/**', '/*', $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: 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 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 (!$services = ContainerBuilder::getServiceConditionals($value)) { Chris@0: return $code; Chris@0: } Chris@0: Chris@0: $conditions = array(); Chris@0: foreach ($services as $service) { Chris@0: $conditions[] = sprintf("\$this->has('%s')", $service); 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", implode(' && ', $conditions), $code); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Builds service calls from arguments. Chris@0: * Chris@0: * @param array $arguments Chris@0: * @param array &$calls By reference Chris@0: * @param array &$behavior By reference Chris@0: */ Chris@0: private function getServiceCallsFromArguments(array $arguments, array &$calls, array &$behavior) Chris@0: { Chris@0: foreach ($arguments as $argument) { Chris@0: if (is_array($argument)) { Chris@0: $this->getServiceCallsFromArguments($argument, $calls, $behavior); Chris@0: } elseif ($argument instanceof Reference) { Chris@0: $id = (string) $argument; Chris@0: Chris@0: if (!isset($calls[$id])) { Chris@0: $calls[$id] = 0; Chris@0: } Chris@0: if (!isset($behavior[$id])) { Chris@0: $behavior[$id] = $argument->getInvalidBehavior(); Chris@0: } elseif (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) { Chris@0: $behavior[$id] = $argument->getInvalidBehavior(); Chris@0: } Chris@0: Chris@0: ++$calls[$id]; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the inline definition. Chris@0: * Chris@0: * @param Definition $definition Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: private function getInlinedDefinitions(Definition $definition) Chris@0: { Chris@0: if (false === $this->inlinedDefinitions->contains($definition)) { Chris@0: $definitions = array_merge( Chris@0: $this->getDefinitionsFromArguments($definition->getArguments()), Chris@0: $this->getDefinitionsFromArguments($definition->getMethodCalls()), Chris@0: $this->getDefinitionsFromArguments($definition->getProperties()), Chris@0: $this->getDefinitionsFromArguments(array($definition->getConfigurator())), Chris@0: $this->getDefinitionsFromArguments(array($definition->getFactory())) Chris@0: ); Chris@0: Chris@0: $this->inlinedDefinitions->offsetSet($definition, $definitions); Chris@0: Chris@0: return $definitions; Chris@0: } Chris@0: Chris@0: return $this->inlinedDefinitions->offsetGet($definition); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the definition from arguments. Chris@0: * Chris@0: * @param array $arguments Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: private function getDefinitionsFromArguments(array $arguments) Chris@0: { Chris@0: $definitions = array(); Chris@0: foreach ($arguments as $argument) { Chris@0: if (is_array($argument)) { Chris@0: $definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument)); Chris@0: } elseif ($argument instanceof Definition) { Chris@0: $definitions = array_merge( Chris@0: $definitions, Chris@0: $this->getInlinedDefinitions($argument), Chris@0: array($argument) Chris@0: ); 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: 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: } elseif ($argument instanceof Reference) { Chris@0: $argumentId = (string) $argument; Chris@0: if ($id === $argumentId) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: if ($deep && !isset($visited[$argumentId]) && 'service_container' !== $argumentId) { Chris@0: $visited[$argumentId] = true; Chris@0: Chris@0: $service = $this->container->getDefinition($argumentId); 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: $arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties()); Chris@0: Chris@0: if ($this->hasReference($id, $arguments, $deep, $visited)) { Chris@0: return true; Chris@0: } Chris@0: } 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: $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 Definition) { Chris@0: if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { Chris@0: return $this->dumpValue($this->definitionVariables->offsetGet($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: if (is_string($factory[0])) { Chris@0: return sprintf('%s::%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory[0])), $factory[1], implode(', ', $arguments)); Chris@0: } Chris@0: Chris@0: if ($factory[0] instanceof Definition) { Chris@0: return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($factory[0]), $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)', $this->dumpValue($factory[0]), $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: if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) { Chris@0: return $this->dumpValue($this->referenceVariables[$id], $interpolate); Chris@0: } Chris@0: Chris@0: return $this->getServiceCall((string) $value, $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(strtolower($match[1])); Chris@0: } else { Chris@0: $replaceParameters = function ($match) { Chris@0: return "'.".$this->dumpParameter(strtolower($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('/^\'[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: return '\\'.substr(str_replace('\\\\', '\\', $class), 1, -1); 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->isFrozen() && $this->container->hasParameter($name)) { Chris@0: return $this->dumpValue($this->container->getParameter($name), false); Chris@0: } Chris@0: Chris@0: return sprintf("\$this->getParameter('%s')", strtolower($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: if ('service_container' === $id) { Chris@0: return '$this'; Chris@0: } Chris@0: Chris@0: if ($this->container->hasDefinition($id) && !$this->container->getDefinition($id)->isPublic()) { Chris@0: // The following is PHP 5.5 syntax for what could be written as "(\$this->services['$id'] ?? \$this->{$this->generateMethodName($id)}())" on PHP>=7.0 Chris@0: Chris@0: return "\${(\$_ = isset(\$this->services['$id']) ? \$this->services['$id'] : \$this->{$this->generateMethodName($id)}()) && false ?: '_'}"; Chris@0: } Chris@0: if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { Chris@0: return sprintf('$this->get(\'%s\', ContainerInterface::NULL_ON_INVALID_REFERENCE)', $id); Chris@0: } Chris@0: Chris@0: if ($this->container->hasAlias($id)) { Chris@0: $id = (string) $this->container->getAlias($id); Chris@0: } Chris@0: Chris@0: return sprintf('$this->get(\'%s\')', $id); 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: try { Chris@0: $reflectionClass = new \ReflectionClass($class); Chris@0: foreach ($reflectionClass->getMethods() as $method) { Chris@0: $this->usedMethodNames[strtolower($method->getName())] = true; Chris@0: } Chris@0: } catch (\ReflectionException $e) { 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: $name = Container::camelize($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); 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 exportTargetDirs() Chris@0: { Chris@0: return null === $this->targetDirRegex ? '' : <<targetDirMaxMatches}; ++\$i) { Chris@0: \$this->targetDirs[\$i] = \$dir = dirname(\$dir); Chris@0: } Chris@0: EOF; 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])).'.' : ''; Chris@0: $suffix = $matches[0][1] + strlen($matches[0][0]); Chris@0: $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix)) : ''; Chris@0: $dirname = '__DIR__'; Chris@0: Chris@0: if (0 < $offset = 1 + $this->targetDirMaxMatches - count($matches)) { 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); Chris@0: } Chris@0: Chris@0: private function doExport($value) Chris@0: { Chris@0: $export = var_export($value, true); Chris@0: Chris@0: if ("'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('%s').'")) { Chris@0: $export = $resolvedExport; Chris@0: if ("'" === $export[1]) { Chris@0: $export = substr($export, 3); Chris@0: } Chris@0: if (".''" === substr($export, -3)) { Chris@0: $export = substr($export, 0, -3); Chris@0: } Chris@0: } Chris@0: Chris@0: return $export; Chris@0: } Chris@0: }