Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Rector\Tests\DowngradePhp81\Rector\FuncCall\DowngradeHashAlgorithmXxHash\Fixture;

final class SkipCheckVersionCompareOnIf
{
public function run_v()
{
if ( version_compare( PHP_VERSION, '8.1', '>=' ) ) {
return hash( 'xxh128', $value );
}

return hash( 'md4', $value );
}

public function run_v2()
{
if (version_compare( PHP_VERSION, '8.1', '>=' ) ) {
$hash = hash( 'xxh128', $value );
} else {
$hash = hash( 'md4', $value );
}

return $hash;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\NodeVisitor;
use PHPStan\Type\IntegerRangeType;
use Rector\DeadCode\ConditionResolver;
Expand Down Expand Up @@ -80,14 +84,22 @@ public function run()
*/
public function getNodeTypes(): array
{
return [Ternary::class, FuncCall::class];
return [If_::class, Ternary::class, FuncCall::class];
}

/**
* @param Ternary|FuncCall $node
* @param If_|Ternary|FuncCall $node
*/
public function refactor(Node $node): null|int|Node
{
if ($node instanceof If_) {
if ($this->isVersionCompareIf($node)) {
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}

return null;
}

if ($node instanceof Ternary) {
if ($this->isVersionCompareTernary($node)) {
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
Expand Down Expand Up @@ -118,6 +130,36 @@ public function refactor(Node $node): null|int|Node
return $node;
}

private function isVersionCompareIf(If_ $if): bool
{
if ($if->cond instanceof FuncCall) {
// per use case reported only
if (count($if->stmts) !== 1) {
return false;
}

$versionCompare = $this->conditionResolver->resolveFromExpr($if->cond);

if (! $versionCompare instanceof VersionCompareCondition || $versionCompare->getSecondVersion() !== 80100) {
return false;
}

if ($versionCompare->getCompareSign() !== '>=') {
return false;
}

if ($if->stmts[0] instanceof Expression && $if->stmts[0]->expr instanceof Assign && $if->stmts[0]->expr->expr instanceof FuncCall) {
return $this->isName($if->stmts[0]->expr->expr, 'hash');
}

if ($if->stmts[0] instanceof Return_ && $if->stmts[0]->expr instanceof FuncCall) {
return $this->isName($if->stmts[0]->expr, 'hash');
}
}

return false;
}

private function isVersionCompareTernary(Ternary $ternary): bool
{
if ($ternary->if instanceof Expr && $ternary->cond instanceof FuncCall) {
Expand Down