Set template for the only rule in the chain

When there is just one rule in the chain and the there is a defined
template for that, the expected behaviour when using the `check()`
method is to see the exception message with the defined template.
This commit is contained in:
Henrique Moody 2016-04-07 14:11:40 -03:00
parent 46541c7e46
commit bb0e40a08e
2 changed files with 25 additions and 1 deletions

View file

@ -15,6 +15,7 @@ use finfo;
use ReflectionClass;
use Respect\Validation\Exceptions\AllOfException;
use Respect\Validation\Exceptions\ComponentException;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Rules\AllOf;
use Respect\Validation\Rules\Key;
@ -185,6 +186,19 @@ class Validator extends AllOf
}
}
public function check($input)
{
try {
return parent::check($input);
} catch (ValidationException $exception) {
if (count($this->getRules()) == 1 && $this->template) {
$exception->setTemplate($this->template);
}
throw $exception;
}
}
/**
* @param string $ruleName
* @param array $arguments

View file

@ -8,11 +8,21 @@ use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Rules\Callback;
use Respect\Validation\Validator;
$rule = Validator::callback('is_int')->setTemplate('{{name}} is not tasty');
try {
Validator::callback('is_int')->setTemplate('{{name}} is not tasty')->assert('something');
$rule->assert('something');
} catch (NestedValidationException $e) {
echo $e->getMainMessage();
}
echo PHP_EOL;
try {
$rule->check('something');
} catch (NestedValidationException $e) {
echo $e->getMainMessage();
}
?>
--EXPECTF--
"something" is not tasty
"something" is not tasty