Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions src/Parser/SwitchTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -124,6 +124,13 @@ protected function parseSwitch(Node\Stmt\Switch_ $v): string
$caseConds = [];
$hasDefault = false;
}
if (!empty($caseConds) || $hasDefault) {
$target = count($caseGroups);
if ($hasDefault) {
$defaultTarget = $target;
}
$caseGroups[] = [$caseConds, $hasDefault, []];
}

foreach ($caseGroups as $groupIndex => [$conds]) {
if (!empty($conds)) {
Expand DownExpand Up@@ -172,14 +179,6 @@ protected function parseSwitch(Node\Stmt\Switch_ $v): string
$this->indentLevel--;
$code .= $this->getIndent() . '}' . PHP_EOL;
}
if (!empty($caseConds) || $hasDefault) {
// PHP allows a trailing label without statements; it has no code to execute.
if ($hasDefault && $defaultTarget === null) {
$code .= $this->getIndent() . 'if (!' . $switchMatched . ') {' . PHP_EOL;
$code .= $this->getIndent() . $switchTarget . ' = -1;' . PHP_EOL;
$code .= $this->getIndent() . '}' . PHP_EOL;
}
}
$this->indentLevel--;
$code .= $this->getIndent() . '} while (0);';

Expand Down
49 changes: 49 additions & 0 deletions tests/compiler/switch/trailing-empty-case.phpt
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
--TEST--
Switch evaluates and matches a trailing empty case
--FILE--
<?php
function mark(string $value): string
{
echo "evaluated:$value\n";
return $value;
}

function main(): void
{
switch ('subject') {
default:
echo "default\n";
break;
case mark('other'):
}

switch ('subject') {
default:
echo "default\n";
break;
case mark('subject'):
}

switch ('subject') {
default:
echo "unexpected-default\n";
break;
case mark('first-miss'):
case mark('subject'):
}

switch ('subject') {
case mark('default-miss'):
echo "unexpected-case\n";
break;
default:
}
}
?>
--EXPECT--
evaluated:other
default
evaluated:subject
evaluated:first-miss
evaluated:subject
evaluated:default-miss
Loading