rector/rules/Defluent/NodeAnalyzer/NewFluentChainMethodCallNodeAnalyzer.php
Tomas Votruba 73d7212e05 Updated Rector to commit 17cfa9f376
17cfa9f376 Update to nikic/php-parser 4.13.0 (#904)
2021-09-27 15:43:15 +00:00

59 lines
1.9 KiB
PHP

<?php
declare (strict_types=1);
namespace Rector\Defluent\NodeAnalyzer;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
use PHPStan\Type\MixedType;
use Rector\NodeTypeResolver\NodeTypeResolver;
final class NewFluentChainMethodCallNodeAnalyzer
{
/**
* @var \Rector\NodeTypeResolver\NodeTypeResolver
*/
private $nodeTypeResolver;
public function __construct(\Rector\NodeTypeResolver\NodeTypeResolver $nodeTypeResolver)
{
$this->nodeTypeResolver = $nodeTypeResolver;
}
public function isNewMethodCallReturningSelf(\PhpParser\Node\Expr\MethodCall $methodCall) : bool
{
$newStaticType = $this->nodeTypeResolver->getStaticType($methodCall->var);
$methodCallStaticType = $this->nodeTypeResolver->getStaticType($methodCall);
return $methodCallStaticType->equals($newStaticType);
}
/**
* Method call with "new X", that returns "X"?
* e.g.
*
* $this->setItem(new Item) // → returns "Item"
*/
public function matchNewInFluentSetterMethodCall(\PhpParser\Node\Expr\MethodCall $methodCall) : ?\PhpParser\Node\Expr\New_
{
if (\count($methodCall->args) !== 1) {
return null;
}
if (!isset($methodCall->args[0])) {
return null;
}
if (!$methodCall->args[0] instanceof \PhpParser\Node\Arg) {
return null;
}
$onlyArgValue = $methodCall->args[0]->value;
if (!$onlyArgValue instanceof \PhpParser\Node\Expr\New_) {
return null;
}
$newType = $this->nodeTypeResolver->resolve($onlyArgValue);
if ($newType instanceof \PHPStan\Type\MixedType) {
return null;
}
$parentMethodCallReturnType = $this->nodeTypeResolver->resolve($methodCall);
if (!$newType->equals($parentMethodCallReturnType)) {
return null;
}
return $onlyArgValue;
}
}