diff --git a/src/CliMenu.php b/src/CliMenu.php index 29eb5749..3a2682bc 100644 --- a/src/CliMenu.php +++ b/src/CliMenu.php @@ -212,6 +212,16 @@ public function addCustomControlMapping(string $input, callable $callable) : voi $this->customControlMappings[$input] = $callable; } + /** + * Shorthand function to add multiple custom control mapping at once + */ + public function addCustomControlMappings(array $map) : void + { + foreach ($map as $input => $callable) { + $this->addCustomControlMapping($input, $callable); + } + } + /** * Removes a custom control mapping */ diff --git a/test/CliMenuTest.php b/test/CliMenuTest.php index a1d987e1..6bad8f71 100644 --- a/test/CliMenuTest.php +++ b/test/CliMenuTest.php @@ -480,6 +480,62 @@ public function testAddCustomControlMapping() : void static::assertStringEqualsFile($this->getTestFile(), $this->output->fetch()); } + public function testAddCustomControlMappingsThrowsExceptionWhenOverwritingExistingDefaultControls() : void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Cannot rebind this input'); + + $menu = new CliMenu('PHP School FTW', []); + $menu->addCustomControlMappings([ + ' ' => function () { + } + ]); + } + + public function testAddCustomControlMappingsThrowsExceptionWhenAttemptingToOverwriteAddedCustomControlMap() : void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Cannot rebind this input'); + + $menu = new CliMenu('PHP School FTW', []); + $menu->addCustomControlMappings([ + 'c' => function () { + } + ]); + $menu->addCustomControlMappings([ + 'c' => function () { + } + ]); + } + + public function testAddCustomControlMappings() : void + { + $first = true; + $this->terminal->expects($this->any()) + ->method('read') + ->willReturn('c', 'x'); + + $style = $this->getStyle($this->terminal); + + $action = function (CliMenu $menu) { + $menu->close(); + }; + $item = new SelectableItem('Item 1', $action); + + $menu = new CliMenu('PHP School FTW', [$item], $this->terminal, $style); + $menu->addCustomControlMappings([ + 'c' => $action, + 'x' => $action + ]); + + $menu->open(); + static::assertStringEqualsFile($this->getTestFile(), $this->output->fetch()); + + $first = false; + $menu->open(); + static::assertStringEqualsFile($this->getTestFile(), $this->output->fetch()); + } + public function testRemoveCustomControlMappingThrowsExceptionIfNoSuchMappingExists() : void { $this->expectException(\InvalidArgumentException::class); diff --git a/test/res/testAddCustomControlMappings.txt b/test/res/testAddCustomControlMappings.txt new file mode 100644 index 00000000..6c1f18be --- /dev/null +++ b/test/res/testAddCustomControlMappings.txt @@ -0,0 +1,9 @@ + + +   +  PHP School FTW  +  ==========================================  +  ● Item 1  +   + +