Valinor/tests/Unit/Mapper/Tree/Builder/ListNodeBuilderTest.php

42 lines
1.4 KiB
PHP
Raw Normal View History

2021-11-28 17:43:02 +01:00
<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Unit\Mapper\Tree\Builder;
use AssertionError;
use CuyZ\Valinor\Mapper\Tree\Builder\ListNodeBuilder;
use CuyZ\Valinor\Mapper\Tree\Builder\RootNodeBuilder;
use CuyZ\Valinor\Mapper\Tree\Exception\SourceMustBeIterable;
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-18 23:15:08 +02:00
use CuyZ\Valinor\Tests\Fake\Mapper\FakeShell;
2021-11-28 17:43:02 +01:00
use CuyZ\Valinor\Tests\Fake\Type\FakeType;
use CuyZ\Valinor\Type\Types\ListType;
use PHPUnit\Framework\TestCase;
final class ListNodeBuilderTest extends TestCase
{
feat!: make mapper more strict and allow flexible mode The mapper is now more type-sensitive and will fail in the following situations: - When a value does not match exactly the awaited scalar type, for instance a string `"42"` given to a node that awaits an integer. - When unnecessary array keys are present, for instance mapping an array `['foo' => …, 'bar' => …, 'baz' => …]` to an object that needs only `foo` and `bar`. - When permissive types like `mixed` or `object` are encountered. These limitations can be bypassed by enabling the flexible mode: ```php (new \CuyZ\Valinor\MapperBuilder()) ->flexible() ->mapper(); ->map('array{foo: int, bar: bool}', [ 'foo' => '42', // Will be cast from `string` to `int` 'bar' => 'true', // Will be cast from `string` to `bool` 'baz' => '…', // Will be ignored ]); ``` When using this library for a provider application — for instance an API endpoint that can be called with a JSON payload — it is recommended to use the strict mode. This ensures that the consumers of the API provide the exact awaited data structure, and prevents unknown values to be passed. When using this library as a consumer of an external source, it can make sense to enable the flexible mode. This allows for instance to convert string numeric values to integers or to ignore data that is present in the source but not needed in the application. --- All these changes led to a new check that runs on all registered object constructors. If a collision is found between several constructors that have the same signature (the same parameter names), an exception will be thrown. ```php final class SomeClass { public static function constructorA(string $foo, string $bar): self { // … } public static function constructorB(string $foo, string $bar): self { // … } } (new \CuyZ\Valinor\MapperBuilder()) ->registerConstructor( SomeClass::constructorA(...), SomeClass::constructorB(...), ) ->mapper(); ->map(SomeClass::class, [ 'foo' => 'foo', 'bar' => 'bar', ]); // Exception: A collision was detected […] ```
2022-06-23 10:30:36 +02:00
public function test_build_with_null_value_in_flexible_mode_returns_empty_branch_node(): void
2021-11-28 17:43:02 +01:00
{
feat!: make mapper more strict and allow flexible mode The mapper is now more type-sensitive and will fail in the following situations: - When a value does not match exactly the awaited scalar type, for instance a string `"42"` given to a node that awaits an integer. - When unnecessary array keys are present, for instance mapping an array `['foo' => …, 'bar' => …, 'baz' => …]` to an object that needs only `foo` and `bar`. - When permissive types like `mixed` or `object` are encountered. These limitations can be bypassed by enabling the flexible mode: ```php (new \CuyZ\Valinor\MapperBuilder()) ->flexible() ->mapper(); ->map('array{foo: int, bar: bool}', [ 'foo' => '42', // Will be cast from `string` to `int` 'bar' => 'true', // Will be cast from `string` to `bool` 'baz' => '…', // Will be ignored ]); ``` When using this library for a provider application — for instance an API endpoint that can be called with a JSON payload — it is recommended to use the strict mode. This ensures that the consumers of the API provide the exact awaited data structure, and prevents unknown values to be passed. When using this library as a consumer of an external source, it can make sense to enable the flexible mode. This allows for instance to convert string numeric values to integers or to ignore data that is present in the source but not needed in the application. --- All these changes led to a new check that runs on all registered object constructors. If a collision is found between several constructors that have the same signature (the same parameter names), an exception will be thrown. ```php final class SomeClass { public static function constructorA(string $foo, string $bar): self { // … } public static function constructorB(string $foo, string $bar): self { // … } } (new \CuyZ\Valinor\MapperBuilder()) ->registerConstructor( SomeClass::constructorA(...), SomeClass::constructorB(...), ) ->mapper(); ->map(SomeClass::class, [ 'foo' => 'foo', 'bar' => 'bar', ]); // Exception: A collision was detected […] ```
2022-06-23 10:30:36 +02:00
$node = (new RootNodeBuilder(new ListNodeBuilder(true)))->build(FakeShell::new(ListType::native()));
2021-11-28 17:43:02 +01:00
self::assertSame([], $node->value());
self::assertEmpty($node->children());
}
public function test_invalid_type_fails_assertion(): void
{
$this->expectException(AssertionError::class);
feat!: make mapper more strict and allow flexible mode The mapper is now more type-sensitive and will fail in the following situations: - When a value does not match exactly the awaited scalar type, for instance a string `"42"` given to a node that awaits an integer. - When unnecessary array keys are present, for instance mapping an array `['foo' => …, 'bar' => …, 'baz' => …]` to an object that needs only `foo` and `bar`. - When permissive types like `mixed` or `object` are encountered. These limitations can be bypassed by enabling the flexible mode: ```php (new \CuyZ\Valinor\MapperBuilder()) ->flexible() ->mapper(); ->map('array{foo: int, bar: bool}', [ 'foo' => '42', // Will be cast from `string` to `int` 'bar' => 'true', // Will be cast from `string` to `bool` 'baz' => '…', // Will be ignored ]); ``` When using this library for a provider application — for instance an API endpoint that can be called with a JSON payload — it is recommended to use the strict mode. This ensures that the consumers of the API provide the exact awaited data structure, and prevents unknown values to be passed. When using this library as a consumer of an external source, it can make sense to enable the flexible mode. This allows for instance to convert string numeric values to integers or to ignore data that is present in the source but not needed in the application. --- All these changes led to a new check that runs on all registered object constructors. If a collision is found between several constructors that have the same signature (the same parameter names), an exception will be thrown. ```php final class SomeClass { public static function constructorA(string $foo, string $bar): self { // … } public static function constructorB(string $foo, string $bar): self { // … } } (new \CuyZ\Valinor\MapperBuilder()) ->registerConstructor( SomeClass::constructorA(...), SomeClass::constructorB(...), ) ->mapper(); ->map(SomeClass::class, [ 'foo' => 'foo', 'bar' => 'bar', ]); // Exception: A collision was detected […] ```
2022-06-23 10:30:36 +02:00
(new RootNodeBuilder(new ListNodeBuilder(true)))->build(FakeShell::new(new FakeType()));
2021-11-28 17:43:02 +01:00
}
public function test_build_with_invalid_source_throws_exception(): void
{
$this->expectException(SourceMustBeIterable::class);
$this->expectExceptionCode(1618739163);
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-18 23:15:08 +02:00
$this->expectExceptionMessage("Value 'foo' does not match type `list`.");
2021-11-28 17:43:02 +01:00
feat!: make mapper more strict and allow flexible mode The mapper is now more type-sensitive and will fail in the following situations: - When a value does not match exactly the awaited scalar type, for instance a string `"42"` given to a node that awaits an integer. - When unnecessary array keys are present, for instance mapping an array `['foo' => …, 'bar' => …, 'baz' => …]` to an object that needs only `foo` and `bar`. - When permissive types like `mixed` or `object` are encountered. These limitations can be bypassed by enabling the flexible mode: ```php (new \CuyZ\Valinor\MapperBuilder()) ->flexible() ->mapper(); ->map('array{foo: int, bar: bool}', [ 'foo' => '42', // Will be cast from `string` to `int` 'bar' => 'true', // Will be cast from `string` to `bool` 'baz' => '…', // Will be ignored ]); ``` When using this library for a provider application — for instance an API endpoint that can be called with a JSON payload — it is recommended to use the strict mode. This ensures that the consumers of the API provide the exact awaited data structure, and prevents unknown values to be passed. When using this library as a consumer of an external source, it can make sense to enable the flexible mode. This allows for instance to convert string numeric values to integers or to ignore data that is present in the source but not needed in the application. --- All these changes led to a new check that runs on all registered object constructors. If a collision is found between several constructors that have the same signature (the same parameter names), an exception will be thrown. ```php final class SomeClass { public static function constructorA(string $foo, string $bar): self { // … } public static function constructorB(string $foo, string $bar): self { // … } } (new \CuyZ\Valinor\MapperBuilder()) ->registerConstructor( SomeClass::constructorA(...), SomeClass::constructorB(...), ) ->mapper(); ->map(SomeClass::class, [ 'foo' => 'foo', 'bar' => 'bar', ]); // Exception: A collision was detected […] ```
2022-06-23 10:30:36 +02:00
(new RootNodeBuilder(new ListNodeBuilder(true)))->build(FakeShell::new(ListType::native(), 'foo'));
2021-11-28 17:43:02 +01:00
}
}