forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestedListStringFormatter.php
More file actions
95 lines (81 loc) · 2.62 KB
/
NestedListStringFormatter.php
File metadata and controls
95 lines (81 loc) · 2.62 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/*
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-FileContributor: Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/
declare(strict_types=1);
namespace Respect\Validation\Message\Formatter;
use Respect\Validation\Message\Renderer;
use Respect\Validation\Message\StringFormatter;
use Respect\Validation\Name;
use Respect\Validation\Result;
use function array_filter;
use function count;
use function rtrim;
use function sprintf;
use function str_repeat;
use const PHP_EOL;
final readonly class NestedListStringFormatter implements StringFormatter
{
/** @param array<string|int, mixed> $templates */
public function format(Result $result, Renderer $renderer, array $templates): string
{
return $this->formatRecursively($result, $renderer, $templates, 0, null, true);
}
/** @param array<string|int, mixed> $templates */
private function formatRecursively(
Result $result,
Renderer $renderer,
array $templates,
int $depth,
Name|null $lastVisibleName,
bool $isRoot,
Result ...$siblings,
): string {
$formatted = '';
if ($this->isVisible($result, ...$siblings)) {
$indentation = str_repeat(' ', $depth * 2);
$formatted .= sprintf(
'%s- %s' . PHP_EOL,
$indentation,
$renderer->render(
$lastVisibleName === $result->name ? $result->withoutName() : $result,
$templates,
$isRoot,
),
);
$lastVisibleName ??= $result->name;
$depth++;
}
foreach ($result->children as $child) {
$formatted .= $this->formatRecursively(
$child,
$renderer,
$templates,
$depth,
$lastVisibleName,
false,
...array_filter($result->children, static fn(Result $sibling) => $sibling !== $child),
);
$formatted .= PHP_EOL;
}
return rtrim($formatted, PHP_EOL);
}
private function isVisible(Result $result, Result ...$siblings): bool
{
if ($result->hasCustomTemplate()) {
return true;
}
if (count($result->children) !== 1) {
return true;
}
foreach ($siblings as $sibling) {
if ($sibling->hasCustomTemplate() || count($sibling->children) !== 1) {
return true;
}
}
return false;
}
}