Skip to content

[2.1] Method Injection #881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public function process(ContainerBuilder $container)
if (!$this->onlyConstructorArguments) {
$this->processArguments($definition->getMethodCalls());
$this->processArguments($definition->getProperties());
$this->processArguments($definition->getLookupMethods());
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference;

/**
* Generates the classes which implement the requested lookup methods.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class GenerateLookupMethodClassesPass implements CompilerPassInterface
{
private $generatedClasses = array();
private $container;
private $currentId;
private $cacheDir;

public function __construct($cacheDir)
{
$this->cacheDir = $cacheDir;
}

public function process(ContainerBuilder $container)
{
$this->container = $container;
$this->generatedClasses = array();
$this->cleanUpCacheDir($this->cacheDir);

foreach ($container->getDefinitions() as $id => $definition) {
if ($definition->isSynthetic() || $definition->isAbstract()) {
continue;
}
if (!$methods = $definition->getLookupMethods()) {
continue;
}

$this->currentId = $id;
$this->generateClass($definition, $this->cacheDir);
}
}

private function cleanUpCacheDir($dir)
{
if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true)) {
throw new \RuntimeException(sprintf('The cache directory "%s" could not be created.', $dir));
}

return;
}

if (!is_writable($dir)) {
throw new \RuntimeException(sprintf('The cache directory "%s" is not writable.', $dir));
}

foreach (new \DirectoryIterator($dir) as $file) {
if ('.' === $file->getFileName() || !is_file($file->getPathName())) {
continue;
}

if (false === @unlink($file->getPathName())) {
throw new \RuntimeException(sprintf('Could not delete auto-generated file "%s".', $file->getPathName()));
}
}
}

private function generateClass(Definition $definition, $cacheDir)
{
$code = <<<'EOF'
<?php

namespace Symfony\Component\DependencyInjection\LookupMethodClasses;
%s
/**
* This class has been auto-generated by the Symfony Dependency Injection
* Component.
*
* Manual changes to it will be lost.
*
* You can modify this class by changing your "lookup_method" configuration
* for service "%s".
*/
class %s extends \%s
{
private $__symfonyDependencyInjectionContainer;
%s
}
EOF;

// other file requirement
if ($file = $definition->getFile()) {
$require = sprintf("\nrequire_once %s;\n", var_export($file, true));
} else {
$require = '';
}

// get class name
$class = new \ReflectionClass($definition->getClass());
$i = 1;
do {
$className = $class->getShortName();

if ($i > 1) {
$className .= '_'.$i;
}

$i += 1;
} while (isset($this->generatedClasses[$className]));
$this->generatedClasses[$className] = true;

$lookupMethod = <<<'EOF'

%s function %s()
{
return %s;
}
EOF;
$lookupMethods = '';
foreach ($definition->getLookupMethods() as $name => $value) {
if (!$class->hasMethod($name)) {
throw new \RuntimeException(sprintf('The class "%s" has no method named "%s".', $class->getName(), $name));
}
$method = $class->getMethod($name);
if ($method->isFinal()) {
throw new \RuntimeException(sprintf('The method "%s::%s" is marked as final and cannot be declared as lookup-method.', $class->getName(), $name));
}
if ($method->isPrivate()) {
throw new \RuntimeException(sprintf('The method "%s::%s" is marked as private and cannot be declared as lookup-method.', $class->getName(), $name));
}
if ($method->getParameters()) {
throw new \RuntimeException(sprintf('The method "%s::%s" must have a no-arguments signature if you want to use it as lookup-method.', $class->getName(), $name));
}

$lookupMethods .= sprintf($lookupMethod,
$method->isPublic() ? 'public' : 'protected',
$name,
$this->dumpValue($value)
);
}

$code = sprintf($code, $require, $this->currentId, $className, $class->getName(), $lookupMethods);
file_put_contents($cacheDir.'/'.$className.'.php', $code);
require_once $cacheDir.'/'.$className.'.php';
$definition->setClass('Symfony\Component\DependencyInjection\LookupMethodClasses\\'.$className);
$definition->setFile($cacheDir.'/'.$className.'.php');
$definition->setProperty('__symfonyDependencyInjectionContainer', new Reference('service_container'));
$definition->setLookupMethods(array());
}

private function dumpValue($value)
{
if ($value instanceof Parameter) {
return var_export($this->container->getParameter((string) $value), true);
} else if ($value instanceof Reference) {
$id = (string) $value;
if ($this->container->hasAlias($id)) {
$this->container->setAlias($id, (string) $this->container->getAlias());
} else if ($this->container->hasDefinition($id)) {
$this->container->getDefinition($id)->setPublic(true);
}

return '$this->__symfonyDependencyInjectionContainer->get('.var_export($id, true).', '.var_export($value->getInvalidBehavior(), true).')';
} else if (is_array($value) || is_scalar($value) || null === $value) {
return var_export($value, true);
}

throw new \RuntimeException(sprintf('Invalid value for lookup method of service "%s": %s', $this->currentId, json_encode($value)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ private function resolveDefinition($id, DefinitionDecorator $definition)
$def->setArguments($parentDef->getArguments());
$def->setMethodCalls($parentDef->getMethodCalls());
$def->setProperties($parentDef->getProperties());
$def->setLookupMethods($parentDef->getLookupMethods());
$def->setFactoryClass($parentDef->getFactoryClass());
$def->setFactoryMethod($parentDef->getFactoryMethod());
$def->setFactoryService($parentDef->getFactoryService());
Expand Down Expand Up @@ -119,6 +120,11 @@ private function resolveDefinition($id, DefinitionDecorator $definition)
$def->setProperty($k, $v);
}

// merge lookup methods
foreach ($definition->getLookupMethods() as $k => $v) {
$def->setLookupMethod($k, $v);
}

// append method calls
if (count($calls = $definition->getMethodCalls()) > 0) {
$def->setMethodCalls(array_merge($def->getMethodCalls(), $calls));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public function process(ContainerBuilder $container)
$definition->setArguments(
$this->processArguments($definition->getArguments())
);
$definition->setLookupMethods(
$this->processArguments($definition->getLookupMethods())
);

$calls = array();
foreach ($definition->getMethodCalls() as $call) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public function process(ContainerBuilder $container)
$definition->setArguments($this->processArguments($definition->getArguments()));
$definition->setMethodCalls($this->processArguments($definition->getMethodCalls()));
$definition->setProperties($this->processArguments($definition->getProperties()));
$definition->setLookupMethods($this->processArguments($definition->getLookupMethods()));
}

foreach ($container->getAliases() as $id => $alias) {
Expand Down
22 changes: 22 additions & 0 deletions src/Symfony/Component/DependencyInjection/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* Definition represents a service definition.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class Definition
{
Expand All @@ -31,6 +32,7 @@ class Definition
private $public;
private $synthetic;
private $abstract;
private $lookupMethods;

protected $arguments;

Expand All @@ -51,6 +53,7 @@ public function __construct($class = null, array $arguments = array())
$this->synthetic = false;
$this->abstract = false;
$this->properties = array();
$this->lookupMethods = array();
}

/**
Expand Down Expand Up @@ -546,4 +549,23 @@ public function getConfigurator()
{
return $this->configurator;
}

public function setLookupMethod($name, $value)
{
$this->lookupMethods[$name] = $value;

return $this;
}

public function getLookupMethods()
{
return $this->lookupMethods;
}

public function setLookupMethods(array $methods)
{
$this->lookupMethods = $methods;

return $this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,10 @@ private function addService($id, $definition)
$this->referenceVariables = array();
$this->variableCount = 0;

if ($definition->getLookupMethods()) {
throw new \RuntimeException(sprintf('You have set lookup methods for service "%s", but the GenerateLookupMethodClassesPass was not enabled.', $id));
}

$return = '';
if ($definition->isSynthetic()) {
$return = sprintf('@throws \RuntimeException always since this service is expected to be injected dynamically');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ private function addService($definition, $id, \DOMElement $parent)
$this->convertParameters($parameters, 'property', $service, 'name');
}

if ($parameters = $definition->getLookupMethods()) {
$this->convertParameters($parameters, 'lookup_method', $service, 'name');
}

$this->addMethodCalls($definition->getMethodCalls(), $service);

if ($callable = $definition->getConfigurator()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ private function addService($id, $definition)
$code .= sprintf(" properties: %s\n", Yaml::dump($this->dumpValue($definition->getProperties()), 0));
}

if ($definition->getLookupMethods()) {
$code .= sprintf(" lookup_methods: %s\n", Yaml::dump($this->dumpValue($definition->getLookupMethods()), 0));
}

if ($definition->getMethodCalls()) {
$code .= sprintf(" calls:\n %s\n", str_replace("\n", "\n ", Yaml::dump($this->dumpValue($definition->getMethodCalls()), 1)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
namespace Symfony\Component\DependencyInjection\Loader;

use Symfony\Component\DependencyInjection\DefinitionDecorator;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Definition;
Expand Down Expand Up @@ -164,6 +163,7 @@ private function parseDefinition($id, $service, $file)

$definition->setArguments($service->getArgumentsAsPhp('argument'));
$definition->setProperties($service->getArgumentsAsPhp('property'));
$definition->setLookupMethods($service->getArgumentsAsPhp('lookup-method'));

if (isset($service->configurator)) {
if (isset($service->configurator['function'])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ private function parseDefinition($id, $service, $file)
$definition->setProperties($this->resolveServices($service['properties']));
}

if (isset($service['lookup_methods'])) {
$definition->setLookupMethods($this->resolveServices($service['lookup_methods']));
}

if (isset($service['configurator'])) {
if (is_string($service['configurator'])) {
$definition->setConfigurator($service['configurator']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
<xsd:element name="call" type="call" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="tag" type="tag" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="property" type="property" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="lookup-method" type="property" minOccurs="0" maxOccurs="unbounded" />
</xsd:choice>
<xsd:attribute name="id" type="xsd:string" />
<xsd:attribute name="class" type="xsd:string" />
Expand Down
10 changes: 9 additions & 1 deletion src/Symfony/Component/HttpKernel/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\HttpKernel\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
use Symfony\Component\HttpKernel\DependencyInjection\AddClassesToCachePass;
use Symfony\Component\DependencyInjection\Compiler\GenerateLookupMethodClassesPass;
use Symfony\Component\HttpKernel\DependencyInjection\Extension as DIExtension;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Loader\DelegatingLoader;
Expand Down Expand Up @@ -577,8 +578,15 @@ protected function buildContainer()
}
$container->addObjectResource($this);

$passConfig = $container->getCompilerPassConfig();

// ensure these extensions are implicitly loaded
$container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
$passConfig->setMergePass(new MergeExtensionConfigurationPass($extensions));

// enable method injection
$passes = $passConfig->getRemovingPasses();
array_unshift($passes, new GenerateLookupMethodClassesPass($this->getCacheDir().'/lookup_method_classes'));
$passConfig->setRemovingPasses($passes);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why add the pass here instead of in the container?


if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
$container->merge($cont);
Expand Down
Loading