mirror of
https://github.com/danog/Valinor.git
synced 2024-12-04 10:38:27 +01:00
6d427088f7
The method `MapperBuilder::bind()` can be used to define a custom way to build an object during the mapping. The return type of the callback will be resolved by the mapping to know when to use it. The callback can take any arguments, that will automatically be mapped using the given source. These arguments can then be used to instantiate the object in the desired way. Example: ```php (new \CuyZ\Valinor\MapperBuilder()) ->bind(function(string $string, OtherClass $otherClass): SomeClass { $someClass = new SomeClass($string); $someClass->addOtherClass($otherClass); return $someClass; }) ->mapper() ->map(SomeClass::class, [ // … ]); ```
47 lines
1.4 KiB
PHP
47 lines
1.4 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 (): stdClass => new stdClass());
|
|
$builderD = $builderA->alter(static fn (string $value): string => 'foo');
|
|
$builderE = $builderA->withCacheDir(sys_get_temp_dir());
|
|
$builderF = $builderA->enableLegacyDoctrineAnnotations();
|
|
|
|
self::assertNotSame($builderA, $builderB);
|
|
self::assertNotSame($builderA, $builderC);
|
|
self::assertNotSame($builderA, $builderD);
|
|
self::assertNotSame($builderA, $builderE);
|
|
self::assertNotSame($builderA, $builderF);
|
|
}
|
|
|
|
public function test_mapper_instance_is_the_same(): void
|
|
{
|
|
self::assertSame($this->mapperBuilder->mapper(), $this->mapperBuilder->mapper());
|
|
}
|
|
}
|