Skip to content

Commit

Permalink
[TypeDeclaration] AddVoidReturnTypeWhereNoReturnRector turns `@return…
Browse files Browse the repository at this point in the history
… never` into less specific `@return void` (#1553)

* added failling test

* fix

* added more bottom-type tests

* made rector aware of all phpstan supported bottom types

* cs

Co-authored-by: Markus Staab <m.staab@complex-it.de>
  • Loading branch information
staabm and clxmstaab committed Dec 23, 2021
1 parent f05b84f commit 39580db
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ final class ScalarStringToTypeMapper
ResourceType::class => ['resource'],
CallableType::class => ['callback', 'callable'],
ObjectWithoutClassType::class => ['object'],
NeverType::class => ['never'],
NeverType::class => ['never', 'never-return', 'never-returns', 'no-return'],
];

public function mapScalarStringToType(string $scalarName): Type
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector\Fixture;

final class SomeClass
{
/**
* @return never
*/
public function neverReturn()
{
header('Location: example.com');
exit();
}

/**
* @return never-return
*/
public function neverReturn()
{
header('Location: example.com');
exit();
}

/**
* @return never-returns
*/
public function neverReturns()
{
header('Location: example.com');
exit();
}

/**
* @return no-return
*/
public function noReturn()
{
header('Location: example.com');
exit();
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use PHPStan\Type\VoidType;
use PHPStan\Type\NeverType;
use Rector\BetterPhpDocParser\PhpDocManipulator\PhpDocTypeChanger;
use Rector\Core\Contract\Rector\AllowEmptyConfigurableRectorInterface;
use Rector\Core\Rector\AbstractRector;
Expand Down Expand Up @@ -100,8 +101,7 @@ public function refactor(Node $node): ?Node
}

if ($this->usePhpdoc) {
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);
$this->phpDocTypeChanger->changeReturnType($phpDocInfo, new VoidType());
$this->changePhpDocToVoidIfNotNever($node);

return $node;
}
Expand Down Expand Up @@ -129,4 +129,15 @@ public function configure(array $configuration): void

$this->usePhpdoc = $usePhpdoc;
}

private function changePhpDocToVoidIfNotNever(ClassMethod|Function_|Closure|Node $node): void
{
$phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($node);

if ($phpDocInfo->getReturnType() instanceof NeverType) {
return;
}

$this->phpDocTypeChanger->changeReturnType($phpDocInfo, new VoidType());
}
}

0 comments on commit 39580db

Please sign in to comment.