betterNodeFinder = $betterNodeFinder;
$this->stmtsManipulator = $stmtsManipulator;
$this->valueResolver = $valueResolver;
$this->nodeComparator = $nodeComparator;
}
/**
* Matches:
*
* if (<$value> !== null) {
* return $value;
* }
*/
public function matchIfNotNullReturnValue(If_ $if) : ?Expr
{
if (\count($if->stmts) !== 1) {
return null;
}
$insideIfNode = $if->stmts[0];
if (!$insideIfNode instanceof Return_) {
return null;
}
if (!$if->cond instanceof NotIdentical) {
return null;
}
return $this->matchComparedAndReturnedNode($if->cond, $insideIfNode);
}
/**
* @return If_[]
*/
public function collectNestedIfsWithOnlyReturn(If_ $if) : array
{
$ifs = [];
$currentIf = $if;
while ($this->isIfWithOnlyStmtIf($currentIf)) {
$ifs[] = $currentIf;
/** @var If_ $currentIf */
$currentIf = $currentIf->stmts[0];
}
if ($ifs === []) {
return [];
}
if (!$this->hasOnlyStmtOfType($currentIf, Return_::class)) {
return [];
}
// last if is with the return value
$ifs[] = $currentIf;
return $ifs;
}
public function isIfAndElseWithSameVariableAssignAsLastStmts(If_ $if, Expr $desiredExpr) : bool
{
if (!$if->else instanceof Else_) {
return \false;
}
if ((bool) $if->elseifs) {
return \false;
}
$lastIfNode = $this->stmtsManipulator->getUnwrappedLastStmt($if->stmts);
if (!$lastIfNode instanceof Assign) {
return \false;
}
$lastElseNode = $this->stmtsManipulator->getUnwrappedLastStmt($if->else->stmts);
if (!$lastElseNode instanceof Assign) {
return \false;
}
if (!$lastIfNode->var instanceof Variable) {
return \false;
}
if (!$this->nodeComparator->areNodesEqual($lastIfNode->var, $lastElseNode->var)) {
return \false;
}
return $this->nodeComparator->areNodesEqual($desiredExpr, $lastElseNode->var);
}
/**
* @return If_[]
*/
public function collectNestedIfsWithNonBreaking(Foreach_ $foreach) : array
{
if (\count($foreach->stmts) !== 1) {
return [];
}
$onlyForeachStmt = $foreach->stmts[0];
if (!$onlyForeachStmt instanceof If_) {
return [];
}
if ($onlyForeachStmt->cond instanceof BooleanOr) {
return [];
}
$ifs = [];
$currentIf = $onlyForeachStmt;
while ($this->isIfWithOnlyStmtIf($currentIf)) {
$ifs[] = $currentIf;
/** @var If_ $currentIf */
$currentIf = $currentIf->stmts[0];
}
// IfManipulator is not build to handle elseif and else
if (!$this->isIfWithoutElseAndElseIfs($currentIf)) {
return [];
}
$return = $this->betterNodeFinder->findFirstInstanceOf($currentIf->stmts, Return_::class);
if ($return instanceof Return_) {
return [];
}
$exit = $this->betterNodeFinder->findFirstInstanceOf($currentIf->stmts, Exit_::class);
if ($exit instanceof Exit_) {
return [];
}
// last if is with the expression
$ifs[] = $currentIf;
return $ifs;
}
/**
* @param class-string