Add type check to "first" helper

This commit is contained in:
Dmitriy Simushev 2014-12-25 10:37:05 +00:00
parent f25440e632
commit e1d68fe4d7
2 changed files with 32 additions and 2 deletions

View File

@ -43,7 +43,11 @@ class FirstHelper implements HelperInterface
'"first" helper expects exactly one argument.'
);
}
$collection = $context->get($parsed_args[0]);
if (!is_array($collection) && !($collection instanceof \Traversable)) {
throw new \InvalidArgumentException('Wrong type of the argument in the "first" helper.');
}
return reset($collection);
}

View File

@ -63,7 +63,7 @@ class FirstHelperTest extends \PHPUnit_Framework_TestCase
* Tests that exception is thrown if wrong number of arguments is used.
*
* @expectedException InvalidArgumentException
* @dataProvider wrongArgumentsProvider
* @dataProvider wrongArgumentsCountProvider
*/
public function testArgumentsCount($template)
{
@ -76,7 +76,7 @@ class FirstHelperTest extends \PHPUnit_Framework_TestCase
/**
* A data provider for testArgumentsCount method.
*/
public function wrongArgumentsProvider()
public function wrongArgumentsCountProvider()
{
return array(
// Not enough arguments
@ -85,4 +85,30 @@ class FirstHelperTest extends \PHPUnit_Framework_TestCase
array('{{first "Arg" "ANOTHER ARG"}}'),
);
}
/**
* Tests invalid arguments type.
*
* @expectedException InvalidArgumentException
* @dataProvider invalidArgumentsProvider
*/
public function testInvalidArguments($collection)
{
$helpers = new \Handlebars\Helpers(array('first' => new FirstHelper()));
$engine = new \Handlebars\Handlebars(array('helpers' => $helpers));
$engine->render('{{first collection}}', array('collection' => $collection));
}
/**
* A data provider for testInvalidArguments method.
*/
public function invalidArgumentsProvider()
{
return array(
array('a string'),
array(42),
array(new \stdClass()),
);
}
}