Skip to content

Commit

Permalink
feat: More useful TransformerReturnsUnexpectedValueException except…
Browse files Browse the repository at this point in the history
…ion message.
  • Loading branch information
priyadi committed Jan 14, 2024
1 parent 2d178b2 commit 18ac68a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
);

Expand Down
9 changes: 7 additions & 2 deletions src/MainTransformer/MainTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 18ac68a

Please sign in to comment.