Skip to content

Commit

Permalink
Fix StrContainsRector when strpos offset is set (#3086)
Browse files Browse the repository at this point in the history
Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>
  • Loading branch information
ajgarlag and samsonasik committed Nov 22, 2022
1 parent eddc376 commit 30afbb8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Rector\Tests\Php80\Rector\NotIdentical\StrContainsRector\Fixture;

class OffsetStrpos
{
public function run()
{
return strpos('abc', 'a', 1) !== false;
}
}
?>
-----
<?php

namespace Rector\Tests\Php80\Rector\NotIdentical\StrContainsRector\Fixture;

class OffsetStrpos
{
public function run()
{
return str_contains(substr('abc', 1), 'a');
}
}
?>
19 changes: 19 additions & 0 deletions rules/Php80/Rector/NotIdentical/StrContainsRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
namespace Rector\Php80\Rector\NotIdentical;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\LNumber;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
Expand Down Expand Up @@ -82,6 +85,13 @@ public function refactor(Node $node): ?Node
return null;
}

if (isset($funcCall->args[2])) {
if ($this->isName($funcCall->name, 'strpos') && $this->isPositiveInteger($funcCall->args[2]->value)) {
$funcCall->args[0] = new Arg($this->nodeFactory->createFuncCall('substr', [$funcCall->args[0], $funcCall->args[2]]));
}
unset($funcCall->args[2]);
}

$funcCall->name = new Name('str_contains');

if ($node instanceof Identical) {
Expand Down Expand Up @@ -123,4 +133,13 @@ private function matchIdenticalOrNotIdenticalToFalse(Identical | NotIdentical $e

return null;
}

private function isPositiveInteger(Expr $offset): bool
{
if (! $offset instanceof LNumber) {
return false;
}

return $offset->value > 0;
}
}

0 comments on commit 30afbb8

Please sign in to comment.