|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\NodeTypeResolver\PHPStan\Scope\NodeVisitor; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\FuncCall; |
| 9 | +use PhpParser\Node\Expr\Ternary; |
| 10 | +use PhpParser\Node\Stmt\If_; |
| 11 | +use PhpParser\NodeVisitorAbstract; |
| 12 | +use Rector\Contract\PhpParser\DecoratingNodeVisitorInterface; |
| 13 | +use Rector\DeadCode\ConditionResolver; |
| 14 | +use Rector\DeadCode\ValueObject\VersionCompareCondition; |
| 15 | +use Rector\NodeTypeResolver\Node\AttributeKey; |
| 16 | +use Rector\PhpParser\NodeTraverser\SimpleNodeTraverser; |
| 17 | + |
| 18 | +final class PhpVersionConditionNodeVisitor extends NodeVisitorAbstract implements DecoratingNodeVisitorInterface |
| 19 | +{ |
| 20 | + public function __construct( |
| 21 | + private readonly ConditionResolver $conditionResolver |
| 22 | + ) { |
| 23 | + } |
| 24 | + |
| 25 | + public function enterNode(Node $node): ?Node |
| 26 | + { |
| 27 | + if (($node instanceof Ternary || $node instanceof If_) && $this->hasVersionCompareCond($node)) { |
| 28 | + if ($node instanceof Ternary) { |
| 29 | + $nodes = [$node->else]; |
| 30 | + if ($node->if instanceof \PhpParser\Node) { |
| 31 | + $nodes[] = $node->if; |
| 32 | + } |
| 33 | + } else { |
| 34 | + $nodes = $node->stmts; |
| 35 | + } |
| 36 | + |
| 37 | + SimpleNodeTraverser::decorateWithAttributeValue($nodes, AttributeKey::PHP_VERSION_CONDITIONED, true); |
| 38 | + } |
| 39 | + |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + private function hasVersionCompareCond(If_|Ternary $ifOrTernary): bool |
| 44 | + { |
| 45 | + if (! $ifOrTernary->cond instanceof FuncCall) { |
| 46 | + return false; |
| 47 | + } |
| 48 | + |
| 49 | + $versionCompare = $this->conditionResolver->resolveFromExpr($ifOrTernary->cond); |
| 50 | + return $versionCompare instanceof VersionCompareCondition; |
| 51 | + } |
| 52 | +} |
0 commit comments