Skip to content

[DI] Allow to count on lazy collection arguments #21455

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
Feb 2, 2017
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
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,19 @@
/**
* @internal
*/
class RewindableGenerator implements \IteratorAggregate
class RewindableGenerator implements \IteratorAggregate, \Countable
{
private $generator;
private $count;

public function __construct(callable $generator)
/**
* @param callable $generator
* @param int|callable $count
*/
public function __construct(callable $generator, $count)
{
$this->generator = $generator;
$this->count = $count;
}

public function getIterator()
Expand All @@ -29,4 +35,13 @@ public function getIterator()

return $g();
}

public function count()
{
if (is_callable($count = $this->count)) {
Copy link
Member

Choose a reason for hiding this comment

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

Do we need the local $count variable here?

Copy link
Member

Choose a reason for hiding this comment

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

we need it as calling $this->count() would fail below, but could be declared inside the if indeed

Copy link
Member

Choose a reason for hiding this comment

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

No thinking about this again I would keep it as is.

$this->count = $count();
}

return $this->count;
}
}
13 changes: 13 additions & 0 deletions src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,19 @@ public function resolveServices($value)

yield $k => $this->resolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($v)));
}
}, function () use ($value) {
$count = 0;
foreach ($value->getValues() as $v) {
foreach (self::getServiceConditionals($v) as $s) {
if (!$this->has($s)) {
continue 2;
}
}

++$count;
Copy link
Member

Choose a reason for hiding this comment

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

missing return statement?

Copy link
Contributor Author

@ogizanagi ogizanagi Jan 30, 2017

Choose a reason for hiding this comment

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

Grumpf. Good catch. 😅

I need to add a test case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

}

return $count;
});
} elseif ($value instanceof ClosureProxyArgument) {
$parameterBag = $this->getParameterBag();
Expand Down
40 changes: 33 additions & 7 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1362,19 +1362,36 @@ private function instantiateProxy($class, $args, $useConstructor)
*/
private function wrapServiceConditionals($value, $code, &$isUnconditional = null, $containerRef = '$this')
{
if ($isUnconditional = !$services = ContainerBuilder::getServiceConditionals($value)) {
if ($isUnconditional = !$condition = $this->getServiceConditionals($value, $containerRef)) {
return $code;
}

// re-indent the wrapped code
$code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));

return sprintf(" if (%s) {\n%s }\n", $condition, $code);
}

/**
* Get the conditions to execute for conditional services.
*
* @param string $value
* @param string $containerRef
*
* @return null|string
*/
private function getServiceConditionals($value, $containerRef = '$this')
{
if (!$services = ContainerBuilder::getServiceConditionals($value)) {
return null;
}

$conditions = array();
foreach ($services as $service) {
$conditions[] = sprintf("%s->has('%s')", $containerRef, $service);
}

// re-indent the wrapped code
$code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));

return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code);
return implode(' && ', $conditions);
}

/**
Expand Down Expand Up @@ -1524,17 +1541,26 @@ private function dumpValue($value, $interpolate = true)

return sprintf('array(%s)', implode(', ', $code));
} elseif ($value instanceof IteratorArgument) {
$countCode = array();
$countCode[] = 'function () {';
$operands = array(0);

$code = array();
$code[] = 'new RewindableGenerator(function() {';
$code[] = 'new RewindableGenerator(function () {';
foreach ($value->getValues() as $k => $v) {
($c = $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0];
$v = $this->wrapServiceConditionals($v, sprintf(" yield %s => %s;\n", $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)));
foreach (explode("\n", $v) as $v) {
if ($v) {
$code[] = ' '.$v;
}
}
}
$code[] = ' })';

$countCode[] = sprintf(' return %s;', implode(' + ', $operands));
$countCode[] = ' }';

$code[] = sprintf(' }, %s)', count($operands) > 1 ? implode("\n", $countCode) : $operands[0]);

return implode("\n", $code);
} elseif ($value instanceof Definition) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Tests\Argument;

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

class RewindableGeneratorTest extends \PHPUnit_Framework_TestCase
{
public function testImplementsCountable()
{
$this->assertInstanceOf(\Countable::class, new RewindableGenerator(function () {
yield 1;
}, 1));
}

public function testCountUsesProvidedValue()
{
$generator = new RewindableGenerator(function () {
yield 1;
}, 3);

$this->assertCount(3, $generator);
}

public function testCountUsesProvidedValueAsCallback()
{
$called = 0;
$generator = new RewindableGenerator(function () {
yield 1;
}, function () use (&$called) {
++$called;

return 3;
});

$this->assertSame(0, $called, 'Count callback is called lazily');
$this->assertCount(3, $generator);

count($generator);

$this->assertSame(1, $called, 'Count callback is called only once');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ public function testCreateServiceWithIteratorArgument()

$lazyContext = $builder->get('lazy_context');
$this->assertInstanceOf(RewindableGenerator::class, $lazyContext->lazyValues);
$this->assertCount(1, $lazyContext->lazyValues);

$i = 0;
foreach ($lazyContext->lazyValues as $k => $v) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,13 +314,13 @@ protected function getFooWithInlineService()
*/
protected function getLazyContextService()
{
return $this->services['lazy_context'] = new \LazyContext(new RewindableGenerator(function() {
return $this->services['lazy_context'] = new \LazyContext(new RewindableGenerator(function () {
yield 0 => 'foo';
yield 1 => ${($_ = isset($this->services['foo.baz']) ? $this->services['foo.baz'] : $this->get('foo.baz')) && false ?: '_'};
yield 2 => array($this->getParameter('foo') => 'foo is '.$this->getParameter('foo').'', 'foobar' => $this->getParameter('foo'));
yield 3 => true;
yield 4 => $this;
}));
}, 5));
}

/**
Expand All @@ -333,11 +333,13 @@ protected function getLazyContextService()
*/
protected function getLazyContextIgnoreInvalidRefService()
{
return $this->services['lazy_context_ignore_invalid_ref'] = new \LazyContext(new RewindableGenerator(function() {
return $this->services['lazy_context_ignore_invalid_ref'] = new \LazyContext(new RewindableGenerator(function () {
yield 0 => ${($_ = isset($this->services['foo.baz']) ? $this->services['foo.baz'] : $this->get('foo.baz')) && false ?: '_'};
if ($this->has('invalid')) {
yield 1 => $this->get('invalid', ContainerInterface::NULL_ON_INVALID_REFERENCE);
}
}, function () {
return 1 + (int) ($this->has('invalid'));
}));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,13 @@ protected function getFooWithInlineService()
*/
protected function getLazyContextService()
{
return $this->services['lazy_context'] = new \LazyContext(new RewindableGenerator(function() {
return $this->services['lazy_context'] = new \LazyContext(new RewindableGenerator(function () {
yield 0 => 'foo';
yield 1 => ${($_ = isset($this->services['foo.baz']) ? $this->services['foo.baz'] : $this->get('foo.baz')) && false ?: '_'};
yield 2 => array('bar' => 'foo is bar', 'foobar' => 'bar');
yield 3 => true;
yield 4 => $this;
}));
}, 5));
}

/**
Expand All @@ -332,9 +332,9 @@ protected function getLazyContextService()
*/
protected function getLazyContextIgnoreInvalidRefService()
{
return $this->services['lazy_context_ignore_invalid_ref'] = new \LazyContext(new RewindableGenerator(function() {
return $this->services['lazy_context_ignore_invalid_ref'] = new \LazyContext(new RewindableGenerator(function () {
yield 0 => ${($_ = isset($this->services['foo.baz']) ? $this->services['foo.baz'] : $this->get('foo.baz')) && false ?: '_'};
}));
}, 1));
}

/**
Expand Down