Add type check to "last" helper

This commit is contained in:
Dmitriy Simushev 2014-12-25 10:41:21 +00:00
parent e1d68fe4d7
commit 76aa2509e8
2 changed files with 32 additions and 2 deletions

View File

@ -43,7 +43,11 @@ class LastHelper implements HelperInterface
'"last" 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 "last" helper.');
}
return end($collection);
}

View File

@ -63,7 +63,7 @@ class LastHelperTest 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 LastHelperTest 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 LastHelperTest extends \PHPUnit_Framework_TestCase
array('{{last "Arg" "ANOTHER ARG"}}'),
);
}
/**
* Tests invalid arguments type.
*
* @expectedException InvalidArgumentException
* @dataProvider invalidArgumentsProvider
*/
public function testInvalidArguments($collection)
{
$helpers = new \Handlebars\Helpers(array('last' => new LastHelper()));
$engine = new \Handlebars\Handlebars(array('helpers' => $helpers));
$engine->render('{{last collection}}', array('collection' => $collection));
}
/**
* A data provider for testInvalidArguments method.
*/
public function invalidArgumentsProvider()
{
return array(
array('a string'),
array(42),
array(new \stdClass()),
);
}
}