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.
This commit is contained in:
Henrique Moody 2025-12-30 10:33:05 +01:00
commit cd6bcd470b
No known key found for this signature in database
GPG key ID: 221E9281655813A6
18 changed files with 825 additions and 131 deletions

View file

@ -0,0 +1,63 @@
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Message\Modifier;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use Respect\Validation\Exceptions\ComponentException;
use Respect\Validation\Test\Message\NullStringifier;
use Respect\Validation\Test\Message\TestingStringifier;
use Respect\Validation\Test\TestCase;
use function print_r;
use function sprintf;
#[CoversClass(StringifyModifier::class)]
final class StringifyModifierTest extends TestCase
{
#[Test]
public function itShouldUseStringifierWhenAvailable(): void
{
$value = ['some', 'array'];
$stringifier = new TestingStringifier();
$modifier = new StringifyModifier($stringifier);
$expected = $stringifier->stringify($value, 0);
self::assertSame($expected, $modifier->modify($value, null));
}
#[Test]
public function itShouldUseFallbackWhenStringifierIsNull(): void
{
$value = ['some', 'array'];
$expected = print_r($value, true);
$modifier = new StringifyModifier(new NullStringifier());
self::assertSame($expected, $modifier->modify($value, null));
}
#[Test]
public function itShouldFailWhenPipeParameterIsGiven(): void
{
$pipe = 'someModifier';
$modifier = new StringifyModifier(new TestingStringifier());
$this->expectExceptionObject(new ComponentException(sprintf(
'StringifyModifier only accepts null as pipe but "%s" was given.',
$pipe,
)));
$modifier->modify(['some', 'array'], $pipe);
}
}