diff --git a/src/Exceptions/MappingFail.php b/src/Exceptions/MappingFail.php index 2c58885..6e35b30 100644 --- a/src/Exceptions/MappingFail.php +++ b/src/Exceptions/MappingFail.php @@ -8,15 +8,18 @@ class MappingFail extends DTOException { public function __construct( public readonly Mapper $mapper, - public readonly UnexpectedValue|InternalException|null $exception = null + public readonly UnexpectedValue|InternalException|string|null $exception = null ) { parent::__construct( sprintf( '[%s]%s', $mapper::class, - $exception ? " {$exception->getMessage()}" : '' + is_string($exception) + ? $this->exception + : ($exception ? " {$exception->getMessage()}" : '') + ), - previous: $exception + previous: ! is_string($exception) ? $exception : null ); } } diff --git a/src/Support/Mapping/Casts/KeyedArrayCast.php b/src/Support/Mapping/Casts/KeyedArrayCast.php index c568f7b..26d8747 100644 --- a/src/Support/Mapping/Casts/KeyedArrayCast.php +++ b/src/Support/Mapping/Casts/KeyedArrayCast.php @@ -29,7 +29,7 @@ class KeyedArrayCast extends OptionalCast */ protected array|OneOfConstCast|EnumCast|StringCast|null $keyBy = null; - protected bool $nullIfEmpty = false; + protected bool $optionalIfEmpty = false; protected bool $stdClassCastAllowed = false; @@ -75,13 +75,22 @@ public function keySchema(OneOfConstCast|EnumCast|StringCast $cast): static public function nullIfEmpty(): static { - $this->nullIfEmpty = true; + $this->optionalIfEmpty = true; $this->nullable(); return $this; } + public function optionalIfEmpty(): static + { + $this->optionalIfEmpty = true; + + $this->optional(); + + return $this; + } + protected function finalize(mixed $source, array $sourcesTrace): ?stdClass { $value = static::resolveValueFromAccessor( @@ -145,7 +154,7 @@ protected function finalize(mixed $source, array $sourcesTrace): ?stdClass } } - return ! $hasValues && $this->nullIfEmpty ? null : $result; + return ! $hasValues && $this->optionalIfEmpty ? null : $result; } protected function types(): RecordType