diff --git a/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/exactly_object_type.php.inc b/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/exactly_object_type.php.inc new file mode 100644 index 00000000..807867c2 --- /dev/null +++ b/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/exactly_object_type.php.inc @@ -0,0 +1,27 @@ + +----- + diff --git a/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/fixture.php.inc b/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/fixture.php.inc index 4423ba92..db2fbfd7 100644 --- a/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/fixture.php.inc +++ b/rules-tests/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector/Fixture/fixture.php.inc @@ -20,7 +20,7 @@ class Fixture { public function run($obj) { - return method_exists($obj, '__toString'); + return is_object($obj) && method_exists($obj, '__toString'); } } diff --git a/rules/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector.php b/rules/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector.php index 6627645e..5cfd892f 100644 --- a/rules/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector.php +++ b/rules/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector.php @@ -5,6 +5,8 @@ namespace Rector\DowngradePhp80\Rector\Instanceof_; use PhpParser\Node; +use PhpParser\Node\Expr\BinaryOp\BooleanAnd; +use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\Instanceof_; use PhpParser\Node\Name\FullyQualified; use PhpParser\Node\Scalar\String_; @@ -28,7 +30,7 @@ public function getRuleDefinition(): RuleDefinition , <<<'CODE_SAMPLE' -method_exists($obj, '__toString'); +is_object($obj) && method_exists($obj, '__toString'); CODE_SAMPLE ), ]); @@ -45,7 +47,7 @@ public function getNodeTypes(): array /** * @param Instanceof_ $node */ - public function refactor(Node $node): ?Node + public function refactor(Node $node): null|FuncCall|BooleanAnd { if (! $node->class instanceof FullyQualified) { return null; @@ -55,6 +57,13 @@ public function refactor(Node $node): ?Node return null; } - return $this->nodeFactory->createFuncCall('method_exists', [$node->expr, new String_('__toString')]); + $nativeExprType = $this->nodeTypeResolver->getNativeType($node->expr); + $funcCall = $this->nodeFactory->createFuncCall('method_exists', [$node->expr, new String_('__toString')]); + + if ($nativeExprType->isObject()->yes()) { + return $funcCall; + } + + return new BooleanAnd($this->nodeFactory->createFuncCall('is_object', [$node->expr]), $funcCall); } }