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,27 @@
<?php

namespace Rector\Tests\DowngradePhp80\Rector\Instanceof_\DowngradeInstanceofStringableRector\Fixture;

class ExactlyObjectType
{
public function run(object $obj)
{
return $obj instanceof \Stringable;
}
}

?>
-----
<?php

namespace Rector\Tests\DowngradePhp80\Rector\Instanceof_\DowngradeInstanceofStringableRector\Fixture;

class ExactlyObjectType
{
public function run(object $obj)
{
return method_exists($obj, '__toString');
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class Fixture
{
public function run($obj)
{
return method_exists($obj, '__toString');
return is_object($obj) && method_exists($obj, '__toString');
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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_;
Expand All @@ -28,7 +30,7 @@ public function getRuleDefinition(): RuleDefinition

,
<<<'CODE_SAMPLE'
method_exists($obj, '__toString');
is_object($obj) && method_exists($obj, '__toString');
CODE_SAMPLE
),
]);
Expand All @@ -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;
Expand All @@ -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);
}
}
Loading