Fixed previously introduced bug, add integration test

This commit is contained in:
Alexandre Gomes Gaigalas 2023-02-19 22:11:35 -03:00
parent bae314dd00
commit 636906fa07
3 changed files with 50 additions and 19 deletions

View file

@ -9,9 +9,6 @@ declare(strict_types=1);
namespace Respect\Validation\Exceptions;
use function count;
use function current;
/**
* @author Alexandre Gomes Gaigalas <alganet@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
@ -38,27 +35,16 @@ final class EachException extends NestedValidationException
*/
public function getMessages(array $templates = []): array
{
$messages = [$this->getId() => $this->renderMessage($this, $templates)];
$messages = [];
$count = -1;
foreach ($this->getChildren() as $exception) {
$count++;
$id = $exception->getId();
if (!$exception instanceof NestedValidationException) {
$messages[$id . '.' . $count] = $this->renderMessage(
$exception,
$this->findTemplates($templates, $this->getId())
);
continue;
}
$messages[$id . '.' . $count] = $exception->getMessages(
$this->findTemplates($templates, $id, $this->getId())
$messages[$id . '.' . $count] = $this->renderMessage(
$exception,
$this->findTemplates($templates, $this->getId())
);
if (count($messages[$id . '.' . $count]) > 1) {
continue;
}
$messages[$id . '.' . $count] = current($messages[$exception->getId()]);
}
return $messages;

View file

@ -0,0 +1,46 @@
--CREDITS--
Alexandre Gomes Gaigalas <alganet@gmail.com>
--FILE--
<?php
declare(strict_types=1);
require 'vendor/autoload.php';
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator;
$cars = [
['manufacturer' => 'Honda', 'model' => 'Accord'],
['manufacturer' => 'Toyota', 'model' => 'Rav4'],
['manufacturer' => 'Ford', 'model' => 'notarealcar'],
['manufacturer' => 'Honda', 'model' => 'not valid'],
];
try {
Validator::arrayType()->each(
Validator::oneOf(
Validator::key('manufacturer', Validator::equals('Honda'))
->key('model', Validator::in(['Accord', 'Fit'])),
Validator::key('manufacturer', Validator::equals('Toyota'))
->key('model', Validator::in(['Rav4', 'Camry'])),
Validator::key('manufacturer', Validator::equals('Ford'))
->key('model', Validator::in(['F150', 'Bronco']))
)
)->assert($cars);
} catch (NestedValidationException $e) {
var_dump($e->getMessages());
}
?>
--EXPECT--
array(1) {
["each"]=>
array(2) {
["validator.0"]=>
string(92) "All of the required rules must pass for `{ "manufacturer": "Ford", "model": "notarealcar" }`"
["validator.1"]=>
string(91) "All of the required rules must pass for `{ "manufacturer": "Honda", "model": "not valid" }`"
}
}

View file

@ -106,7 +106,6 @@ final class EachTest extends RuleTestCase
$this->assertEquals(
$e->getMessages(),
[
'each' => 'Each item in `{ 1, 2, 3 }` must be valid',
'stringType.0' => '1 must be of type string',
'stringType.1' => '2 must be of type string',
'stringType.2' => '3 must be of type string',