8000 [DI] Allow binding by type+name by nicolas-grekas · Pull Request #27165 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[DI] Allow binding by type+name #27165

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

Merged
merged 1 commit into from
May 21, 2018
Merged
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
Fai 8000 led to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, a
continue;
}
$type = ProxyHelper::getTypeHint($reflectionMethod, $parameter, false);
$type = $type ? sprintf('is type-hinted "%s"', $type) : 'has no type-hint';
$type = $type ? sprintf('is type-hinted "%s"', ltrim($type, '\\')) : 'has no type-hint';

throw new AutowiringFailedException($this->currentId, sprintf('Cannot autowire service "%s": argument "$%s" of method "%s()" %s, you should configure its value explicitly.', $this->currentId, $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method, $type));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ protected function processValue($value, $isRoot = false)
$this->unusedBindings[$bindingId] = array($key, $this->currentId);
}

if (isset($key[0]) && '$' === $key[0]) {
if (preg_match('/^(?:(?:array|bool|float|int|string) )?\$/', $key)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

And iterable?

Copy link
Member Author

Choose a reason for hiding this comment

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

This needs to contain what we can put in parameters. So not iterable nor callable.

Copy link
Contributor
@ogizanagi ogizanagi May 6, 2018

Choose a reason for hiding this comment

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

Theoretically, a factory definition could return a callable or iterable (or any other type) and be used in a binding though. Do we care? (is it actually officially supported? => Edit: I guess yes 😃)

Also, a class might have an iterable typehint but expected injected value be an array. Shouldn't bindings support this too?

Copy link
Member Author

Choose a reason for hiding this comment

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

It's supported since it always worked yes, and it works here also, this just skips the "must be a ref" check for scalar|array types.

a class might have an iterable typehint but expected injected value be an array

That's not supported right now. Could be added in another PR for sure (if worth it)

continue;
}

Expand Down Expand Up @@ -113,15 +113,21 @@ protected function processValue($value, $isRoot = false)
continue;
}

$typeHint = ProxyHelper::getTypeHint($reflectionMethod, $parameter);

if (array_key_exists($k = ltrim($typeHint, '\\').' $'.$parameter->name, $bindings)) {
$arguments[$key] = $this->getBindingValue($bindings[$k]);

continue;
}

if (array_key_exists('$'.$parameter->name, $bindings)) {
$arguments[$key] = $this->getBindingValue($bindings['$'.$parameter->name]);

continue;
}

$typeHint = ProxyHelper::getTypeHint($reflectionMethod, $parameter, true);

if (!isset($bindings[$typeHint])) {
if (!$typeHint || '\\' !== $typeHint[0] || !isset($bindings[$typeHint = substr($typeHint, 1)])) {
continue;
}

Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/DependencyInjection/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,10 @@ public function getBindings()
public function setBindings(array $bindings)
{
foreach ($bindings as $key => $binding) {
if (0 < strpos($key, '$') && $key !== $k = preg_replace('/[ \t]*\$/', ' $', $key)) {
unset($bindings[$key]);
$bindings[$key = $k] = $binding;
}
if (!$binding instanceof BoundArgument) {
$bindings[$key] = new BoundArgument($binding);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ trait BindTrait
final public function bind($nameOrFqcn, $valueOrRef)
{
$valueOrRef = static::processValue($valueOrRef, true);
if (isset($nameOrFqcn[0]) && '$' !== $nameOrFqcn[0] && !$valueOrRef instanceof Reference) {
if (!preg_match('/^(?:(?:array|bool|float|int|string)[ \t]*+)?\$/', $nameOrFqcn) && !$valueOrRef instanceof Reference) {
throw new InvalidArgumentException(sprintf('Invalid binding for service "%s": named arguments must start with a "$", and FQCN must map to references. Neither applies to binding "%s".', $this->id, $nameOrFqcn));
}
$bindings = $this->definition->getBindings();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,28 @@ public function testScalarSetter()

$this->assertEquals(array(array('setDefaultLocale', array('fr'))), $definition->getMethodCalls());
}

public function testTupleBinding()
{
$container = new ContainerBuilder();

$bindings = array(
'$c' => new BoundArgument(new Reference('bar')),
CaseSensitiveClass::class.'$c' => new BoundArgument(new Reference('foo')),
);

$definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class);
$definition->addMethodCall('setSensitiveClass');
$definition->addMethodCall('setAnotherC');
$definition->setBindings($bindings);

$pass = new ResolveBindingsPass();
$pass->process($container);

$expected = array(
array('setSensitiveClass', array(new Reference('foo'))),
array('setAnotherC', array(new Reference('bar'))),
);
$this->assertEquals($expected, $definition->getMethodCalls());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ public function setApiKey($apiKey)
public function setSensitiveClass(CaseSensitiveClass $c)
{
}

public function setAnotherC($c)
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public function process(ContainerBuilder $container)
$args = array();
foreach ($parameters as $p) {
/** @var \ReflectionParameter $p */
$type = $target = ProxyHelper::getTypeHint($r, $p, true);
$type = ltrim($target = ProxyHelper::getTypeHint($r, $p), '\\');
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;

if (isset($arguments[$r->name][$p->name])) {
Expand All @@ -132,7 +132,7 @@ public function process(ContainerBuilder $container)
} elseif ($p->allowsNull() && !$p->isOptional()) {
$invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
}
} elseif (isset($bindings[$bindingName = '$'.$p->name]) || isset($bindings[$bindingName = $type])) {
} elseif (isset($bindings[$bindingName = $type.' $'.$p->name]) || isset($bindings[$bindingName = '$'.$p->name]) || isset($bindings[$bindingName = $type])) {
$binding = $bindings[$bindingName];

list($bindingValue, $bindingId) = $binding->getValues();
Expand All @@ -148,7 +148,7 @@ public function process(ContainerBuilder $container)
}

continue;
} elseif (!$type || !$autowire) {
} elseif (!$type || !$autowire || '\\' !== $target[0]) {
continue;
} elseif (!$p->allowsNull()) {
$invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
Expand All @@ -169,6 +169,7 @@ public function process(ContainerBuilder $container)
throw new InvalidArgumentException($message);
}

$target = ltrim($target, '\\');
$args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior) : new Reference($target, $invalidBehavior);
}
// register the maps as a per-method service-locators
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,16 +308,23 @@ public function testBindings($bindingName)

public function provideBindings()
{
return array(array(ControllerDummy::class), array('$bar'));
return array(
array(ControllerDummy::class.'$bar'),
array(ControllerDummy::class),
array('$bar'),
);
}

public function testBindScalarValueToControllerArgument()
/**
* @dataProvider provideBindScalarValueToControllerArgument
*/
public function testBindScalarValueToControllerArgument($bindingKey)
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument(array());

$container->register('foo', ArgumentWithoutTypeController::class)
->setBindings(array('$someArg' => '%foo%'))
->setBindings(array($bindingKey => '%foo%'))
->addTag('controller.service_arguments');

$container->setParameter('foo', 'foo_val');
Expand All @@ -339,6 +346,12 @@ public function testBindScalarValueToControllerArgument()
$this->assertTrue($container->has((string) $reference));
$this->assertSame('foo_val', $container->get((string) $reference));
}

public function provideBindScalarValueToControllerArgument()
{
yield array('$someArg');
yield array('string $someArg');
}
}

class RegisterTestController
Expand Down Expand Up @@ -396,7 +409,7 @@ public function barAction(NonExistentClass $nonExistent = null, $bar)

class ArgumentWithoutTypeController
{
public function fooAction($someArg)
public function fooAction(string $someArg)
{
}
}
0