|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\DowngradePhp85\Rector\Expression; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\Assign; |
| 9 | +use PhpParser\Node\Expr\Cast\Void_; |
| 10 | +use PhpParser\Node\Expr\Variable; |
| 11 | +use PhpParser\Node\Stmt\Expression; |
| 12 | +use Rector\Naming\Naming\VariableNaming; |
| 13 | +use Rector\PHPStan\ScopeFetcher; |
| 14 | +use Rector\Rector\AbstractRector; |
| 15 | +use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; |
| 16 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 17 | + |
| 18 | +/** |
| 19 | + * @see https://wiki.php.net/rfc/marking_return_value_as_important |
| 20 | + * @see \Rector\Tests\DowngradePhp85\Rector\Expression\DowngradeVoidCastRector\DowngradeVoidCastRectorTest |
| 21 | + */ |
| 22 | +final class DowngradeVoidCastRector extends AbstractRector |
| 23 | +{ |
| 24 | + public function __construct( |
| 25 | + private readonly VariableNaming $variableNaming |
| 26 | + ) { |
| 27 | + } |
| 28 | + |
| 29 | + public function getNodeTypes(): array |
| 30 | + { |
| 31 | + return [Expression::class]; |
| 32 | + } |
| 33 | + |
| 34 | + public function getRuleDefinition(): RuleDefinition |
| 35 | + { |
| 36 | + return new RuleDefinition( |
| 37 | + 'Replace void casts with proper handling of return values', |
| 38 | + [ |
| 39 | + new CodeSample( |
| 40 | + <<<'CODE_SAMPLE' |
| 41 | +#[\NoDiscard] |
| 42 | +function getPhpVersion(): string |
| 43 | +{ |
| 44 | + return 'PHP 8.5'; |
| 45 | +} |
| 46 | +
|
| 47 | +(void) getPhpVersion(); |
| 48 | +CODE_SAMPLE |
| 49 | + , |
| 50 | + <<<'CODE_SAMPLE' |
| 51 | +#[\NoDiscard] |
| 52 | +function getPhpVersion(): string |
| 53 | +{ |
| 54 | + return 'PHP 8.5'; |
| 55 | +} |
| 56 | +
|
| 57 | +$_void = getPhpVersion(); |
| 58 | +CODE_SAMPLE |
| 59 | + ), |
| 60 | + ] |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @param Expression $node |
| 66 | + */ |
| 67 | + public function refactor(Node $node): ?Node |
| 68 | + { |
| 69 | + if (! $node->expr instanceof Void_) { |
| 70 | + return null; |
| 71 | + } |
| 72 | + |
| 73 | + $scope = ScopeFetcher::fetch($node); |
| 74 | + $variable = new Variable($this->variableNaming->createCountedValueName('_void', $scope)); |
| 75 | + |
| 76 | + // the assign is needed to avoid warning |
| 77 | + // see https://3v4l.org/ie68D#v8.5.3 vs https://3v4l.org/nLc5J#v8.5.3 |
| 78 | + $node->expr = new Assign( |
| 79 | + $variable, |
| 80 | + $node->expr->expr |
| 81 | + ); |
| 82 | + return $node; |
| 83 | + } |
| 84 | +} |
0 commit comments