Valinor/tests/Integration/Mapping/InterfaceInferringMappingTest.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

214 lines
7.9 KiB
PHP

<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Integration\Mapping;
use CuyZ\Valinor\Mapper\MappingError;
use CuyZ\Valinor\Mapper\Tree\Exception\InvalidInterfaceResolverReturnType;
use CuyZ\Valinor\Mapper\Tree\Exception\InvalidTypeResolvedForInterface;
use CuyZ\Valinor\Mapper\Tree\Exception\ResolvedTypeForInterfaceIsNotAccepted;
use CuyZ\Valinor\Tests\Integration\IntegrationTest;
use CuyZ\Valinor\Type\Resolver\Exception\CannotResolveTypeFromInterface;
use DateTime;
use DateTimeInterface;
use DomainException;
use stdClass;
final class InterfaceInferringMappingTest extends IntegrationTest
{
public function test_override_date_time_interface_inferring_overrides_correctly(): void
{
try {
$result = $this->mapperBuilder
->infer(DateTimeInterface::class, fn () => DateTime::class)
->mapper()
->map(DateTimeInterface::class, 1645279176);
} catch (MappingError $error) {
$this->mappingFail($error);
}
self::assertInstanceOf(DateTime::class, $result);
self::assertSame('1645279176', $result->format('U'));
}
public function test_infer_interface_with_single_argument_works_properly(): void
{
try {
[$resultA, $resultB] = $this->mapperBuilder
->infer(SomeInterface::class, function (string $type): string {
// @PHP8.0 use `match` with short closure
switch ($type) {
case 'classA-foo':
return SomeClassThatInheritsInterfaceA::class;
case 'classB-bar':
return SomeClassThatInheritsInterfaceB::class;
default:
self::fail("Type `$type` not handled.");
}
})
->mapper()
->map('list<' . SomeInterface::class . '>', [
'classA-foo',
['type' => 'classB-bar', 'valueB' => 'classB-bar'],
]);
} catch (MappingError $error) {
$this->mappingFail($error);
}
self::assertInstanceOf(SomeClassThatInheritsInterfaceA::class, $resultA);
self::assertInstanceOf(SomeClassThatInheritsInterfaceB::class, $resultB);
self::assertSame('classA-foo', $resultA->valueA);
self::assertSame('classB-bar', $resultB->valueB);
}
public function test_infer_interface_with_several_arguments_works_properly(): void
{
try {
[$resultA, $resultB] = $this->mapperBuilder
->infer(SomeInterface::class, function (string $type, int $key): string {
if ($type === 'classA' && $key === 42) {
return SomeClassThatInheritsInterfaceA::class;
} elseif ($type === 'classB' && $key === 1337) {
return SomeClassThatInheritsInterfaceB::class;
}
self::fail("Combinaison `$type` / `$key` not handled.");
})
->mapper()
->map('list<' . SomeInterface::class . '>', [
[
'type' => 'classA',
'key' => 42,
'valueA' => 'foo',
],
[
'type' => 'classB',
'key' => 1337,
'valueB' => 'bar',
],
]);
} catch (MappingError $error) {
$this->mappingFail($error);
}
self::assertInstanceOf(SomeClassThatInheritsInterfaceA::class, $resultA);
self::assertInstanceOf(SomeClassThatInheritsInterfaceB::class, $resultB);
self::assertSame('foo', $resultA->valueA);
self::assertSame('bar', $resultB->valueB);
}
public function test_unresolvable_interface_implementation_throws_exception(): void
{
$this->expectException(CannotResolveTypeFromInterface::class);
$this->expectExceptionCode(1618049116);
$this->expectExceptionMessage('Impossible to resolve an implementation for the interface `' . SomeInterface::class . '`.');
$this->mapperBuilder
->mapper()
->map(SomeInterface::class, []);
}
public function test_invalid_interface_resolver_return_type_throws_exception(): void
{
$this->expectException(InvalidInterfaceResolverReturnType::class);
$this->expectExceptionCode(1630091260);
$this->expectExceptionMessage('Invalid value 42; it must be the name of a class that implements `DateTimeInterface`.');
$this->mapperBuilder
->infer(DateTimeInterface::class, fn () => 42)
->mapper()
->map(DateTimeInterface::class, []);
}
public function test_invalid_interface_resolved_return_type_throws_exception(): void
{
$this->expectException(InvalidTypeResolvedForInterface::class);
$this->expectExceptionCode(1618049224);
$this->expectExceptionMessage('Invalid type `int`; it must be the name of a class that implements `DateTimeInterface`.');
$this->mapperBuilder
->infer(DateTimeInterface::class, fn () => 'int')
->mapper()
->map(DateTimeInterface::class, []);
}
public function test_invalid_resolved_interface_implementation_throws_exception(): void
{
$this->expectException(ResolvedTypeForInterfaceIsNotAccepted::class);
$this->expectExceptionCode(1618049487);
$this->expectExceptionMessage('The implementation `stdClass` is not accepted by the interface `DateTimeInterface`.');
$this->mapperBuilder
->infer(DateTimeInterface::class, fn () => stdClass::class)
->mapper()
->map(DateTimeInterface::class, []);
}
public function test_invalid_source_throws_exception(): void
{
try {
$this->mapperBuilder
->infer(SomeInterface::class, function (string $type, int $key): string {
return SomeClassThatInheritsInterfaceA::class;
})
->mapper()
->map(SomeInterface::class, 42);
} catch (MappingError $exception) {
$error = $exception->node()->messages()[0];
self::assertSame('1645283485', $error->code());
self::assertSame('Invalid value 42: it must be an array.', (string)$error);
}
}
public function test_invalid_source_value_throws_exception(): void
{
try {
$this->mapperBuilder
->infer(SomeInterface::class, function (int $key): string {
return SomeClassThatInheritsInterfaceA::class;
})
->mapper()
->map(SomeInterface::class, 'foo');
} catch (MappingError $exception) {
$error = $exception->node()->children()['key']->messages()[0];
self::assertSame('1618736242', $error->code());
self::assertSame("Cannot cast 'foo' to `int`.", (string)$error);
}
}
public function test_exception_thrown_is_caught_and_throws_message_exception(): void
{
try {
$this->mapperBuilder
->infer(DateTimeInterface::class, function () {
// @PHP8.0 use short closure
throw new DomainException('some error message', 1645303304);
})
->mapper()
->map(DateTimeInterface::class, 'foo');
} catch (MappingError $exception) {
$error = $exception->node()->messages()[0];
self::assertSame('1645303304', $error->code());
self::assertSame('some error message', (string)$error);
}
}
}
interface SomeInterface
{
}
final class SomeClassThatInheritsInterfaceA implements SomeInterface
{
public string $valueA;
}
final class SomeClassThatInheritsInterfaceB implements SomeInterface
{
public string $valueB;
}