Skip to content

Commit 8e110fd

Browse files
committed
Fix rendering of return types that are unions
1 parent d071e71 commit 8e110fd

File tree

4 files changed

+30
-2
lines changed

4 files changed

+30
-2
lines changed

src/Renderer/Php7Renderer.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -628,12 +628,14 @@ public function renderFunctionSignature(PhpFunction $function): array
628628
$ret[] = ')';
629629
}
630630

631-
if ($function->getReturnType()->getTypeHint()) {
631+
$returnTypeHint = $this->renderFunctionReturnType($function);
632+
633+
if ($returnTypeHint) {
632634
$lastKey = (int)array_key_last($ret);
633635
if (!is_string($ret[$lastKey])) {
634636
throw InvalidCode::invalidType();
635637
}
636-
$ret[$lastKey] .= ': ' . $function->getReturnType()->getTypeHint();
638+
$ret[$lastKey] .= ': ' . $returnTypeHint;
637639
}
638640

639641
$lastKey = (int)array_key_last($ret);
@@ -789,4 +791,9 @@ public function renderAttribute(PhpAttribute $attr): array
789791
// not-supported
790792
return [];
791793
}
794+
795+
protected function renderFunctionReturnType(PhpFunction $function): string
796+
{
797+
return $function->getReturnType()->getTypeHint() ?? '';
798+
}
792799
}

src/Renderer/Php8Renderer.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,11 @@ public function renderMethod(PhpMethod $method): array
223223
return $ret;
224224
}
225225

226+
protected function renderFunctionReturnType(PhpFunction $function): string
227+
{
228+
return $function->getReturnType()->getTypeHint(true) ?? '';
229+
}
230+
226231
public function renderComment(?PhpDocComment $comment): array
227232
{
228233
if (!$comment) {

tests/Renderer/PhpMethodTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,4 +401,14 @@ public function testVariadicParamInCtorAndPropertyPromotion(): void
401401
$renderer = new Php8Renderer();
402402
$this->assertSourceResult($renderer->renderClass($c), 'PhpMethodTest.testVariadicParamInCtorAndPropertyPromotion');
403403
}
404+
405+
public function testRenderUnionResponseTypeForPhp8(): void
406+
{
407+
$type = Type::empty();
408+
$type->addUnion(\DateTimeImmutable::class);
409+
$type->addUnion(\PDO::class);
410+
$method = PhpMethod::public('test', [], [], $type);
411+
$renderer = new Php8Renderer();
412+
$this->assertSourceResult($renderer->renderMethod($method), 'PhpMethodTest.testRenderUnionResponseTypeForPhp8');
413+
}
404414
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/**
2+
* @return DateTimeImmutable|PDO
3+
*/
4+
public function test(): DateTimeImmutable|PDO
5+
{
6+
}

0 commit comments

Comments
 (0)