|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\DowngradePhp82\Rector\ArrowFunction; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\ArrowFunction; |
| 9 | +use PHPStan\Type\NeverType; |
| 10 | +use Rector\PhpDocDecorator\PhpDocFromTypeDeclarationDecorator; |
| 11 | +use Rector\Rector\AbstractRector; |
| 12 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 13 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 14 | + |
| 15 | +/** |
| 16 | + * PHP 8.1 accepts the "never" return type everywhere except on arrow functions, where the implicit |
| 17 | + * return of the body expression trips "A never-returning function must not return" at compile time. |
| 18 | + * PHP 8.2 fixed that, so only the arrow-function case has to go when targeting 8.1; other |
| 19 | + * function-likes keep "never" until the 8.1 set removes it. |
| 20 | + * |
| 21 | + * @changelog https://github.com/php/php-src/issues/7900 |
| 22 | + * |
| 23 | + * @see \Rector\Tests\DowngradePhp82\Rector\ArrowFunction\DowngradeArrowFunctionNeverReturnTypeRector\DowngradeArrowFunctionNeverReturnTypeRectorTest |
| 24 | + */ |
| 25 | +final class DowngradeArrowFunctionNeverReturnTypeRector extends AbstractRector |
| 26 | +{ |
| 27 | + public function __construct( |
| 28 | + private readonly PhpDocFromTypeDeclarationDecorator $phpDocFromTypeDeclarationDecorator |
| 29 | + ) { |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @return array<class-string<Node>> |
| 34 | + */ |
| 35 | + public function getNodeTypes(): array |
| 36 | + { |
| 37 | + return [ArrowFunction::class]; |
| 38 | + } |
| 39 | + |
| 40 | + public function getRuleDefinition(): RuleDefinition |
| 41 | + { |
| 42 | + return new RuleDefinition( |
| 43 | + 'Remove "never" return type from arrow functions, which PHP 8.1 rejects at compile time', |
| 44 | + [ |
| 45 | + new CodeSample( |
| 46 | + <<<'CODE_SAMPLE' |
| 47 | +$callable = fn (): never => throw new \RuntimeException(); |
| 48 | +CODE_SAMPLE |
| 49 | + , |
| 50 | + <<<'CODE_SAMPLE' |
| 51 | +$callable = fn () => throw new \RuntimeException(); |
| 52 | +CODE_SAMPLE |
| 53 | + ), |
| 54 | + ] |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * @param ArrowFunction $node |
| 60 | + */ |
| 61 | + public function refactor(Node $node): ?Node |
| 62 | + { |
| 63 | + if (! $this->phpDocFromTypeDeclarationDecorator->decorateReturnWithSpecificType($node, new NeverType())) { |
| 64 | + return null; |
| 65 | + } |
| 66 | + |
| 67 | + return $node; |
| 68 | + } |
| 69 | +} |
0 commit comments