Skip to content

Commit

Permalink
If load a DB item with value which not exists in Enum, throw a readab…
Browse files Browse the repository at this point in the history
…le error message windwalker-io/core#1115
  • Loading branch information
asika32764 committed Dec 15, 2024
1 parent fcea012 commit 5e3583d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Cast/CastManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,15 @@ public function castToCallback(mixed $cast, int $options, string $direction = 'h
if (class_exists($cast)) {
// Cast interface
if (is_subclass_of($cast, CastInterface::class)) {
return static function (mixed $value, ORM $orm) use ($options, $direction, $cast) {
return static function (mixed $value, ORM $orm) use ($cast, $options, $direction) {
return $orm->getAttributesResolver()
->createObject($cast)
->$direction($value);
};
}

// Pure class
return static function (mixed $value, ORM $orm) use ($options, $cast) {
return static function (mixed $value, ORM $orm) use ($cast, $options) {
if (is_subclass_of($cast, \BackedEnum::class)) {
return $cast::wrap($value);
}
Expand Down
26 changes: 26 additions & 0 deletions src/Hydrator/EntityHydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ public static function castFieldForHydrate(
try {
$value = $hydrator($value, $metadata->getORM(), $entity);
} catch (Throwable $e) {
if ($hydrator instanceof \Closure) {
$hydrator = static::extractCastNameFromClosure($hydrator);
}

$castName = is_object($hydrator) ? $hydrator::class : json_encode($hydrator);

throw new CastingException(
Expand Down Expand Up @@ -260,4 +264,26 @@ public static function castArray(EntityMetadata $metadata, array $data, ?object

return $data;
}

/**
* @param \Closure $hydrator
*
* @return mixed
*
* @throws \ReflectionException
*/
protected static function extractCastNameFromClosure(\Closure $hydrator): mixed
{
$ref = new \ReflectionFunction($hydrator);

if ($caster = $ref->getClosureUsedVariables()['caster'] ?? null) {
$ref = new \ReflectionFunction($caster);

if ($cast = $ref->getClosureUsedVariables()['cast'] ?? null) {
$hydrator = $cast;
}
}

return $hydrator;
}
}

0 comments on commit 5e3583d

Please sign in to comment.