Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix infinite loop when no selectable items #148

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) princip
- Enable cursor when exiting menu (#110)
- Fixed (#71) - changed padding calculation when row too long to stop php notices (#112)
- Fixed wordwrap helper (#134)
- Fixed infinite loop when no selectable items exist in menu (#144, #148)

### Removed
- Dropped PHP 5.x and PHP 7.0 support (#79)
Expand Down
14 changes: 14 additions & 0 deletions src/CliMenu.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ class CliMenu
*/
private $currentFrame;

/**
* @var bool
*/
private $hasSelectableItems = false;

public function __construct(
?string $title,
array $items,
Expand Down Expand Up @@ -277,6 +282,10 @@ private function display() : void
*/
protected function moveSelectionVertically(string $direction) : void
{
if (!$this->hasSelectableItems) {
return;
}

$itemKeys = array_keys($this->items);

do {
Expand Down Expand Up @@ -493,6 +502,11 @@ public function open() : void

$this->configureTerminal();
$this->open = true;

$this->hasSelectableItems = array_reduce($this->items, function (bool $carry, MenuItemInterface $item) {
return $carry || $item->canSelect();
}, false);

$this->display();
}

Expand Down
16 changes: 16 additions & 0 deletions test/CliMenuTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,22 @@ public function testSelectableCallableReceivesSelectableAndNotSplitItem() : void
self::assertSame($expectedSelectedItem, $actualSelectedItem);
}

public function testMenuCanOpenAndFunctionWithoutAnySelectableItems() : void
{
$this->terminal->expects($this->exactly(3))
->method('read')
->willReturn("\033[B", "\033[B", 'Q');

$menu = new CliMenu('PHP School FTW', [new StaticItem('One')], $this->terminal);
$menu->addCustomControlMapping('Q', function (CliMenu $menu) {
$menu->close();
});

$menu->open();

self::assertCount(1, $menu->getItems());
}

private function getTestFile() : string
{
return sprintf('%s/res/%s.txt', __DIR__, $this->getName());
Expand Down