Valinor/tests/Unit/Mapper/Tree/Message/NodeMessageTest.php
Romain Canon 60a6656141 feat!: improve message customization with formatters
The way messages can be customized has been totally revisited, requiring
several breaking changes. All existing error messages have been
rewritten to better fit the actual meaning of the error.

The content of a message can be changed to fit custom use cases; it can
contain placeholders that will be replaced with useful information.

The placeholders below are always available; even more may be used
depending on the original message.

- `{message_code}` — the code of the message
- `{node_name}` — name of the node to which the message is bound
- `{node_path}` — path of the node to which the message is bound
- `{node_type}` — type of the node to which the message is bound
- `{original_value}` — the source value that was given to the node
- `{original_message}` — the original message before being customized

```php
try {
    (new \CuyZ\Valinor\MapperBuilder())
        ->mapper()
        ->map(SomeClass::class, [/* … */]);
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
    $messages = new MessagesFlattener($error->node());

    foreach ($messages as $message) {
        if ($message->code() === 'some_code') {
            $message = $message->withBody('new / {original_message}');
        }

        echo $message;
    }
}
```

The messages are formatted using the ICU library, enabling the
placeholders to use advanced syntax to perform proper translations, for
instance currency support.

```php
try {
    (new MapperBuilder())->mapper()->map('int<0, 100>', 1337);
} catch (\CuyZ\Valinor\Mapper\MappingError $error) {
    $message = $error->node()->messages()[0];

    if (is_numeric($message->value())) {
        $message = $message->withBody(
            'Invalid amount {original_value, number, currency}'
        );
    }

    // Invalid amount: $1,337.00
    echo $message->withLocale('en_US');

    // Invalid amount: £1,337.00
    echo $message->withLocale('en_GB');

    // Invalid amount: 1 337,00 €
    echo $message->withLocale('fr_FR');
}
```

If the `intl` extension is not installed, a shim will be available to
replace the placeholders, but it won't handle advanced syntax as
described above.

---

The new formatter `TranslationMessageFormatter` can be used to translate
the content of messages.

The library provides a list of all messages that can be returned; this
list can be filled or modified with custom translations.

```php
TranslationMessageFormatter::default()
    // Create/override a single entry…
    ->withTranslation(
        'fr',
        'some custom message',
        'un message personnalisé'
    )
    // …or several entries.
    ->withTranslations([
        'some custom message' => [
            'en' => 'Some custom message',
            'fr' => 'Un message personnalisé',
            'es' => 'Un mensaje personalizado',
        ],
        'some other message' => [
            // …
        ],
    ])
    ->format($message);
```

It is possible to join several formatters into one formatter by using
the `AggregateMessageFormatter`. This instance can then easily be
injected in a service that will handle messages.

The formatters will be called in the same order they are given to the
aggregate.

```php
(new AggregateMessageFormatter(
    new LocaleMessageFormatter('fr'),
    new MessageMapFormatter([
        // …
    ],
    TranslationMessageFormatter::default(),
))->format($message)
```

BREAKING CHANGE: The method `NodeMessage::format` has been removed,
message formatters should be used instead. If needed, the old behaviour
can be retrieved with the formatter `PlaceHolderMessageFormatter`,
although it is strongly advised to use the new placeholders feature.

BREAKING CHANGE: The signature of the method `MessageFormatter::format`
has changed.
2022-05-21 16:30:24 +02:00

119 lines
4.4 KiB
PHP

<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Unit\Mapper\Tree\Message;
use CuyZ\Valinor\Mapper\Tree\Message\Message;
use CuyZ\Valinor\Mapper\Tree\Message\NodeMessage;
use CuyZ\Valinor\Tests\Fake\Definition\FakeAttributes;
use CuyZ\Valinor\Tests\Fake\Mapper\FakeShell;
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Message\FakeErrorMessage;
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Message\FakeMessage;
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Message\FakeNodeMessage;
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Message\FakeTranslatableMessage;
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Message\Formatter\FakeMessageFormatter;
use CuyZ\Valinor\Tests\Fake\Type\FakeType;
use PHPUnit\Framework\TestCase;
final class NodeMessageTest extends TestCase
{
public function test_node_properties_can_be_accessed(): void
{
$originalMessage = new FakeMessage();
$type = FakeType::permissive();
$attributes = new FakeAttributes();
$shell = FakeShell::any()->child('foo', $type, 'some value', $attributes);
$message = new NodeMessage($shell, $originalMessage);
self::assertSame('foo', $message->name());
self::assertSame('foo', $message->path());
self::assertSame('some value', $message->value());
self::assertSame($type, $message->type());
self::assertSame($attributes, $message->attributes());
self::assertSame($originalMessage, $message->originalMessage());
}
public function test_message_is_error_if_original_message_is_throwable(): void
{
$originalMessage = new FakeErrorMessage();
$message = new NodeMessage(FakeShell::any(), $originalMessage);
self::assertTrue($message->isError());
self::assertSame('1652883436', $message->code());
self::assertSame('some error message', $message->body());
}
public function test_parameters_are_replaced_in_body(): void
{
$originalMessage = new FakeTranslatableMessage('some original message', ['some_parameter' => 'some parameter value']);
$type = FakeType::permissive();
$shell = FakeShell::any()->child('foo', $type, 'some value');
$message = new NodeMessage($shell, $originalMessage);
$message = $message->withBody('{message_code} / {node_name} / {node_path} / {node_type} / {original_value} / {original_message} / {some_parameter}');
self::assertSame("1652902453 / foo / foo / `$type` / 'some value' / some original message (toString) / some parameter value", (string)$message);
}
public function test_replaces_correct_original_message_if_throwable(): void
{
$message = new NodeMessage(FakeShell::any(), new FakeErrorMessage('some error message'));
$message = $message->withBody('original: {original_message}');
self::assertSame('original: some error message', (string)$message);
}
public function test_format_message_uses_formatter_to_replace_content(): void
{
$originalMessage = new FakeMessage('some message');
$message = new NodeMessage(FakeShell::any(), $originalMessage);
$formattedMessage = (new FakeMessageFormatter())->format($message);
self::assertNotSame($message, $formattedMessage);
self::assertSame('formatted: some message', (string)$formattedMessage);
}
public function test_custom_body_returns_clone(): void
{
$messageA = FakeNodeMessage::any();
$messageB = $messageA->withBody('some other message');
self::assertNotSame($messageA, $messageB);
}
public function test_custom_locale_returns_clone(): void
{
$messageA = FakeNodeMessage::any();
$messageB = $messageA->withLocale('fr');
self::assertNotSame($messageA, $messageB);
}
public function test_custom_locale_is_used(): void
{
$originalMessage = new FakeTranslatableMessage('un message: {value, spellout}', ['value' => '42']);
$message = new NodeMessage(FakeShell::any(), $originalMessage);
$message = $message->withLocale('fr');
self::assertSame('un message: quarante-deux', (string)$message);
}
public function test_message_with_no_code_returns_unknown(): void
{
$originalMessage = new class () implements Message {
public function __toString(): string
{
return 'some message';
}
};
$message = new NodeMessage(FakeShell::any(), $originalMessage);
self::assertSame('unknown', $message->code());
}
}