forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemplateResolver.php
More file actions
95 lines (75 loc) · 2.56 KB
/
TemplateResolver.php
File metadata and controls
95 lines (75 loc) · 2.56 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\TemplateRegistry;
use Respect\Validation\Path;
use Respect\Validation\Result;
use function is_array;
use function is_string;
final class TemplateResolver
{
public function __construct(
private TemplateRegistry $templateRegistry,
) {
}
/** @param array<string|int, mixed> $templates */
public function getGivenTemplate(Result $result, array $templates, bool $isRoot = true): string|null
{
if ($result->hasCustomTemplate()) {
return $result->template;
}
$filtered = $templates;
$isAtCorrectScope = $isRoot;
if ($result->path !== null) {
[$filtered, $isAtCorrectScope] = $this->filterByPath($result->path, $templates);
}
foreach ([$result->path?->value, $result->name?->value, $result->id->value] as $key) {
if ($key === null || !isset($filtered[$key])) {
continue;
}
if (is_string($filtered[$key])) {
return $filtered[$key];
}
}
if ($isAtCorrectScope && isset($filtered['__root__']) && is_string($filtered['__root__'])) {
return $filtered['__root__'];
}
return null;
}
public function getValidatorTemplate(Result $result): string
{
foreach ($this->templateRegistry->getTemplates($result->validator::class) as $template) {
if ($template->id !== $result->template) {
continue;
}
if ($result->hasInvertedMode) {
return $template->inverted;
}
return $template->default;
}
return $result->template;
}
/**
* @param array<string|int, mixed> $templates
*
* @return array{array<string|int, mixed>, bool}
*/
private function filterByPath(Path $path, array $templates): array
{
if ($path->parent !== null) {
[$templates, $fullyConsumed] = $this->filterByPath($path->parent, $templates);
} else {
$fullyConsumed = true;
}
if (isset($templates[$path->value]) && is_array($templates[$path->value])) {
return [$templates[$path->value], $fullyConsumed];
}
return [$templates, false];
}
}