forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNestedArrayFormatter.php
More file actions
73 lines (61 loc) · 2.13 KB
/
Copy pathNestedArrayFormatter.php
File metadata and controls
73 lines (61 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Message\Formatter;
use Respect\Validation\Message\ArrayFormatter;
use Respect\Validation\Message\Renderer;
use Respect\Validation\Message\Translator;
use Respect\Validation\Result;
use function count;
use function current;
final readonly class NestedArrayFormatter implements ArrayFormatter
{
public function __construct(
private Renderer $renderer,
private TemplateResolver $templateResolver,
) {
}
/**
* @param array<string|int, mixed> $templates
*
* @return array<string|int, mixed>
*/
public function format(Result $result, array $templates, Translator $translator): array
{
$matchedTemplates = $this->templateResolver->selectMatches($result, $templates);
if (count($result->children) === 0 || $this->templateResolver->hasMatch($result, $matchedTemplates)) {
return [
$result->path->value ?? $result->id->value => $this->renderer->render(
$this->templateResolver->resolve($result->withoutParentPath(), $matchedTemplates),
$translator,
),
];
}
$messages = [];
foreach ($result->children as $child) {
$key = $child->path->value ?? $child->id->value;
$messages[$key] = $this->format(
$child->withoutParentPath()->withoutName(),
$this->templateResolver->selectMatches($child, $matchedTemplates),
$translator,
);
if (count($messages[$key]) !== 1) {
continue;
}
$messages[$key] = current($messages[$key]);
}
if (count($messages) > 1) {
$self = [
'__root__' => $this->renderer->render(
$this->templateResolver->resolve($result->withoutParentPath(), $matchedTemplates),
$translator,
),
];
return $self + $messages;
}
return $messages;
}
}