From 18ac68a2a4005c7a16b2dff9fe4e926b7c03dc9f Mon Sep 17 00:00:00 2001 From: Priyadi Iman Nurcahyo <1102197+priyadi@users.noreply.github.com> Date: Sun, 14 Jan 2024 14:42:39 +0700 Subject: [PATCH] feat: More useful `TransformerReturnsUnexpectedValueException` exception message. --- CHANGELOG.md | 1 + ...ransformerReturnsUnexpectedValueException.php | 16 ++++++++++++---- src/MainTransformer/MainTransformer.php | 9 +++++++-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbd3967f..0a70d016 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * feat: Context methods now accept `$context` variable, and pass it to exceptions. * feat: Main transformer's exception now accepts `$context` variable. +* feat: More useful `TransformerReturnsUnexpectedValueException` exception message. ## 0.5.8 diff --git a/src/MainTransformer/Exception/TransformerReturnsUnexpectedValueException.php b/src/MainTransformer/Exception/TransformerReturnsUnexpectedValueException.php index fe6840c7..dc1385ee 100644 --- a/src/MainTransformer/Exception/TransformerReturnsUnexpectedValueException.php +++ b/src/MainTransformer/Exception/TransformerReturnsUnexpectedValueException.php @@ -16,16 +16,24 @@ use Rekalogika\Mapper\Context\Context; use Rekalogika\Mapper\Exception\UnexpectedValueException; use Rekalogika\Mapper\Transformer\Contracts\MixedType; +use Rekalogika\Mapper\Transformer\Contracts\TransformerInterface; use Rekalogika\Mapper\Util\TypeUtil; use Symfony\Component\PropertyInfo\Type; class TransformerReturnsUnexpectedValueException extends UnexpectedValueException { - public function __construct(Type|MixedType $type, mixed $target, Context $context) - { + public function __construct( + mixed $source, + Type|MixedType $targetType, + mixed $target, + TransformerInterface $transformer, + Context $context + ) { $message = sprintf( - 'Mapper returns unexpected value. Expected type "%s", but got "%s".', - TypeUtil::getTypeString($type), + 'Trying to map source type "%s" to target type "%s", but the assigned transformer "%s" returns an unexpected type "%s".', + \get_debug_type($source), + TypeUtil::getTypeString($targetType), + \get_class($transformer), get_debug_type($target), ); diff --git a/src/MainTransformer/MainTransformer.php b/src/MainTransformer/MainTransformer.php index 1673be5d..4d46096d 100644 --- a/src/MainTransformer/MainTransformer.php +++ b/src/MainTransformer/MainTransformer.php @@ -172,8 +172,13 @@ public function transform( context: $context ); - if (!TypeCheck::isVariableInstanceOf($result, $targetType)) { - throw new TransformerReturnsUnexpectedValueException($targetType, $result, context: $context); + // check the result type + + if ( + !TypeCheck::isVariableInstanceOf($result, $targetType) + && $result !== null + ) { + throw new TransformerReturnsUnexpectedValueException($source, $targetType, $result, $transformer, $context); } // if the target type is not null, cache it