feat: allow to declare parameter for message

The parameter can then be used with a placeholder inside the body of the
message.
This commit is contained in:
Romain Canon 2022-07-26 19:15:37 +02:00
parent 28a412abd1
commit f61eb553fa
3 changed files with 44 additions and 2 deletions

View File

@ -28,9 +28,12 @@ try {
foreach ($messages as $message) {
if ($message->code() === 'some_code') {
$message = $message->withBody('new message / {original_message}');
$message = $message
->withParameter('some_parameter', 'some custom value')
->withBody('new message / {message_code} / {some_parameter}');
}
// new message / some_code / some custom value
echo $message;
}
}

View File

@ -9,6 +9,8 @@ use CuyZ\Valinor\Utility\String\StringFormatter;
use CuyZ\Valinor\Utility\ValueDumper;
use Throwable;
use function array_merge;
/** @api */
final class NodeMessage implements Message, HasCode
{
@ -18,6 +20,9 @@ final class NodeMessage implements Message, HasCode
private string $body;
/** @var array<string, string> */
private array $parameters = [];
private string $locale = StringFormatter::DEFAULT_LOCALE;
public function __construct(Node $node, Message $message)
@ -77,6 +82,19 @@ final class NodeMessage implements Message, HasCode
return $this->body;
}
/**
* Adds a parameter that can replace a placeholder in the message body.
*
* @see self::withBody()
*/
public function withParameter(string $name, string $value): self
{
$clone = clone $this;
$clone->parameters[$name] = $value;
return $clone;
}
/**
* @deprecated use `$message->node()->name()` instead
*/
@ -172,6 +190,6 @@ final class NodeMessage implements Message, HasCode
$parameters['original_message'] = $this->format($this->message->body(), $parameters);
return $parameters;
return array_merge($parameters, $this->parameters);
}
}

View File

@ -57,6 +57,19 @@ final class NodeMessageTest extends TestCase
self::assertSame($expected, (string)$message);
}
public function test_custom_parameters_are_replaced_in_body(): void
{
$originalMessage = new FakeMessage('some original message / {some_parameter}');
$message = new NodeMessage(FakeNode::any(), $originalMessage);
$message = $message->withParameter('some_parameter', 'some value');
$expected = 'some original message / some value';
self::assertSame($expected, $message->toString());
self::assertSame($expected, (string)$message);
}
public function test_replaces_correct_original_message_if_throwable(): void
{
$originalMessage = new FakeErrorMessage('some error message');
@ -78,6 +91,14 @@ final class NodeMessageTest extends TestCase
self::assertNotSame($messageA, $messageB);
}
public function test_add_parameter_returns_clone(): void
{
$messageA = FakeNodeMessage::any();
$messageB = $messageA->withParameter('some_parameter', 'some value');
self::assertNotSame($messageA, $messageB);
}
public function test_custom_locale_returns_clone(): void
{
$messageA = FakeNodeMessage::any();