Skip to content

Commit

Permalink
fix: display useful error message for invalid constructor return type
Browse files Browse the repository at this point in the history
  • Loading branch information
romm committed Feb 12, 2023
1 parent 3177bf7 commit dc7f5c3
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/Mapper/Object/Exception/InvalidConstructorReturnType.php
Expand Up @@ -5,16 +5,20 @@
namespace CuyZ\Valinor\Mapper\Object\Exception;

use CuyZ\Valinor\Definition\FunctionDefinition;
use CuyZ\Valinor\Type\Types\UnresolvableType;
use LogicException;

/** @internal */
final class InvalidConstructorReturnType extends LogicException
{
public function __construct(FunctionDefinition $function)
{
parent::__construct(
"Invalid return type `{$function->returnType()->toString()}` for constructor `{$function->signature()}`, it must be a valid class name.",
1659446121
);
$returnType = $function->returnType();

$message = $returnType instanceof UnresolvableType
? $returnType->getMessage()
: "Invalid return type `{$returnType->toString()}` for constructor `{$function->signature()}`, it must be a valid class name.";

parent::__construct($message, 1659446121);
}
}
15 changes: 15 additions & 0 deletions tests/Integration/Mapping/ConstructorRegistrationMappingTest.php
Expand Up @@ -16,6 +16,7 @@
use CuyZ\Valinor\Tests\Fake\Mapper\Tree\Message\FakeErrorMessage;
use CuyZ\Valinor\Tests\Integration\IntegrationTest;
use CuyZ\Valinor\Tests\Integration\Mapping\Fixture\SimpleObject;
use CuyZ\Valinor\Tests\Integration\Mapping\Fixture\SimpleObjectWithGeneric;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
Expand Down Expand Up @@ -568,6 +569,20 @@ public function test_invalid_constructor_return_type_throws_exception(): void
->map(stdClass::class, []);
}

public function test_invalid_constructor_return_type_missing_generic_throws_exception(): void
{
$this->expectException(InvalidConstructorReturnType::class);
$this->expectExceptionCode(1659446121);
$this->expectExceptionMessageMatches('/The type `.*` for return type of method `.*` could not be resolved: No generic was assigned to the template\(s\) `T` for the class .*/');

(new MapperBuilder())
->registerConstructor(
fn (): SimpleObjectWithGeneric => new SimpleObjectWithGeneric()
)
->mapper()
->map(stdClass::class, []);
}

public function test_missing_constructor_class_type_parameter_throws_exception(): void
{
$this->expectException(MissingConstructorClassTypeParameter::class);
Expand Down
14 changes: 14 additions & 0 deletions tests/Integration/Mapping/Fixture/SimpleObjectWithGeneric.php
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace CuyZ\Valinor\Tests\Integration\Mapping\Fixture;

/**
* @template T
*/
final class SimpleObjectWithGeneric
{
/** @var T */
public $value;
}

0 comments on commit dc7f5c3

Please sign in to comment.