rector/rules/Php80/NodeAnalyzer/SwitchAnalyzer.php
Tomas Votruba f45f2bf59a Updated Rector to commit d91667cd18cf3bb1b567a6c09ac15b26b6ac016a
d91667cd18 [PHP 8.0] Add implicit exception support to match (#182)
2021-06-08 13:06:20 +00:00

76 lines
2.2 KiB
PHP

<?php
declare (strict_types=1);
namespace Rector\Php80\NodeAnalyzer;
use PhpParser\Node;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\Case_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
final class SwitchAnalyzer
{
public function hasEachCaseBreak(\PhpParser\Node\Stmt\Switch_ $switch) : bool
{
$totalCases = \count($switch->cases);
if ($totalCases === 1) {
return $this->containsCaseReturn($switch->cases[0]);
}
foreach ($switch->cases as $key => $case) {
if ($key === $totalCases - 1) {
return \true;
}
if ($this->hasBreakOrReturnOrEmpty($case)) {
continue;
}
return \false;
}
return \true;
}
public function hasEachCaseSingleStmt(\PhpParser\Node\Stmt\Switch_ $switch) : bool
{
foreach ($switch->cases as $case) {
$stmtsWithoutBreak = \array_filter($case->stmts, function (\PhpParser\Node $node) : bool {
return !$node instanceof \PhpParser\Node\Stmt\Break_;
});
if (\count($stmtsWithoutBreak) !== 1) {
return \false;
}
}
return \true;
}
public function hasDefault(\PhpParser\Node\Stmt\Switch_ $switch) : bool
{
foreach ($switch->cases as $case) {
if ($case->cond === null) {
return \true;
}
}
return \false;
}
private function hasBreakOrReturnOrEmpty(\PhpParser\Node\Stmt\Case_ $case) : bool
{
if ($case->stmts === []) {
return \true;
}
foreach ($case->stmts as $caseStmt) {
if ($caseStmt instanceof \PhpParser\Node\Stmt\Break_) {
return \true;
}
if ($caseStmt instanceof \PhpParser\Node\Stmt\Return_) {
return \true;
}
}
return \false;
}
private function containsCaseReturn(\PhpParser\Node\Stmt\Case_ $case) : bool
{
foreach ($case->stmts as $stmt) {
if ($stmt instanceof \PhpParser\Node\Stmt\Return_) {
return \true;
}
}
return \false;
}
}