Get the proper exception when using findMessage()

This commit is contained in:
Henrique Moody 2016-09-17 20:21:05 +02:00
parent 494b67871f
commit 98443bad0c
No known key found for this signature in database
GPG key ID: 221E9281655813A6
4 changed files with 74 additions and 4 deletions

View file

@ -34,6 +34,27 @@ class NestedValidationException extends ValidationException implements IteratorA
return $this;
}
/**
* @param string $path
* @param ValidationException $exception
*
* @return ValidationException
*/
private function getExceptionForPath($path, ValidationException $exception)
{
if ($path === $exception->guessId()) {
return $exception;
}
if (!$exception instanceof self) {
return $exception;
}
foreach ($exception as $subException) {
return $subException;
}
}
/**
* @param array $paths
*
@ -49,12 +70,19 @@ class NestedValidationException extends ValidationException implements IteratorA
$exception = $this->findRelated($path);
if (is_object($exception) && !$numericKey) {
$path = str_replace('.', '_', $path);
if (!$exception) {
$messages[$path] = '';
continue;
}
$exception = $this->getExceptionForPath($path, $exception);
if (!$numericKey) {
$exception->setTemplate($value);
}
$path = str_replace('.', '_', $path);
$messages[$path] = $exception ? $exception->getMainMessage() : '';
$messages[$path] = $exception->getMainMessage();
}
return $messages;

View file

@ -324,7 +324,7 @@ class ValidationException extends InvalidArgumentException implements ExceptionI
return static::$defaultTemplates[$this->mode][$templateKey];
}
protected function guessId()
public function guessId()
{
if (!empty($this->id) && $this->id != 'validation') {
return $this->id;

View file

@ -17,6 +17,10 @@ try {
->assert($object);
} catch (NestedValidationException $exception) {
print_r($exception->getMessages());
print_r($exception->findMessages([
'email' => 'Error: {{name}}',
'noWhitespace' => 'Error: {{name}}'
]));
}
?>
--EXPECTF--
@ -25,3 +29,8 @@ Array
[0] => Email Field must be valid email
[1] => Password Field must not contain whitespace
)
Array
(
[email] => Error: Email Field
[noWhitespace] => Error: Password Field
)

View file

@ -0,0 +1,33 @@
--FILE--
<?php
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;
$input = [
'user_name' => 'MyName111',
'user_surname' => 'MySurname111',
'user_tel' => 'asd123'
];
$rules = [
v::key('user_name', v::numeric())->setName('First Name'),
v::key('user_surname', v::numeric())->setName('Second Name'),
v::key('user_tel', v::phone())->setName('Phone number'),
];
try{
v::allOf($rules)->setName('Validation Form')->assert($input);
} catch (NestedValidationException $exception) {
print_r($exception->findMessages(array_keys($input)));
}
?>
--EXPECTF--
Array
(
[user_name] => user_name must be numeric
[user_surname] => user_surname must be numeric
[user_tel] => user_tel must be a valid telephone number
)