From b3cd96075ef5fd5ebe972c0db1c1bd750e000f8f Mon Sep 17 00:00:00 2001 From: Anatoly Nekhay Date: Tue, 17 Sep 2024 04:31:13 +0200 Subject: [PATCH] v3.11 --- src/Hydrator.php | 5 +++-- tests/HydratorTest.php | 30 ++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/Hydrator.php b/src/Hydrator.php index ea01d09..f44914c 100644 --- a/src/Hydrator.php +++ b/src/Hydrator.php @@ -83,8 +83,9 @@ class Hydrator implements HydratorInterface * Constructor of the class * * @param array $context + * @param list $typeConverters */ - public function __construct(array $context = []) + public function __construct(array $context = [], array $typeConverters = []) { $this->context = $context; @@ -92,7 +93,7 @@ public function __construct(array $context = []) new BuiltinAnnotationReader() : new NullAnnotationReader(); - $this->addTypeConverter(...self::defaultTypeConverters()); + $this->addTypeConverter(...self::defaultTypeConverters(), ...$typeConverters); } /** diff --git a/tests/HydratorTest.php b/tests/HydratorTest.php index dbf4e5b..68666e9 100644 --- a/tests/HydratorTest.php +++ b/tests/HydratorTest.php @@ -27,6 +27,7 @@ use Sunrise\Hydrator\HydratorInterface; use Sunrise\Hydrator\Type; use Sunrise\Hydrator\TypeConverter\TimestampTypeConverter; +use Sunrise\Hydrator\TypeConverterInterface; use function date; use function get_class; @@ -86,6 +87,31 @@ public function testStdClassWithAssociationProperty(): void $this->assertSame('foo', $object->value->value); } + public function testCreateHydratorWithTypeConverters(): void + { + $object = new class { + public \Closure $foo; + }; + + $typeConverter = $this->createMock(TypeConverterInterface::class); + + $typeConverter->method('castValue')->willReturnCallback( + static function ($value, Type $type, array $path, array $context): Generator { + if ($type->getName() === \Closure::class) { + yield static function () use ($value) { + return $value; + }; + } + } + ); + + $this->createHydrator([], [$typeConverter])->hydrate($object, [ + 'foo' => 'bar', + ]); + + $this->assertSame('bar', ($object->foo)()); + } + /** * @group boolean * @dataProvider strictBooleanDataProvider @@ -3068,9 +3094,9 @@ public function uuidDataProvider(): Generator yield [['value' => '207ddb61-c300-4368-9f26-33d0a99eac00'], '207ddb61-c300-4368-9f26-33d0a99eac00']; } - private function createHydrator(array $context = []): HydratorInterface + private function createHydrator(array $context = [], array $typeConverters = []): HydratorInterface { - $hydrator = new Hydrator($context); + $hydrator = new Hydrator($context, $typeConverters); if (PHP_VERSION_ID < 80000) { $hydrator->useDefaultAnnotationReader(); }