Skip to content

Commit

Permalink
more test + fix
Browse files Browse the repository at this point in the history
  • Loading branch information
vjik committed Oct 25, 2023
1 parent 4662c55 commit 2a19ae0
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/TypeCaster/HydratorTypeCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use ReflectionClass;
use ReflectionNamedType;
use ReflectionUnionType;
use Yiisoft\Hydrator\Exception\NonInstantiableException;
use Yiisoft\Hydrator\HydratorInterface;
use Yiisoft\Hydrator\Result;

Expand Down Expand Up @@ -58,9 +59,12 @@ private function castInternal(array $value, ReflectionNamedType $type, HydratorI

$reflection = new ReflectionClass($class);
if ($reflection->isInstantiable()) {
return Result::success(
$hydrator->create($class, $value)
);
try {
$object = $hydrator->create($class, $value);
} catch (NonInstantiableException) {
return Result::fail();
}
return Result::success($object);
}

return Result::fail();
Expand Down
12 changes: 12 additions & 0 deletions tests/Support/PrivateConstructorObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Hydrator\Tests\Support;

final class PrivateConstructorObject
{
private function __construct()
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ public function dataBase(): array
['string' => 'hello'],
$this->createContext(static fn(StringableObject|(Stringable&Countable) $object) => null),
],
'incompatible array to union type with intersection type' => [
Result::fail(),
['var' => 'hello'],
$this->createContext(static fn(StringableObject|(Stringable&Countable) $object) => null),
],
];
}

Expand Down
6 changes: 6 additions & 0 deletions tests/TypeCaster/HydratorTypeCasterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use ReflectionFunction;
use Yiisoft\Hydrator\Hydrator;
use Yiisoft\Hydrator\Result;
use Yiisoft\Hydrator\Tests\Support\PrivateConstructorObject;
use Yiisoft\Hydrator\Tests\Support\StringableObject;
use Yiisoft\Hydrator\TypeCaster\HydratorTypeCaster;
use Yiisoft\Hydrator\TypeCaster\TypeCastContext;
Expand Down Expand Up @@ -48,6 +49,11 @@ public function dataBase(): array
['string' => 'hello'],
$this->createContext(static fn(int|StringableObject $object) => null),
],
'array to non-instantiable object' => [
Result::fail(),
['string' => 'hello'],
$this->createContext(static fn(PrivateConstructorObject $object) => null),
],
];
}

Expand Down

0 comments on commit 2a19ae0

Please sign in to comment.