Valinor/tests/Integration/Mapping/Attribute/ObjectBuilderStrategyMappingTest.php

130 lines
3.5 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\Attribute;
use Attribute;
use CuyZ\Valinor\Attribute\StaticMethodConstructor;
use CuyZ\Valinor\Definition\ClassDefinition;
use CuyZ\Valinor\Mapper\MappingError;
use CuyZ\Valinor\Mapper\Object\Exception\TooManyObjectBuilderFactoryAttributes;
use CuyZ\Valinor\Mapper\Object\Factory\ObjectBuilderFactory;
use CuyZ\Valinor\MapperBuilder;
use CuyZ\Valinor\Tests\Fake\Mapper\Object\FakeObjectBuilder;
2021-11-28 17:43:02 +01:00
use CuyZ\Valinor\Tests\Integration\IntegrationTest;
use RuntimeException;
2021-11-28 17:43:02 +01:00
final class ObjectBuilderStrategyMappingTest extends IntegrationTest
{
public function test_object_builder_attribute_is_used(): void
{
try {
$result = (new MapperBuilder())->mapper()->map(ObjectWithBuilderStrategyAttribute::class, [
'foo' => 'foo',
'bar' => 'bar',
]);
2021-11-28 17:43:02 +01:00
} catch (MappingError $error) {
$this->mappingFail($error);
}
self::assertSame('foo', $result->foo);
self::assertSame('bar', $result->bar);
2021-11-28 17:43:02 +01:00
self::assertTrue($result->staticConstructorCalled);
}
public function test_named_constructor_throwing_exception_is_caught_by_mapper(): void
{
try {
(new MapperBuilder())->mapper()->map(ObjectWithFailingBuilderStrategyAttribute::class, []);
} catch (MappingError $exception) {
$error = $exception->node()->messages()[0];
self::assertSame('some exception', (string)$error);
}
}
2021-11-28 17:43:02 +01:00
public function test_repeated_object_builder_factory_attributes_throws_exception(): void
{
$factoryClass = ObjectBuilderFactory::class;
$objectClass = ObjectWithSeveralBuilderStrategyAttributes::class;
$this->expectException(TooManyObjectBuilderFactoryAttributes::class);
$this->expectExceptionCode(1634044714);
$this->expectExceptionMessage("Only one attribute of type `$factoryClass` is allowed, class `$objectClass` contains 2.");
(new MapperBuilder())->mapper()->map($objectClass, 'foo');
2021-11-28 17:43:02 +01:00
}
}
/**
* @Annotation
*/
#[Attribute(Attribute::TARGET_CLASS)]
final class ForeignAttribute
{
}
2021-11-28 17:43:02 +01:00
/**
* @Annotation
*/
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
final class ObjectBuilderStrategyAttribute implements ObjectBuilderFactory
{
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 for(ClassDefinition $class): iterable
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
return [new FakeObjectBuilder()];
2021-11-28 17:43:02 +01:00
}
}
/**
* @ForeignAttribute
2021-11-28 17:43:02 +01:00
* @StaticMethodConstructor("create")
*/
#[ForeignAttribute]
2021-11-28 17:43:02 +01:00
#[StaticMethodConstructor('create')]
final class ObjectWithBuilderStrategyAttribute
{
public bool $staticConstructorCalled = false;
public string $foo;
public string $bar;
private function __construct(string $foo, string $bar)
2021-11-28 17:43:02 +01:00
{
$this->foo = $foo;
$this->bar = $bar;
2021-11-28 17:43:02 +01:00
}
public static function create(string $foo, string $bar = 'optional value'): self
2021-11-28 17:43:02 +01:00
{
$instance = new self($foo, $bar);
2021-11-28 17:43:02 +01:00
$instance->staticConstructorCalled = true;
return $instance;
}
}
/**
* @StaticMethodConstructor("failingConstructor")
*/
#[StaticMethodConstructor('failingConstructor')]
final class ObjectWithFailingBuilderStrategyAttribute
{
public static function failingConstructor(): self
{
throw new RuntimeException('some exception');
}
}
2021-11-28 17:43:02 +01:00
/**
* @ObjectBuilderStrategyAttribute
* @ObjectBuilderStrategyAttribute
*/
#[ObjectBuilderStrategyAttribute]
#[ObjectBuilderStrategyAttribute]
final class ObjectWithSeveralBuilderStrategyAttributes
{
}