respect-validation/library/Message/Modifier/StringifyModifier.php
Henrique Moody cd6bcd470b
Enable adding modifiers without changing InterpolationRenderer
The `InterpolationRenderer` was violating the open-closed principle,
because every time we would want to add a new modifier, we would need to
change its implementation.

This commit changes that behaviour by creating a `Modifier` interface.
The classes implementing that interface are using a chain of
responsibility to pass the data to the next one. Using a chain of
responsibility makes a lot of sense, since it's only possible to have
one modifier at a time.
2025-12-30 11:17:11 +01:00

37 lines
890 B
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Message\Modifier;
use Respect\Stringifier\Stringifier;
use Respect\Validation\Exceptions\ComponentException;
use Respect\Validation\Message\Modifier;
use function print_r;
use function sprintf;
final readonly class StringifyModifier implements Modifier
{
public function __construct(
private Stringifier $stringifier,
) {
}
public function modify(mixed $value, string|null $pipe): string
{
if ($pipe !== null) {
throw new ComponentException(sprintf(
'StringifyModifier only accepts null as pipe but "%s" was given.',
$pipe,
));
}
return $this->stringifier->stringify($value, 0) ?? print_r($value, true);
}
}