ifManipulator = $ifManipulator; $this->stmtsManipulator = $stmtsManipulator; } public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition { return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Change if/else value to early return', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE' class SomeClass { public function run() { if ($this->hasDocBlock($tokens, $index)) { $docToken = $tokens[$this->getDocBlockIndex($tokens, $index)]; } else { $docToken = null; } return $docToken; } } CODE_SAMPLE , <<<'CODE_SAMPLE' class SomeClass { public function run() { if ($this->hasDocBlock($tokens, $index)) { return $tokens[$this->getDocBlockIndex($tokens, $index)]; } return null; } } CODE_SAMPLE )]); } /** * @return array> */ public function getNodeTypes() : array { return [\PhpParser\Node\Stmt\If_::class]; } /** * @param If_ $node * @return Stmt[]|null */ public function refactor(\PhpParser\Node $node) : ?array { $nextNode = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::NEXT_NODE); if (!$nextNode instanceof \PhpParser\Node\Stmt\Return_) { return null; } if ($nextNode->expr === null) { return null; } if (!$this->ifManipulator->isIfAndElseWithSameVariableAssignAsLastStmts($node, $nextNode->expr)) { return null; } \end($node->stmts); $lastIfStmtKey = \key($node->stmts); /** @var Assign $assign */ $assign = $this->stmtsManipulator->getUnwrappedLastStmt($node->stmts); $return = new \PhpParser\Node\Stmt\Return_($assign->expr); $this->mirrorComments($return, $assign); $node->stmts[$lastIfStmtKey] = $return; $else = $node->else; if (!$else instanceof \PhpParser\Node\Stmt\Else_) { throw new \Rector\Core\Exception\ShouldNotHappenException(); } $elseStmts = $else->stmts; /** @var Assign $assign */ $assign = $this->stmtsManipulator->getUnwrappedLastStmt($elseStmts); \end($elseStmts); $lastElseStmtKey = \key($elseStmts); $return = new \PhpParser\Node\Stmt\Return_($assign->expr); $this->mirrorComments($return, $assign); $elseStmts[$lastElseStmtKey] = $return; $node->else = null; $this->removeNode($nextNode); return \array_merge([$node], $elseStmts); } }