2021-11-28 17:43:02 +01:00
< ? php
declare ( strict_types = 1 );
namespace CuyZ\Valinor\Tests\Unit\Mapper\Object ;
use CuyZ\Valinor\Mapper\Object\Exception\ConstructorMethodIsNotPublic ;
use CuyZ\Valinor\Mapper\Object\Exception\ConstructorMethodIsNotStatic ;
use CuyZ\Valinor\Mapper\Object\Exception\InvalidConstructorMethodClassReturnType ;
use CuyZ\Valinor\Mapper\Object\Exception\MethodNotFound ;
use CuyZ\Valinor\Mapper\Object\MethodObjectBuilder ;
2021-12-31 13:10:20 +01:00
use CuyZ\Valinor\Mapper\Tree\Message\ThrowableMessage ;
2021-11-28 17:43:02 +01:00
use CuyZ\Valinor\Tests\Fake\Definition\FakeClassDefinition ;
use PHPUnit\Framework\TestCase ;
use ReflectionClass ;
use RuntimeException ;
use stdClass ;
use function get_class ;
final class MethodObjectBuilderTest extends TestCase
{
public function test_build_object_with_constructor_returns_correct_object () : void
{
$object = new class ( ' foo ', ' bar ' ) {
public string $valueA ;
public string $valueB ;
public string $valueC ;
public function __construct (
string $valueA ,
string $valueB ,
string $valueC = 'Some parameter default value'
) {
$this -> valueA = $valueA ;
$this -> valueB = $valueB ;
$this -> valueC = $valueC ;
}
};
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $object ));
$objectBuilder = new MethodObjectBuilder ( $class , '__construct' );
$result = $objectBuilder -> build ([
'valueA' => 'valueA' ,
'valueB' => 'valueB' ,
'valueC' => 'valueC' ,
]);
self :: assertSame ( 'valueA' , $result -> valueA ); // @phpstan-ignore-line
self :: assertSame ( 'valueB' , $result -> valueB ); // @phpstan-ignore-line
self :: assertSame ( 'valueC' , $result -> valueC ); // @phpstan-ignore-line
}
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_signature_is_method_signature () : void
{
$object = new class ( ) {
public function __construct ()
{
}
};
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $object ));
$objectBuilder = new MethodObjectBuilder ( $class , '__construct' );
self :: assertSame ( 'Signature::__construct' , $objectBuilder -> signature ());
}
2021-11-28 17:43:02 +01:00
public function test_not_existing_method_throws_exception () : void
{
$this -> expectException ( MethodNotFound :: class );
$this -> expectExceptionCode ( 1634044209 );
$this -> expectExceptionMessage ( 'Method `notExistingMethod` was not found in class `stdClass`.' );
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( stdClass :: class ));
new MethodObjectBuilder ( $class , 'notExistingMethod' );
}
public function test_invalid_constructor_method_throws_exception () : void
{
$this -> expectException ( ConstructorMethodIsNotStatic :: class );
$this -> expectExceptionCode ( 1634044370 );
$this -> expectExceptionMessage ( 'Invalid constructor method `Signature::invalidConstructor`: it is neither the constructor nor a static constructor.' );
$object = new class ( ) {
public function invalidConstructor () : void
{
}
};
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $object ));
new MethodObjectBuilder ( $class , 'invalidConstructor' );
}
public function test_invalid_constructor_method_return_type_throws_exception () : void
{
$object = new class ( ) {
feat: introduce automatic named constructor resolution
An object may have several ways of being created — in such cases it is
common to use so-called named constructors, also known as static factory
methods. If one or more are found, they can be called during the mapping
to create an instance of the object.
What defines a named constructor is a method that:
1. is public
2. is static
3. returns an instance of the object
4. has one or more arguments
```php
final class Color
{
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
private function __construct(
public readonly int $red,
public readonly int $green,
public readonly int $blue
) {}
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
public static function fromRgb(
int $red,
int $green,
int $blue,
): self {
return new self($red, $green, $blue);
}
/**
* @param non-empty-string $hex
*/
public static function fromHex(string $hex): self
{
if (strlen($hex) !== 6) {
throw new DomainException('Must be 6 characters long');
}
/** @var int<0, 255> $red */
$red = hexdec(substr($hex, 0, 2));
/** @var int<0, 255> $green */
$green = hexdec(substr($hex, 2, 2));
/** @var int<0, 255> $blue */
$blue = hexdec(substr($hex, 4, 2));
return new self($red, $green, $blue);
}
}
```
2022-01-21 19:14:00 +01:00
public static function invalidConstructor () : bool
2021-11-28 17:43:02 +01:00
{
feat: introduce automatic named constructor resolution
An object may have several ways of being created — in such cases it is
common to use so-called named constructors, also known as static factory
methods. If one or more are found, they can be called during the mapping
to create an instance of the object.
What defines a named constructor is a method that:
1. is public
2. is static
3. returns an instance of the object
4. has one or more arguments
```php
final class Color
{
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
private function __construct(
public readonly int $red,
public readonly int $green,
public readonly int $blue
) {}
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
public static function fromRgb(
int $red,
int $green,
int $blue,
): self {
return new self($red, $green, $blue);
}
/**
* @param non-empty-string $hex
*/
public static function fromHex(string $hex): self
{
if (strlen($hex) !== 6) {
throw new DomainException('Must be 6 characters long');
}
/** @var int<0, 255> $red */
$red = hexdec(substr($hex, 0, 2));
/** @var int<0, 255> $green */
$green = hexdec(substr($hex, 2, 2));
/** @var int<0, 255> $blue */
$blue = hexdec(substr($hex, 4, 2));
return new self($red, $green, $blue);
}
}
```
2022-01-21 19:14:00 +01:00
return true ;
2021-11-28 17:43:02 +01:00
}
};
feat: introduce automatic named constructor resolution
An object may have several ways of being created — in such cases it is
common to use so-called named constructors, also known as static factory
methods. If one or more are found, they can be called during the mapping
to create an instance of the object.
What defines a named constructor is a method that:
1. is public
2. is static
3. returns an instance of the object
4. has one or more arguments
```php
final class Color
{
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
private function __construct(
public readonly int $red,
public readonly int $green,
public readonly int $blue
) {}
/**
* @param int<0, 255> $red
* @param int<0, 255> $green
* @param int<0, 255> $blue
*/
public static function fromRgb(
int $red,
int $green,
int $blue,
): self {
return new self($red, $green, $blue);
}
/**
* @param non-empty-string $hex
*/
public static function fromHex(string $hex): self
{
if (strlen($hex) !== 6) {
throw new DomainException('Must be 6 characters long');
}
/** @var int<0, 255> $red */
$red = hexdec(substr($hex, 0, 2));
/** @var int<0, 255> $green */
$green = hexdec(substr($hex, 2, 2));
/** @var int<0, 255> $blue */
$blue = hexdec(substr($hex, 4, 2));
return new self($red, $green, $blue);
}
}
```
2022-01-21 19:14:00 +01:00
$this -> expectException ( InvalidConstructorMethodClassReturnType :: class );
$this -> expectExceptionCode ( 1638094499 );
$this -> expectExceptionMessage ( 'Method `Signature::invalidConstructor` must return `' . get_class ( $object ) . '` to be a valid constructor but returns `bool`.' );
2021-11-28 17:43:02 +01:00
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $object ));
new MethodObjectBuilder ( $class , 'invalidConstructor' );
}
public function test_invalid_constructor_method_class_return_type_throws_exception () : void
{
$object = new class ( ) {
public static function invalidConstructor () : stdClass
{
return new stdClass ();
}
};
$this -> expectException ( InvalidConstructorMethodClassReturnType :: class );
$this -> expectExceptionCode ( 1638094499 );
$this -> expectExceptionMessage ( 'Method `Signature::invalidConstructor` must return `' . get_class ( $object ) . '` to be a valid constructor but returns `stdClass`.' );
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $object ));
new MethodObjectBuilder ( $class , 'invalidConstructor' );
}
public function test_exception_thrown_by_constructor_is_caught_and_wrapped () : void
{
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( ObjectWithConstructorThatThrowsException :: class ));
$objectBuilder = new MethodObjectBuilder ( $class , '__construct' );
2021-12-31 13:10:20 +01:00
$this -> expectException ( ThrowableMessage :: class );
$this -> expectExceptionCode ( 1337 );
2021-11-28 17:43:02 +01:00
$this -> expectExceptionMessage ( 'some exception' );
$objectBuilder -> build ([]);
}
public function test_constructor_builder_for_class_with_private_constructor_throws_exception () : void
{
$this -> expectException ( ConstructorMethodIsNotPublic :: class );
$this -> expectExceptionCode ( 1630937169 );
2022-03-11 12:25:47 +01:00
$this -> expectExceptionMessage ( 'The constructor of the class `' . ObjectWithPrivateNativeConstructor :: class . '` is not public.' );
2021-11-28 17:43:02 +01:00
2022-03-11 12:25:47 +01:00
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( ObjectWithPrivateNativeConstructor :: class ));
new MethodObjectBuilder ( $class , '__construct' );
}
public function test_constructor_builder_for_class_with_private_named_constructor_throws_exception () : void
{
$classWithPrivateNativeConstructor = new class ( ) {
// @phpstan-ignore-next-line
private static function someConstructor () : void
{
}
};
$this -> expectException ( ConstructorMethodIsNotPublic :: class );
$this -> expectExceptionCode ( 1630937169 );
$this -> expectExceptionMessage ( 'The named constructor `Signature::someConstructor` is not public.' );
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $classWithPrivateNativeConstructor ));
2021-11-28 17:43:02 +01:00
new MethodObjectBuilder ( $class , 'someConstructor' );
}
2022-03-30 23:09:19 +02:00
public function test_arguments_instance_stays_the_same () : void
{
$class = new class ( ' foo ' ) {
public string $string ;
public function __construct ( string $string )
{
$this -> string = $string ;
}
};
$class = FakeClassDefinition :: fromReflection ( new ReflectionClass ( $class ));
$objectBuilder = new MethodObjectBuilder ( $class , '__construct' );
$argumentsA = $objectBuilder -> describeArguments ();
$argumentsB = $objectBuilder -> describeArguments ();
self :: assertSame ( $argumentsA , $argumentsB );
}
2021-11-28 17:43:02 +01:00
}
2022-03-11 12:25:47 +01:00
final class ObjectWithPrivateNativeConstructor
2021-11-28 17:43:02 +01:00
{
2022-03-11 12:25:47 +01:00
private function __construct ()
2021-11-28 17:43:02 +01:00
{
}
}
final class ObjectWithConstructorThatThrowsException
{
public function __construct ()
{
2021-12-31 13:10:20 +01:00
throw new RuntimeException ( 'some exception' , 1337 );
2021-11-28 17:43:02 +01:00
}
}