Skip to content

Commit

Permalink
Set template for the only rule in the chain
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
henriquemoody committed Apr 8, 2016
1 parent 46541c7 commit bb0e40a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
14 changes: 14 additions & 0 deletions library/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
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;

Expand Down Expand Up @@ -185,6 +186,19 @@ public static function with($rulePrefix, $prepend = false)
}
}

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit bb0e40a

Please sign in to comment.