Valinor/tests/Unit/MapperBuilderTest.php
Romain Canon ecafba3b21 feat!: introduce method to register constructors used during mapping
It is now mandatory to explicitly register custom constructors —
including named constructors — that can be used by the mapper. The
former automatic registration of named constructor feature doesn't
work anymore.

BREAKING CHANGE: existing code must list all named constructors that
were previously automatically used by the mapper, and registerer them
using the method `MapperBuilder::registerConstructor()`.

The method `MapperBuilder::bind()` has been deprecated, the method above
should be used instead.

```php
final class SomeClass
{
    public static function namedConstructor(string $foo): self
    {
        // …
    }
}

(new \CuyZ\Valinor\MapperBuilder())
    ->registerConstructor(
        SomeClass::namedConstructor(...),
        // …or for PHP < 8.1:
        [SomeClass::class, 'namedConstructor'],
    )
    ->mapper()
    ->map(SomeClass::class, [
        // …
    ]);
```
2022-03-24 13:03:55 +01:00

49 lines
1.5 KiB
PHP

<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Tests\Unit;
use CuyZ\Valinor\MapperBuilder;
use DateTime;
use DateTimeInterface;
use PHPUnit\Framework\TestCase;
use stdClass;
use function sys_get_temp_dir;
final class MapperBuilderTest extends TestCase
{
private MapperBuilder $mapperBuilder;
protected function setUp(): void
{
parent::setUp();
$this->mapperBuilder = new MapperBuilder();
}
public function test_builder_methods_return_clone_of_builder_instance(): void
{
$builderA = $this->mapperBuilder;
$builderB = $builderA->infer(DateTimeInterface::class, static fn () => DateTime::class);
$builderC = $builderA->bind(static fn (): DateTime => new DateTime());
$builderD = $builderA->registerConstructor(static fn (): stdClass => new stdClass());
$builderE = $builderA->alter(static fn (string $value): string => 'foo');
$builderF = $builderA->withCacheDir(sys_get_temp_dir());
$builderG = $builderA->enableLegacyDoctrineAnnotations();
self::assertNotSame($builderA, $builderB);
self::assertNotSame($builderA, $builderC);
self::assertNotSame($builderA, $builderD);
self::assertNotSame($builderA, $builderE);
self::assertNotSame($builderA, $builderF);
self::assertNotSame($builderA, $builderG);
}
public function test_mapper_instance_is_the_same(): void
{
self::assertSame($this->mapperBuilder->mapper(), $this->mapperBuilder->mapper()); // @phpstan-ignore-line
}
}