Valinor/tests/Integration/Mapping/Object/DateTimeMappingTest.php
Romain Canon 90dc586018
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

148 lines
5.8 KiB
PHP

<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Integration\Mapping\Object;
use CuyZ\Valinor\Mapper\MappingError;
use CuyZ\Valinor\Mapper\Object\DateTimeObjectBuilder;
use CuyZ\Valinor\MapperBuilder;
use CuyZ\Valinor\Tests\Integration\IntegrationTest;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use function random_int;
final class DateTimeMappingTest extends IntegrationTest
{
public function test_datetime_properties_are_converted_properly(): void
{
$dateTimeInterface = new DateTimeImmutable('@' . $this->buildRandomTimestamp());
$dateTimeImmutable = new DateTimeImmutable('@' . $this->buildRandomTimestamp());
$dateTimeFromTimestamp = $this->buildRandomTimestamp();
$dateTimeFromTimestampWithOutFormat = [
'datetime' => $this->buildRandomTimestamp(),
];
$dateTimeFromTimestampWithFormat = [
'datetime' => $this->buildRandomTimestamp(),
'format' => 'U',
];
$dateTimeFromAtomFormat = (new DateTime())->setTimestamp($this->buildRandomTimestamp())->format(DATE_ATOM);
$dateTimeFromArray = [
'datetime' => (new DateTime('@' . $this->buildRandomTimestamp()))->format('Y-m-d H:i:s'),
'format' => 'Y-m-d H:i:s',
];
$mysqlDate = (new DateTime('@' . $this->buildRandomTimestamp()))->format('Y-m-d H:i:s');
$pgsqlDate = (new DateTime('@' . $this->buildRandomTimestamp()))->format('Y-m-d H:i:s.u');
$sqlDateNotTime = '2022-04-30';
try {
$result = (new MapperBuilder())->mapper()->map(AllDateTimeValues::class, [
'dateTimeInterface' => $dateTimeInterface,
'dateTimeImmutable' => $dateTimeImmutable,
'dateTimeFromTimestamp' => $dateTimeFromTimestamp,
'dateTimeFromTimestampWithOutFormat' => $dateTimeFromTimestampWithOutFormat,
'dateTimeFromTimestampWithFormat' => $dateTimeFromTimestampWithFormat,
'dateTimeFromAtomFormat' => $dateTimeFromAtomFormat,
'dateTimeFromArray' => $dateTimeFromArray,
'mysqlDate' => $mysqlDate,
'pgsqlDate' => $pgsqlDate,
'sqlDateNotTime' => $sqlDateNotTime,
]);
} catch (MappingError $error) {
$this->mappingFail($error);
}
self::assertInstanceOf(DateTimeImmutable::class, $result->dateTimeInterface);
self::assertEquals($dateTimeInterface, $result->dateTimeInterface);
self::assertEquals($dateTimeImmutable, $result->dateTimeImmutable);
self::assertEquals(new DateTimeImmutable("@$dateTimeFromTimestamp"), $result->dateTimeFromTimestamp);
self::assertEquals(new DateTimeImmutable("@{$dateTimeFromTimestampWithFormat['datetime']}"), $result->dateTimeFromTimestampWithFormat);
self::assertEquals(new DateTimeImmutable("@{$dateTimeFromTimestampWithOutFormat['datetime']}"), $result->dateTimeFromTimestampWithOutFormat);
self::assertEquals(DateTimeImmutable::createFromFormat(DATE_ATOM, $dateTimeFromAtomFormat), $result->dateTimeFromAtomFormat);
self::assertEquals(DateTimeImmutable::createFromFormat($dateTimeFromArray['format'], $dateTimeFromArray['datetime']), $result->dateTimeFromArray);
self::assertEquals(DateTimeImmutable::createFromFormat(DateTimeObjectBuilder::DATE_MYSQL, $mysqlDate), $result->mysqlDate);
self::assertEquals(DateTimeImmutable::createFromFormat(DateTimeObjectBuilder::DATE_PGSQL, $pgsqlDate), $result->pgsqlDate);
self::assertSame($sqlDateNotTime . ' 00:00:00', $result->sqlDateNotTime->format(DateTimeObjectBuilder::DATE_MYSQL));
}
public function test_invalid_datetime_throws_exception(): void
{
try {
(new MapperBuilder())
->mapper()
->map(DateTimeInterface::class, 'invalid datetime');
} catch (MappingError $exception) {
$error = $exception->node()->messages()[0];
self::assertSame('1630686564', $error->code());
self::assertSame("Value 'invalid datetime' does not match a valid date format.", (string)$error);
}
}
public function test_invalid_datetime_from_array_throws_exception(): void
{
try {
(new MapperBuilder())
->mapper()
->map(DateTimeInterface::class, [
'datetime' => 1337,
'format' => 'H',
]);
} catch (MappingError $exception) {
$error = $exception->node()->messages()[0];
self::assertSame('1630686564', $error->code());
self::assertSame("Value 1337 does not match a valid date format.", (string)$error);
}
}
public function test_invalid_array_source_throws_exception(): void
{
try {
(new MapperBuilder())
->mapper()
->map(DateTimeInterface::class, [
'dateTime' => [
'invalid key' => '2012-12-21T13:37:42+00:00',
],
]);
} catch (MappingError $exception) {
$error = $exception->node()->children()['value']->messages()[0];
self::assertSame('1607027306', $error->code());
}
}
private function buildRandomTimestamp(): int
{
return random_int(1, 32503726800);
}
}
final class AllDateTimeValues
{
public DateTimeInterface $dateTimeInterface;
public DateTimeImmutable $dateTimeImmutable;
public DateTime $dateTimeFromTimestamp;
public DateTime $dateTimeFromTimestampWithOutFormat;
public DateTime $dateTimeFromTimestampWithFormat;
public DateTimeInterface $dateTimeFromAtomFormat;
public DateTimeInterface $dateTimeFromArray;
public DateTimeInterface $mysqlDate;
public DateTimeInterface $pgsqlDate;
public DateTimeImmutable $sqlDateNotTime;
}