Skip to content

Commit

Permalink
Merge pull request #38 from sunrise-php/release/v3.11.0
Browse files Browse the repository at this point in the history
v3.11.0
  • Loading branch information
fenric authored Sep 17, 2024
2 parents f122aab + b3cd960 commit df8d6f7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/Hydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,16 +83,17 @@ class Hydrator implements HydratorInterface
* Constructor of the class
*
* @param array<string, mixed> $context
* @param list<TypeConverterInterface> $typeConverters
*/
public function __construct(array $context = [])
public function __construct(array $context = [], array $typeConverters = [])
{
$this->context = $context;

$this->annotationReader = PHP_MAJOR_VERSION >= 8 ?
new BuiltinAnnotationReader() :
new NullAnnotationReader();

$this->addTypeConverter(...self::defaultTypeConverters());
$this->addTypeConverter(...self::defaultTypeConverters(), ...$typeConverters);
}

/**
Expand Down
30 changes: 28 additions & 2 deletions tests/HydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
}
Expand Down

0 comments on commit df8d6f7

Please sign in to comment.