Skip to content

Commit ab3b294

Browse files
authored
Merge pull request #159 from php-school/fix-infinite-loop
Fix infinite loop when no selectable items.
2 parents d01d834 + 1ca95cb commit ab3b294

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/CliMenu.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,17 @@ protected function moveSelectionVertically(string $direction) : void
283283
{
284284
$itemKeys = array_keys($this->items);
285285

286+
$increments = 0;
287+
286288
do {
289+
$increments++;
290+
291+
if ($increments > count($itemKeys)) {
292+
//full cycle detected, there must be no selected items
293+
//in the menu, so stop trying to select one.
294+
return;
295+
}
296+
287297
$direction === 'UP'
288298
? $this->selectedItem--
289299
: $this->selectedItem++;

test/CliMenuTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,20 @@ public function testGetSelectedItemThrowsExceptionIfNoSelectedItem() : void
920920
$menu->getSelectedItem();
921921
}
922922

923+
public function testMenuCanOpenAndFunctionWithoutAnySelectableItems() : void
924+
{
925+
$this->terminal->expects($this->exactly(3))
926+
->method('read')
927+
->willReturn("\033[B", "\033[B", 'Q');
928+
$menu = new CliMenu('PHP School FTW', [new StaticItem('One')], $this->terminal);
929+
$menu->addCustomControlMapping('Q', function (CliMenu $menu) {
930+
$menu->close();
931+
});
932+
$menu->open();
933+
934+
self::assertCount(1, $menu->getItems());
935+
}
936+
923937
private function getTestFile() : string
924938
{
925939
return sprintf('%s/res/%s.txt', __DIR__, $this->getName());

0 commit comments

Comments
 (0)