Valinor/tests/Integration/Mapping/Object/ArrayValuesMappingTest.php

194 lines
7.8 KiB
PHP
Raw Normal View History

2021-11-28 17:43:02 +01:00
<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Integration\Mapping\Object;
2021-11-28 17:43:02 +01:00
use CuyZ\Valinor\Mapper\MappingError;
use CuyZ\Valinor\MapperBuilder;
2021-11-28 17:43:02 +01:00
use CuyZ\Valinor\Tests\Integration\IntegrationTest;
use CuyZ\Valinor\Tests\Integration\Mapping\Fixture\SimpleObject;
use CuyZ\Valinor\Tests\Integration\Mapping\Fixture\SimpleObject as SimpleObjectAlias;
final class ArrayValuesMappingTest extends IntegrationTest
{
public function test_values_are_mapped_properly(): void
{
$source = [
'booleans' => [true, false, true],
'floats' => [42.404, 404.42],
'integers' => [42, 404, 1337],
'strings' => ['foo', 'bar', 'baz'],
'arrayWithDefaultKeyType' => [42 => 'foo', 'some-key' => 'bar'],
'arrayWithIntegerKeyType' => [1337 => 'foo', 42.0 => 'bar', '404' => 'baz'],
'arrayWithStringKeyType' => [1337 => 'foo', 42.0 => 'bar', 'some-key' => 'baz'],
'simpleArray' => [42 => 'foo', 'some-key' => 'bar'],
'objects' => [
'foo' => ['value' => 'foo'],
'bar' => ['value' => 'bar'],
'baz' => ['value' => 'baz'],
],
'objectsWithAlias' => [
'foo' => ['value' => 'foo'],
'bar' => ['value' => 'bar'],
'baz' => ['value' => 'baz'],
],
'nonEmptyArraysOfStrings' => ['foo', 'bar', 'baz'],
'nonEmptyArrayWithDefaultKeyType' => [42 => 'foo', 'some-key' => 'bar'],
'nonEmptyArrayWithIntegerKeyType' => [1337 => 'foo', 42.0 => 'bar', '404' => 'baz'],
'nonEmptyArrayWithStringKeyType' => [1337 => 'foo', 42.0 => 'bar', 'some-key' => 'baz'],
];
foreach ([ArrayValues::class, ArrayValuesWithConstructor::class] as $class) {
try {
$result = (new MapperBuilder())->mapper()->map($class, $source);
2021-11-28 17:43:02 +01:00
} catch (MappingError $error) {
$this->mappingFail($error);
}
self::assertSame($source['booleans'], $result->booleans);
self::assertSame($source['floats'], $result->floats);
self::assertSame($source['integers'], $result->integers);
self::assertSame($source['strings'], $result->strings);
self::assertSame($source['arrayWithDefaultKeyType'], $result->arrayWithDefaultKeyType);
self::assertSame($source['arrayWithIntegerKeyType'], $result->arrayWithIntegerKeyType);
self::assertSame($source['arrayWithStringKeyType'], $result->arrayWithStringKeyType);
self::assertSame($source['simpleArray'], $result->simpleArray);
self::assertSame('foo', $result->objects['foo']->value);
self::assertSame('bar', $result->objects['bar']->value);
self::assertSame('baz', $result->objects['baz']->value);
self::assertSame('foo', $result->objectsWithAlias['foo']->value);
self::assertSame('bar', $result->objectsWithAlias['bar']->value);
self::assertSame('baz', $result->objectsWithAlias['baz']->value);
self::assertSame($source['nonEmptyArraysOfStrings'], $result->nonEmptyArraysOfStrings);
self::assertSame($source['nonEmptyArrayWithDefaultKeyType'], $result->nonEmptyArrayWithDefaultKeyType);
self::assertSame($source['nonEmptyArrayWithIntegerKeyType'], $result->nonEmptyArrayWithIntegerKeyType);
self::assertSame($source['nonEmptyArrayWithStringKeyType'], $result->nonEmptyArrayWithStringKeyType);
}
}
public function test_empty_array_in_non_empty_array_throws_exception(): void
{
try {
(new MapperBuilder())->mapper()->map(ArrayValues::class, [
2021-11-28 17:43:02 +01:00
'nonEmptyArraysOfStrings' => [],
]);
} catch (MappingError $exception) {
feat!: add access to root node when error occurs during mapping When an error occurs during mapping, the root instance of `Node` can now be accessed from the exception. This recursive object allows retrieving all needed information through the whole mapping tree: path, values, types and messages, including the issues that caused the exception. It can be used like the following: ```php try { (new \CuyZ\Valinor\MapperBuilder()) ->mapper() ->map(SomeClass::class, [/* ... */]); } catch (\CuyZ\Valinor\Mapper\MappingError $error) { // Do something with `$error->node()` // See README for more information } ``` This change removes the method `MappingError::describe()` which provided a flattened view of messages of all the errors that were encountered during the mapping. The same behaviour can still be retrieved, see the example below: ```php use CuyZ\Valinor\Mapper\Tree\Message\Message; use CuyZ\Valinor\Mapper\Tree\Node; /** * @implements \IteratorAggregate<string, array<\Throwable&Message>> */ final class MappingErrorList implements \IteratorAggregate { private Node $node; public function __construct(Node $node) { $this->node = $node; } /** * @return \Traversable<string, array<\Throwable&Message>> */ public function getIterator(): \Traversable { yield from $this->errors($this->node); } /** * @return \Traversable<string, array<\Throwable&Message>> */ private function errors(Node $node): \Traversable { $errors = array_filter( $node->messages(), static fn (Message $m) => $m instanceof \Throwable ); if (! empty($errors)) { yield $node->path() => array_values($errors); } foreach ($node->children() as $child) { yield from $this->errors($child); } } } try { (new \CuyZ\Valinor\MapperBuilder()) ->mapper() ->map(SomeClass::class, [/* ... */]); } catch (\CuyZ\Valinor\Mapper\MappingError $error) { $errors = iterator_to_array(new MappingErrorList($error->node())); } ``` The class `CannotMapObject` is deleted, as it does not provide any value; this means that `MappingError` which was previously an interface becomes a class.
2021-12-16 00:00:45 +01:00
$error = $exception->node()->children()['nonEmptyArraysOfStrings']->messages()[0];
self::assertSame('1630678334', $error->code());
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
self::assertSame('Value array (empty) does not match type `non-empty-array<string>`.', (string)$error);
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
public function test_value_with_invalid_type_throws_exception(): void
2021-11-28 17:43:02 +01:00
{
try {
(new MapperBuilder())->mapper()->map(ArrayValues::class, [
2021-11-28 17:43:02 +01:00
'integers' => ['foo'],
]);
} catch (MappingError $exception) {
feat!: add access to root node when error occurs during mapping When an error occurs during mapping, the root instance of `Node` can now be accessed from the exception. This recursive object allows retrieving all needed information through the whole mapping tree: path, values, types and messages, including the issues that caused the exception. It can be used like the following: ```php try { (new \CuyZ\Valinor\MapperBuilder()) ->mapper() ->map(SomeClass::class, [/* ... */]); } catch (\CuyZ\Valinor\Mapper\MappingError $error) { // Do something with `$error->node()` // See README for more information } ``` This change removes the method `MappingError::describe()` which provided a flattened view of messages of all the errors that were encountered during the mapping. The same behaviour can still be retrieved, see the example below: ```php use CuyZ\Valinor\Mapper\Tree\Message\Message; use CuyZ\Valinor\Mapper\Tree\Node; /** * @implements \IteratorAggregate<string, array<\Throwable&Message>> */ final class MappingErrorList implements \IteratorAggregate { private Node $node; public function __construct(Node $node) { $this->node = $node; } /** * @return \Traversable<string, array<\Throwable&Message>> */ public function getIterator(): \Traversable { yield from $this->errors($this->node); } /** * @return \Traversable<string, array<\Throwable&Message>> */ private function errors(Node $node): \Traversable { $errors = array_filter( $node->messages(), static fn (Message $m) => $m instanceof \Throwable ); if (! empty($errors)) { yield $node->path() => array_values($errors); } foreach ($node->children() as $child) { yield from $this->errors($child); } } } try { (new \CuyZ\Valinor\MapperBuilder()) ->mapper() ->map(SomeClass::class, [/* ... */]); } catch (\CuyZ\Valinor\Mapper\MappingError $error) { $errors = iterator_to_array(new MappingErrorList($error->node())); } ``` The class `CannotMapObject` is deleted, as it does not provide any value; this means that `MappingError` which was previously an interface becomes a class.
2021-12-16 00:00:45 +01:00
$error = $exception->node()->children()['integers']->children()[0]->messages()[0];
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
self::assertSame('1655030601', $error->code());
self::assertSame("Value 'foo' does not match type `int`.", (string)$error);
2021-11-28 17:43:02 +01:00
}
}
}
class ArrayValues
{
/** @var array<bool> */
public array $booleans;
/** @var array<float> */
public array $floats;
/** @var array<int> */
public array $integers;
/** @var array<string> */
public array $strings;
/** @var array<array-key, string> */
public array $arrayWithDefaultKeyType;
/** @var array<int, string> */
public array $arrayWithIntegerKeyType;
/** @var array<string, string> */
public array $arrayWithStringKeyType;
/** @var string[] */
public array $simpleArray;
/** @var array<SimpleObject> */
public array $objects;
/** @var array<SimpleObjectAlias> */
public array $objectsWithAlias;
/** @var non-empty-array<string> */
public array $nonEmptyArraysOfStrings = ['foo'];
/** @var non-empty-array<array-key, string> */
public array $nonEmptyArrayWithDefaultKeyType = ['foo'];
/** @var non-empty-array<int, string> */
public array $nonEmptyArrayWithIntegerKeyType = ['foo'];
/** @var non-empty-array<string, string> */
public array $nonEmptyArrayWithStringKeyType = ['foo' => 'bar'];
}
class ArrayValuesWithConstructor extends ArrayValues
{
/**
* @param array<bool> $booleans
* @param array<float> $floats
* @param array<int> $integers
* @param array<string> $strings
* @param array<array-key, string> $arrayWithDefaultKeyType
* @param array<int, string> $arrayWithIntegerKeyType
* @param array<string, string> $arrayWithStringKeyType
* @param string[] $simpleArray
* @param array<SimpleObject> $objects
* @param array<SimpleObjectAlias> $objectsWithAlias
* @param non-empty-array<string> $nonEmptyArraysOfStrings
* @param non-empty-array<array-key, string> $nonEmptyArrayWithDefaultKeyType
* @param non-empty-array<int, string> $nonEmptyArrayWithIntegerKeyType
* @param non-empty-array<string, string> $nonEmptyArrayWithStringKeyType
*/
public function __construct(
array $booleans,
array $floats,
array $integers,
array $strings,
array $arrayWithDefaultKeyType,
array $arrayWithIntegerKeyType,
array $arrayWithStringKeyType,
array $simpleArray,
array $objects,
array $objectsWithAlias,
array $nonEmptyArraysOfStrings,
array $nonEmptyArrayWithDefaultKeyType,
array $nonEmptyArrayWithIntegerKeyType,
array $nonEmptyArrayWithStringKeyType
) {
$this->booleans = $booleans;
$this->floats = $floats;
$this->integers = $integers;
$this->strings = $strings;
$this->arrayWithDefaultKeyType = $arrayWithDefaultKeyType;
$this->arrayWithIntegerKeyType = $arrayWithIntegerKeyType;
$this->arrayWithStringKeyType = $arrayWithStringKeyType;
$this->simpleArray = $simpleArray;
$this->objects = $objects;
$this->objectsWithAlias = $objectsWithAlias;
$this->nonEmptyArraysOfStrings = $nonEmptyArraysOfStrings;
$this->nonEmptyArrayWithDefaultKeyType = $nonEmptyArrayWithDefaultKeyType;
$this->nonEmptyArrayWithIntegerKeyType = $nonEmptyArrayWithIntegerKeyType;
$this->nonEmptyArrayWithStringKeyType = $nonEmptyArrayWithStringKeyType;
}
}