This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Components/DependencyInjection/Dumper/PhpDumper.php

501 lines
14 KiB
PHP
Raw Normal View History

2010-01-04 14:26:20 +00:00
<?php
namespace Symfony\Components\DependencyInjection\Dumper;
use Symfony\Components\DependencyInjection\Builder;
use Symfony\Components\DependencyInjection\Container;
use Symfony\Components\DependencyInjection\Reference;
use Symfony\Components\DependencyInjection\Parameter;
/*
* This file is part of the Symfony framework.
2010-01-04 14:26:20 +00:00
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* PhpDumper dumps a service container as a PHP class.
*
* @package Symfony
* @subpackage Components_DependencyInjection
2010-01-04 14:26:20 +00:00
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class PhpDumper extends Dumper
{
/**
* Dumps the service container as a PHP class.
*
* Available options:
*
* * class: The class name
* * base_class: The base class name
*
* @param array $options An array of options
*
* @return string A PHP class representing of the service container
*/
public function dump(array $options = array())
{
$options = array_merge(array(
'class' => 'ProjectServiceContainer',
'base_class' => 'Container',
), $options);
return
$this->startClass($options['class'], $options['base_class']).
$this->addConstructor().
$this->addServices().
$this->addAnnotations().
$this->addDefaultParametersMethod().
$this->endClass()
;
}
protected function addServiceInclude($id, $definition)
{
if (null !== $definition->getFile())
{
return sprintf(" require_once %s;\n\n", $this->dumpValue($definition->getFile()));
}
2010-01-04 14:26:20 +00:00
}
protected function addServiceShared($id, $definition)
2010-01-04 14:26:20 +00:00
{
if ($definition->isShared())
{
return <<<EOF
if (isset(\$this->shared['$id'])) return \$this->shared['$id'];
2010-01-04 14:26:20 +00:00
EOF;
}
2010-01-04 14:26:20 +00:00
}
protected function addServiceReturn($id, $definition)
{
return <<<EOF
2010-01-04 14:26:20 +00:00
return \$instance;
}
2010-01-04 14:26:20 +00:00
EOF;
}
protected function addServiceInstance($id, $definition)
2010-01-04 14:26:20 +00:00
{
$class = $this->dumpValue($definition->getClass());
$arguments = array();
foreach ($definition->getArguments() as $value)
{
$arguments[] = $this->dumpValue($value);
}
if (null !== $definition->getConstructor())
{
$code = sprintf(" \$instance = call_user_func(array(%s, '%s')%s);\n", $class, $definition->getConstructor(), $arguments ? ', '.implode(', ', $arguments) : '');
}
elseif ($class != "'".str_replace('\\', '\\\\', $definition->getClass())."'")
{
$code = sprintf(" \$class = %s;\n \$instance = new \$class(%s);\n", $class, implode(', ', $arguments));
}
else
{
$code = sprintf(" \$instance = new %s(%s);\n", $definition->getClass(), implode(', ', $arguments));
}
2010-01-04 14:26:20 +00:00
if ($definition->isShared())
{
$code .= sprintf(" \$this->shared['$id'] = \$instance;\n");
}
2010-01-04 14:26:20 +00:00
return $code;
2010-01-04 14:26:20 +00:00
}
protected function addServiceMethodCalls($id, $definition)
2010-01-04 14:26:20 +00:00
{
$calls = '';
foreach ($definition->getMethodCalls() as $call)
{
$arguments = array();
foreach ($call[1] as $value)
{
$arguments[] = $this->dumpValue($value);
}
2010-01-04 14:26:20 +00:00
$calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$instance->%s(%s);\n", $call[0], implode(', ', $arguments)));
}
2010-01-04 14:26:20 +00:00
return $calls;
}
2010-01-04 14:26:20 +00:00
protected function addServiceConfigurator($id, $definition)
2010-01-04 14:26:20 +00:00
{
if (!$callable = $definition->getConfigurator())
{
return '';
}
2010-01-04 14:26:20 +00:00
if (is_array($callable))
{
if (is_object($callable[0]) && $callable[0] instanceof Reference)
{
return sprintf(" %s->%s(\$instance);\n", $this->getServiceCall((string) $callable[0]), $callable[1]);
}
else
{
return sprintf(" call_user_func(array(%s, '%s'), \$instance);\n", $this->dumpValue($callable[0]), $callable[1]);
}
}
else
{
return sprintf(" %s(\$instance);\n", $callable);
}
2010-01-04 14:26:20 +00:00
}
protected function addService($id, $definition)
{
$name = Container::camelize($id);
$class = $definition->getClass();
$type = 0 === strpos($class, '%') ? 'Object' : $class;
2010-01-04 14:26:20 +00:00
$doc = '';
if ($definition->isShared())
{
$doc = <<<EOF
2010-01-04 14:26:20 +00:00
*
* This service is shared.
* This method always returns the same instance of the service.
2010-01-04 14:26:20 +00:00
EOF;
}
2010-01-04 14:26:20 +00:00
$code = <<<EOF
2010-01-04 14:26:20 +00:00
/**
* Gets the '$id' service.$doc
*
* @return $type A $class instance.
*/
protected function get{$name}Service()
{
2010-01-04 14:26:20 +00:00
EOF;
2010-01-04 14:26:20 +00:00
$code .=
$this->addServiceInclude($id, $definition).
$this->addServiceShared($id, $definition).
$this->addServiceInstance($id, $definition).
$this->addServiceMethodCalls($id, $definition).
$this->addServiceConfigurator($id, $definition).
$this->addServiceReturn($id, $definition)
;
return $code;
2010-01-04 14:26:20 +00:00
}
protected function addServiceAlias($alias, $id)
{
$name = Container::camelize($alias);
$type = 'Object';
2010-01-04 14:26:20 +00:00
if ($this->container->hasDefinition($id))
{
$class = $this->container->getDefinition($id)->getClass();
$type = 0 === strpos($class, '%') ? 'Object' : $class;
}
2010-01-04 14:26:20 +00:00
return <<<EOF
2010-01-04 14:26:20 +00:00
/**
* Gets the $alias service alias.
*
* @return $type An instance of the $id service
*/
protected function get{$name}Service()
2010-01-04 14:26:20 +00:00
{
return {$this->getServiceCall($id)};
2010-01-04 14:26:20 +00:00
}
EOF;
2010-01-04 14:26:20 +00:00
}
protected function addServices()
{
$code = '';
foreach ($this->container->getDefinitions() as $id => $definition)
{
$code .= $this->addService($id, $definition);
}
foreach ($this->container->getAliases() as $alias => $id)
{
$code .= $this->addServiceAlias($alias, $id);
}
return $code;
}
protected function addAnnotations()
{
$annotations = array();
foreach ($this->container->getDefinitions() as $id => $definition)
{
foreach ($definition->getAnnotations() as $name => $ann)
{
if (!isset($annotations[$name]))
{
$annotations[$name] = array();
}
$annotations[$name][$id] = $ann;
}
}
$annotations = var_export($annotations, true);
return <<<EOF
/**
* Returns service ids for a given annotation.
*
* @param string \$name The annotation name
*
* @return array An array of annotations
*/
public function findAnnotatedServiceIds(\$name)
2010-01-04 14:26:20 +00:00
{
static \$annotations = $annotations;
return isset(\$annotations[\$name]) ? \$annotations[\$name] : array();
2010-01-04 14:26:20 +00:00
}
EOF;
2010-01-04 14:26:20 +00:00
}
protected function startClass($class, $baseClass)
2010-01-04 14:26:20 +00:00
{
$properties = array();
foreach ($this->container->getDefinitions() as $id => $definition)
{
$type = 0 === strpos($definition->getClass(), '%') ? 'Object' : $definition->getClass();
$properties[] = sprintf(' * @property %s $%s', $type, $id);
}
foreach ($this->container->getAliases() as $alias => $id)
{
$type = 'Object';
if ($this->container->hasDefinition($id))
{
$sclass = $this->container->getDefinition($id)->getClass();
$type = 0 === strpos($sclass, '%') ? 'Object' : $sclass;
}
$properties[] = sprintf(' * @property %s $%s', $type, $alias);
}
$properties = implode("\n", $properties);
if ($properties)
{
$properties = "\n *\n".$properties;
}
2010-01-04 14:26:20 +00:00
return <<<EOF
2010-01-04 14:26:20 +00:00
<?php
use Symfony\Components\DependencyInjection\Container;
use Symfony\Components\DependencyInjection\Reference;
use Symfony\Components\DependencyInjection\Parameter;
/**
* $class
*
* This class has been auto-generated
* by the Symfony Dependency Injection Component.$properties
*/
class $class extends $baseClass
{
protected \$shared = array();
2010-01-04 14:26:20 +00:00
EOF;
}
2010-01-04 14:26:20 +00:00
protected function addConstructor()
2010-01-04 14:26:20 +00:00
{
if (!$this->container->getParameters())
{
return '';
}
2010-01-04 14:26:20 +00:00
return <<<EOF
2010-01-04 14:26:20 +00:00
/**
* Constructor.
*/
public function __construct()
{
parent::__construct();
\$this->parameters = \$this->getDefaultParameters();
}
2010-01-04 14:26:20 +00:00
EOF;
}
protected function addDefaultParametersMethod()
{
if (!$this->container->getParameters())
{
return '';
}
2010-01-04 14:26:20 +00:00
$parameters = $this->exportParameters($this->container->getParameters());
2010-01-04 14:26:20 +00:00
return <<<EOF
2010-01-04 14:26:20 +00:00
/**
* Gets the default parameters.
*
* @return array An array of the default parameters
*/
protected function getDefaultParameters()
2010-01-04 14:26:20 +00:00
{
return $parameters;
2010-01-04 14:26:20 +00:00
}
EOF;
}
protected function exportParameters($parameters, $indent = 12)
2010-01-04 14:26:20 +00:00
{
$php = array();
foreach ($parameters as $key => $value)
{
if (is_array($value))
{
$value = $this->exportParameters($value, $indent + 4);
}
elseif ($value instanceof Reference)
{
throw new \InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service %s found).', $value));
}
else
{
$value = var_export($value, true);
}
$php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), var_export($key, true), $value);
}
2010-01-04 14:26:20 +00:00
return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4));
}
2010-01-04 14:26:20 +00:00
protected function endClass()
2010-01-04 14:26:20 +00:00
{
return <<<EOF
}
2010-01-04 14:26:20 +00:00
EOF;
2010-01-04 14:26:20 +00:00
}
protected function wrapServiceConditionals($value, $code)
2010-01-04 14:26:20 +00:00
{
if (!$services = Builder::getServiceConditionals($value))
2010-01-04 14:26:20 +00:00
{
return $code;
}
2010-01-04 14:26:20 +00:00
$conditions = array();
foreach ($services as $service)
{
$conditions[] = sprintf("\$this->hasService('%s')", $service);
}
2010-01-04 14:26:20 +00:00
// re-indent the wrapped code
$code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
2010-01-04 14:26:20 +00:00
return sprintf(" if (%s)\n {\n%s }\n", implode(' && ', $conditions), $code);
2010-01-04 14:26:20 +00:00
}
protected function dumpValue($value)
2010-01-04 14:26:20 +00:00
{
if (is_array($value))
{
$code = array();
foreach ($value as $k => $v)
{
$code[] = sprintf('%s => %s', $this->dumpValue($k), $this->dumpValue($v));
}
2010-01-04 14:26:20 +00:00
return sprintf('array(%s)', implode(', ', $code));
}
elseif (is_object($value) && $value instanceof Reference)
{
return $this->getServiceCall((string) $value, $value);
}
elseif (is_object($value) && $value instanceof Parameter)
{
return sprintf("\$this->getParameter('%s')", strtolower($value));
}
elseif (is_string($value))
{
if (preg_match('/^%([^%]+)%$/', $value, $match))
{
// we do this to deal with non string values (boolean, integer, ...)
// the preg_replace_callback converts them to strings
return sprintf("\$this->getParameter('%s')", strtolower($match[1]));
}
else
{
$replaceParameters = function ($match)
{
return sprintf("'.\$this->getParameter('%s').'", strtolower($match[2]));
};
$code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, var_export($value, true)));
// optimize string
$code = preg_replace(array("/^''\./", "/\.''$/", "/\.''\./"), array('', '', '.'), $code);
return $code;
}
}
elseif (is_object($value) || is_resource($value))
{
throw new \RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
}
else
{
return var_export($value, true);
}
2010-01-04 14:26:20 +00:00
}
protected function getServiceCall($id, Reference $reference = null)
2010-01-04 14:26:20 +00:00
{
if ('service_container' === $id)
{
return '$this';
}
if (null !== $reference && Container::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior())
{
return sprintf('$this->getService(\'%s\', Container::NULL_ON_INVALID_REFERENCE)', $id);
}
else
{
if ($this->container->hasAlias($id))
{
$id = $this->container->getAlias($id);
}
if ($this->container->hasDefinition($id))
{
return sprintf('$this->get%sService()', Container::camelize($id));
}
return sprintf('$this->getService(\'%s\')', $id);
}
2010-01-04 14:26:20 +00:00
}
}