Skip to content

Commit 49c115c

Browse files
committed
isobject
1 parent 719435b commit 49c115c

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Rector\Tests\DowngradePhp80\Rector\Instanceof_\DowngradeInstanceofStringableRector\Fixture;
4+
5+
class ExactlyObjectType
6+
{
7+
public function run(object $obj)
8+
{
9+
return $obj instanceof \Stringable;
10+
}
11+
}
12+
13+
?>
14+
-----
15+
<?php
16+
17+
namespace Rector\Tests\DowngradePhp80\Rector\Instanceof_\DowngradeInstanceofStringableRector\Fixture;
18+
19+
class ExactlyObjectType
20+
{
21+
public function run(object $obj)
22+
{
23+
return method_exists($obj, '__toString');
24+
}
25+
}
26+
27+
?>

rules/DowngradePhp80/Rector/Instanceof_/DowngradeInstanceofStringableRector.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PhpParser\Node;
88
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
9+
use PhpParser\Node\Expr\FuncCall;
910
use PhpParser\Node\Expr\Instanceof_;
1011
use PhpParser\Node\Name\FullyQualified;
1112
use PhpParser\Node\Scalar\String_;
@@ -46,7 +47,7 @@ public function getNodeTypes(): array
4647
/**
4748
* @param Instanceof_ $node
4849
*/
49-
public function refactor(Node $node): ?BooleanAnd
50+
public function refactor(Node $node): null|FuncCall|BooleanAnd
5051
{
5152
if (! $node->class instanceof FullyQualified) {
5253
return null;
@@ -56,9 +57,13 @@ public function refactor(Node $node): ?BooleanAnd
5657
return null;
5758
}
5859

59-
return new BooleanAnd(
60-
$this->nodeFactory->createFuncCall('is_object', [$node->expr]),
61-
$this->nodeFactory->createFuncCall('method_exists', [$node->expr, new String_('__toString')])
62-
);
60+
$nativeExprType = $this->nodeTypeResolver->getNativeType($node->expr);
61+
$funcCall = $this->nodeFactory->createFuncCall('method_exists', [$node->expr, new String_('__toString')]);
62+
63+
if ($nativeExprType->isObject()->yes()) {
64+
return $funcCall;
65+
}
66+
67+
return new BooleanAnd($this->nodeFactory->createFuncCall('is_object', [$node->expr]), $funcCall);
6368
}
6469
}

0 commit comments

Comments
 (0)