respect-validation/library/Message/Formatter/FirstResultStringFormatter.php
Henrique Moody 644ecb5190
Change the contract of the formatters
Both `ArrayFormatter` and `StringFormatter` accept an instance of the
`Translator`. Thinking about it a bit better, I realised that a
formatter might not always need a `Translator`, but it will surely need
a `Renderer`.

Besides, the `InterpolationRenderer` needs to take translation into
account, so it seems more natural to me that this is the one that will
get an instance of the `Translator`, as other implementations of the
`Renderer` might not even deal with translations.
2025-12-22 13:43:59 +01:00

35 lines
1 KiB
PHP

<?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\Renderer;
use Respect\Validation\Message\StringFormatter;
use Respect\Validation\Result;
final readonly class FirstResultStringFormatter implements StringFormatter
{
public function __construct(
private TemplateResolver $templateResolver,
) {
}
/** @param array<string|int, mixed> $templates */
public function format(Result $result, Renderer $renderer, array $templates): string
{
$matchedTemplates = $this->templateResolver->selectMatches($result, $templates);
if (!$this->templateResolver->hasMatch($result, $matchedTemplates)) {
foreach ($result->children as $child) {
return $this->format($child, $renderer, $matchedTemplates);
}
}
return $renderer->render($this->templateResolver->resolve($result, $matchedTemplates));
}
}