From 5e6ad9c7a48c8b49aec692543d4d0ee20c75a61e Mon Sep 17 00:00:00 2001 From: jake Date: Sun, 6 Apr 2014 01:27:27 +0200 Subject: [PATCH] Fix: Optional method should be called inside closure so that each generated value is optional --- Factory/FormatterFactory.php | 13 ++++++------- Tests/Factory/FormatterFactoryTest.php | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/Factory/FormatterFactory.php b/Factory/FormatterFactory.php index b72618c..8b9361e 100644 --- a/Factory/FormatterFactory.php +++ b/Factory/FormatterFactory.php @@ -23,14 +23,13 @@ public static function createClosure($generator, $method, array $parameters = ar $generator = $generator->unique(); } - if (null !== $optional && $generator instanceof Generator) { - $generator = $generator->optional((double) $optional); - } + return function () use ($generator, $method, $parameters, $optional) { - if (0 === count($parameters)) { - return function () use ($generator, $method) { return $generator->$method(); }; - } + if (null !== $optional && $generator instanceof Generator) { + $generator = $generator->optional((double)$optional); + } - return function () use ($generator, $method, $parameters) { return call_user_func_array(array($generator, $method), (array) $parameters); }; + return call_user_func_array(array($generator, $method), (array)$parameters); + }; } } diff --git a/Tests/Factory/FormatterFactoryTest.php b/Tests/Factory/FormatterFactoryTest.php index 9784dc6..ea3efe2 100644 --- a/Tests/Factory/FormatterFactoryTest.php +++ b/Tests/Factory/FormatterFactoryTest.php @@ -22,6 +22,10 @@ public function testCreateClosureWithoutParameters() ->expects($this->once()) ->method('foo') ; + $generator + ->expects($this->never()) + ->method('optional') + ; $closure = FormatterFactory::createClosure($generator, 'foo'); @@ -29,6 +33,24 @@ public function testCreateClosureWithoutParameters() $closure(); } + public function testCreateClosureWithOptional() + { + $generator = $this->getMock('Faker\Generator', array('foo','optional')); + $generator + ->expects($this->once()) + ->method('foo') + ; + $generator + ->expects($this->once()) + ->method('optional') + ->willReturn($generator) + ; + $closure = FormatterFactory::createClosure($generator, 'foo', array(), null, 0.1); + + $this->assertTrue(is_callable($closure)); + $closure(); + } + public function withParameterProvider() { return array(