Create method getMessages() on nested exception

This commit is contained in:
Henrique Moody 2015-09-10 19:10:18 -03:00
parent f14e53921c
commit 69f433db6b
4 changed files with 83 additions and 1 deletions

View file

@ -121,7 +121,7 @@ The printed message is exactly this, as a text tree:
\-"really messed up screen#name" must have a length between 1 and 15
```
## Getting Messages
## Requesting Messages
The text tree is fine, but unusable on a HTML form or something more custom. You can use
`findMessages()` for that:
@ -138,6 +138,35 @@ try {
`findMessages()` returns an array with messages from the requested validators.
## Getting Messages
Sometimes you just need all the messages, for that you can use `getMessages()`.
It will return all messages from the rules that did not pass the validation.
```php
try {
Validator::key('username', Validator::length(2, 32))
->key('birthdate', Validator::date())
->key('password', Validator::notEmpty())
->key('email', Validator::email())
->assert($input);
} catch (NestedValidationExceptionInterface $e) {
print_r($e->getMessages());
}
```
The code above may display something like:
```
Array
(
[0] => username must have a length between 2 and 32
[1] => birthdate must be a valid date
[2] => password must not be empty
[3] => Key email must be present
)
```
## Custom Messages
Getting messages as an array is fine, but sometimes you need to customize them in order

View file

@ -73,6 +73,21 @@ class AbstractNestedException extends ValidationException implements NestedValid
}
}
public function getMessages()
{
$messages = array();
foreach ($this->getIterator() as $key => $exception) {
if ($exception instanceof AbstractNestedException
&& count($exception->getRelated()) > 0) {
continue;
}
$messages[] = $exception->getMessage();
}
return $messages;
}
public function getFullMessage()
{
$message = array();

View file

@ -14,5 +14,6 @@ namespace Respect\Validation\Exceptions;
interface NestedValidationExceptionInterface extends ValidationExceptionInterface
{
public function findMessages(array $paths);
public function getMessages();
public function getFullMessage();
}

View file

@ -0,0 +1,37 @@
--TEST--
getMessages() should include all validation messages in a chain
--FILE--
<?php
date_default_timezone_set('UTC');
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\NestedValidationExceptionInterface;
use Respect\Validation\Validator;
try {
$input = array(
'username' => 'u',
'birthdate' => 'Not a date',
'password' => '',
);
Validator::key('username', Validator::length(2, 32))
->key('birthdate', Validator::date())
->key('password', Validator::notEmpty())
->key('email', Validator::email())
->assert($input);
} catch (NestedValidationExceptionInterface $e) {
print_r($e->getMessages());
}
?>
--EXPECTF--
Array
(
[0] => username must have a length between 2 and 32
[1] => birthdate must be a valid date
[2] => password must not be empty
[3] => Key email must be present
)