Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🖥 Build beautiful PHP CLI menus. Simple yet Powerful. Expressive DSL.

License

NotificationsYou must be signed in to change notification settings

php-school/cli-menu

Repository files navigation


Contents

Minimum Requirements

  • PHP 7.1
  • Composer
  • ext-posix

Installation

composer require php-school/cli-menu

Upgrading

Please refer to theUpgrade Documentation documentation to see what is required to upgrade your installedcli-menu version.

Usage

Quick Setup

Here is a super basic example menu which will echo out the text of the selected item to get you started.

<?phpusePhpSchool\CliMenu\CliMenu;usePhpSchool\CliMenu\Builder\CliMenuBuilder;require_once(__DIR__ .'/../vendor/autoload.php');$itemCallable =function (CliMenu$menu) {echo$menu->getSelectedItem()->getText();};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->setBorder(1,2,'yellow')    ->setPadding(2,4)    ->setMarginAuto()    ->build();$menu->open();

Examples

Check out theexamples directory and run them to see what is possible! The best way to run the examples is to git clone the repository:

git clone https://github.com/php-school/cli-menu.gitcd cli-menucomposer install --no-devcd examplesphp basic.php

Basic Menu

basic

Basic Menu Auto Centered

submenu

Basic Menu with separation

basic-seperation

Menu with crazy separation

crazy-seperation

Custom Styles

custom-styles

Borders and 256 colours

submenu

Useful Separation

useful-seperation

Displaying Item Extra

item-extra

Remove Defaults

remove-defaults

Submenu

submenu

submenu-options

Split Item

split-item

Disabled Items & Submenus

submenu

Checkbox Items

checkbox

checkbox-split

Radio Items

radio

radio-split

Flash Dialogue

submenu

Confirm Dialogue

submenu

Number Input

submenu

submenu

Text Input

submenu

Password Input

submenu

Using cli-menu to create art

Want to see something really cool? Well you can use cli-menu to create a drawing canvas on your terminal. Check it out!:

submenu

API

TheCliMenu object is constructed via the Builder class

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)/**     *  Customise    **/    ->build();

Once you have a menu object, you can open and close it like so:

$menu->open();$menu->close();

Appearance

Menu Title

You can give your menu a title and you can customise the separator, a line which displays under the title.Whatever string you pass tosetTitleSeparator will be repeated for the width of the Menu.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setTitle('One Menu to rule them all!')    ->setTitleSeparator('*-')    ->build();

Colour

You can change the foreground and background colour of the menu to any of the following colours:

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setForegroundColour('green')    ->setBackgroundColour('black')    ->build();

If your terminal supports 256 colours then you can also use any of those by specifying the code, like230. You can find a listof thecolours and codes here. If you specify a code and the terminal does not support 256 coloursit will automatically fallback to a sane default, using a generated map you can see in src/Util/ColourUtil.php. You can also manually specify thefallback colour as the second argument tosetForegroundColour and `setBackgroundColour.

In this example if no 256 colour support is found it will automatically fall back togreen andblue.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setForegroundColour('40')    ->setBackgroundColour('92')    ->build();

In this example if no 256 colour support is found it will fall back toyellow andmagenta.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setForegroundColour('40','yellow')    ->setBackgroundColour('92','magenta')    ->build();

Width

Customise the width of the menu. Setting a value larger than the size of the terminal will result inthe width being the same as the terminal size. The width will include the padding and the border. So with a width of 100and all around border of 5 and all around padding of 5 will leave for a content width of 80 (5 + 5 + 80 + 5 + 5).

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setWidth(1000)//if terminal is only 400, width will also be 400    ->build();

If you want to use the full width of the terminal, you can grab the terminal object and ask/set it from there like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = ($builder =newCliMenuBuilder)    ->setWidth($builder->getTerminal()->getWidth())    ->build();

If you want to use the full width of the terminal and apply a margin, use the terminal width, and we will do the calculationsautomatically (shrink the width based on the margin).

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = ($builder =newCliMenuBuilder)    ->setWidth($builder->getTerminal()->getWidth())    ->setMargin(2)    ->build();

Padding

The padding can be set for all sides with one value or can be set individually for top/bottom and left/right.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setPadding(10)//10 padding top/bottom/left/right    ->build();

Different values can also be set for the top/bottom and the left/right padding:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setPaddingTopBottom(10)    ->setPaddingLeftRight(5)    ->build();

Configure top/bottom and left/right padding using the shorthand method:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setPadding(10,5)//top/bottom = 10, left/right = 5    ->build();

Margin

The margin can be customised as one value. It can also be set automatically which will center the menu nicely in theterminal.

Automatically center menu:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setWidth(200)    ->setMarginAuto()     ->build();

Arbitrary margin:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setWidth(200)    ->setMargin(5)    ->build();

Borders

Borders can be customised just like CSS borders. We can add any amount of border to either side, left, right top orbottom and we can apply a colour to it.

Set universal red border of 2:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setWidth(200)    ->setBorder(2,'red')    ->build();

Configure each border separately:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setWidth(200)    ->setBorderTopWidth(2)    ->setBorderRightWidth(4)    ->setBorderBottomWidth(2)    ->setBorderLeftWidth(4)    ->setBorderColour('42','red')//SpringGreen2 fallback to red    ->build();

Configure each border separately using the shorthand method, like CSS:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setWidth(200)    ->setBorder(3,4,'red')//top/bottom = 3, left/right = 4    ->setBorder(3,4,5,'red')//top = 3, left/right = 4, bottom = 5    ->setBorder(3,4,5,6,'red')//top = 3, left = 4, bottom = 5, right = 6    ->build();

Exit Button Text

Modify the exit button text:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->setExitButtonText("Don't you want me baby?")    ->build();

Remove Exit Button

You can remove the exit button altogether:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->disableDefaultItems()    ->build();

Note: This will also disable the Go Back button for sub menus.

You can manually add exit and go back buttons using the following:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\Action\ExitAction;usePhpSchool\CliMenu\Action\GoBackAction;$menu = (newCliMenuBuilder)    ->disableDefaultItems()    ->addSubMenu('Super Sub Menu',function (CliMenuBuilder$b) {$b->disableDefaultItems()            ->setTitle('Behold the awesomeness')            ->addItem('Return to parent menu',newGoBackAction);//add a go back button    })    ->addItem('Leave this place now !',newExitAction)//add an exit button    ->build();

Items

There a few different types of items you can add to your menu

  • Selectable Item - This is the type of item you need for something to be selectable (you can hit enter and it will invoke your callable)
  • Checkbox Item - This is a checkbox type of item that keeps track of its toggled state to show a different marker.
  • Radio Item - This is a radio type of item that keeps track of its toggled state to show a different marker. Disables all other radios within itsCliMenu level.
  • Line Break Item - This is used to break up areas, it can span multiple lines and will be the width of Menu. Whatever string is passed will be repeated.
  • Static Item - This will print whatever text is passed, useful for headings.
  • Ascii Art Item - Special item which allows usage of Ascii art. It takes care of padding and alignment.
  • Sub Menu Item - Special item to allow an item to open another menu. Useful for an options menu.
  • Split Item - Special item to fit multiple items on the same row.

Selectable Item

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$menu = (newCliMenuBuilder)    ->addItem('The Item Text',function (CliMenu$menu) {echo'I am alive!';     })    ->build();

You can add multiple items at once like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$callable =function (CliMenu$menu) {echo'I am alive!';};$menu = (newCliMenuBuilder)    ->addItems([        ['Item 1',$callable],        ['Item 2',$callable],        ['Item 3',$callable],    ])    ->build();

Note: You can add as many items as you want and they can all have a different action. The action is the second parameterand must be a valid PHPcallable. Try using anInvokable class to keep your actions easily testable.

Checkbox Item

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$callable =function (CliMenu$menu) {echo$menu->getSelectedItem()->getText();};$menu = (newCliMenuBuilder)    ->addCheckboxItem('Item 1',$callable)    ->addCheckboxItem('Item 2',$callable)    ->addCheckboxItem('Item 3',$callable)    ->build();

You can add multiple checkbox items at once like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$callable =function (CliMenu$menu) {echo'I am alive!';};$menu = (newCliMenuBuilder)    ->addCheckboxItems([        ['Item 1',$callable],        ['Item 2',$callable],        ['Item 3',$callable],    ])    ->build();

When selecting an item, it will be toggled. Notice at first each item is unchecked. After selecting one it will becomechecked.

Radio Item

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$callable =function (CliMenu$menu) {echo$menu->getSelectedItem()->getText();};$menu = (newCliMenuBuilder)    ->addRadioItem('Item 1',$callable)    ->addRadioItem('Item 2',$callable)    ->addRadioItem('Item 3',$callable)    ->build();

You can add multiple radio items at once like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$callable =function (CliMenu$menu) {echo'I am alive!';};$menu = (newCliMenuBuilder)    ->addRadioItems([        ['Item 1',$callable],        ['Item 2',$callable],        ['Item 3',$callable],    ])    ->build();

When selecting an item, it will be toggled. Notice at first each item is unchecked. After selecting one it will becomechecked and all otherRadioItem within the same level will be unchecked.

Line Break Item

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->addLineBreak('<3',2)    ->build();

The above would repeat the character sequence<3 across the Menu for 2 lines

Static Item

Static items are similar to Line Breaks, however, they don't repeat and fill. It is output as is.If the text is longer than the width of the Menu, it will be continued on the next line.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$menu = (newCliMenuBuilder)    ->addStaticItem('AREA 1')//add some items here    ->addStaticItem('AREA 2')//add some boring items here    ->addStaticItem('AREA 51')//add some top secret items here    ->build();

Ascii Art Item

The following will place the Ascii art in the centre of your menu. Use these constants to alter thealignment:

  • AsciiArtItem::POSITION_CENTER
  • AsciiArtItem::POSITION_LEFT
  • AsciiArtItem::POSITION_RIGHT
<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\MenuItem\AsciiArtItem;$art =<<<ART        _ __ _       / |..| \       \/ || \/        |_''_|      PHP SCHOOLLEARNING FOR ELEPHANTSART;$menu = (newCliMenuBuilder)    ->addAsciiArt($art, AsciiArtItem::POSITION_CENTER)    ->build();

The third optional parameter toaddAsciiArt is alternate text. If the ascii art is too wide for the terminal, thenit will not be displayed at all. However, if you pass a string to the third argument, in the case that the ascii art is toowide for the terminal the alternate text will be displayed instead.

Sub Menu Item

Sub Menus are really powerful! You can add Menus to Menus, whattttt?? You can have your main menu and then an options menu.The options item will look like a normal item except when you hit it, you will enter to another menu, whichcan have different styles and colours!

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$callable =function (CliMenu$menu) {echo"I'm just a boring selectable item";};$menu = (newCliMenuBuilder)    ->addItem('Normal Item',$callable)    ->addSubMenu('Super Sub Menu',function (CliMenuBuilder$b) {$b->setTitle('Behold the awesomeness')            ->addItem(/** **/);    })    ->build();

In this example a single sub menu will be created. Upon entering the sub menu, you will be able to return to the main menuor exit completely. A Go Back button will be automatically added. You can customise this text using the->setGoBackButtonText() method on theCliMenuBuilderinstance for the sub menu.

There are a few things to note about the syntax and builder process here

  1. The first parameter toaddSubMenu is the text to be displayed on the menu which you select to enter the submenu.
  2. The second parameter is a closure, which will be invoked with a new instance ofCliMenuBuilder which you can use to customise the sub menu exactly the same way you would the parent
  3. If you do not modify the styles of the sub menu (eg, colours) it will inherit styles from the parent!

If you have already have a configured menu builder you can just pass that toaddSubMenuFromBuilder and be done:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;$subMenuBuilder = (newCliMenuBuilder)    ->setTitle('Behold the awesomeness')    ->addItem(/** **/);$menu = (newCliMenuBuilder)    ->addSubMenuFromBuilder('Super Sub Menu',$subMenuBuilder)    ->build();

Note: The submenu menu item will be an instance of\PhpSchool\CliMenu\MenuItem\MenuMenuItem. If you need access to the submenu,you can get it via$menuMenuItem->getSubMenu().

Split Item

Split Items allows you to add multiple items on the same row. The full width of the menu will be split evenly between all items. You can move between those items using left/right arrows.

You can set the number of spaces separating items using->setGutter() (defaults to 2).

Only Selectable, Checkbox, Radio, Static and SubMenu items are currently allowed inside a Split Item.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\Builder\SplitItemBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {echo$menu->getSelectedItem()->getText();};$menu = (newCliMenuBuilder)    ->setWidth(150)    ->addStaticItem('Below is a SplitItem')    ->addSplitItem(function (SplitItemBuilder$b)use ($itemCallable) {$b->setGutter(5)            ->addSubMenu('Sub Menu on a split item',function (CliMenuBuilder$b) {$b->setTitle('Behold the awesomeness')                    ->addItem('This is awesome',function() {print'Yes!'; });            })            ->addItem('Item 2',$itemCallable)            ->addStaticItem('Item 3 - Static');    })    ->build();$menu->open();

There are a few things to note about the syntax and builder process here:

  1. The first parameter toaddSplitItem is a closure, which will be invoked with a new instance ofSplitItemBuilder which you can use to add items to the split item.
  2. You can calladdItem,addCheckboxItem,addRadioItem,addSubMenu andaddStaticItem on theSplitItemBuilder.
  3. SplitItemBuilder has a fluent interface so you can chain method calls.

Disabling Items & Sub Menus

In this example we are disabling certain items and a submenu but still having them shown in the menu.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {echo$menu->getSelectedItem()->getText();};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu Disabled Items')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable,false,true)    ->addItem('Third Item',$itemCallable,false,true)    ->addSubMenu('Submenu',function (CliMenuBuilder$b)use ($itemCallable) {$b->setTitle('Basic CLI Menu Disabled Items > Submenu')            ->addItem('You can go in here!',$itemCallable);    })    ->addSubMenu('Disabled Submenu',function (CliMenuBuilder$b)use ($itemCallable) {$b->setTitle('Basic CLI Menu Disabled Items > Disabled Submenu')            ->addItem('Nope can\'t see this!',$itemCallable)            ->disableMenu();    })    ->addLineBreak('-')    ->build();

The third param on the->addItem call is what disables an item while the->disableMenu() call disables the relevant menu.

The outcome is a full menu with dimmed rows to denote them being disabled. When a user navigates the menu these items are jumped over to the next available selectable item.

Item Markers

The marker displayed by the side of the currently active item can be modified, UTF-8 characters are supported.The marker for un-selected items can also be modified. If you want to disable it, just set it to an empty string. Itemmarkers only display onselectable items, which are:\PhpSchool\CliMenu\MenuItem\SelectableItem &\PhpSchool\CliMenu\MenuItem\MenuMenuItem.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\Style\SelectableStyle;$menu = (newCliMenuBuilder)    ->modifySelectableStyle(function (SelectableStyle$style) {$style->setUnselectedMarker('')            ->setSelectedMarker('')// disable unselected marker            ->setUnselectedMarker('')        ;    })    ->build();

You may also change the marker for\PhpSchool\CliMenu\MenuItem\CheckboxItem:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\Style\CheckboxStyle;$menu = (newCliMenuBuilder)    ->modifyCheckboxStyle(function (CheckboxStyle$style) {$style->setUncheckedMarker('[○]')            ->setCheckedMarker('[●]');    })    ->addCheckboxItem('Orange juice',function () {})    ->addCheckboxItem('Bread',function () {})    ->build();

and for\PhpSchool\CliMenu\MenuItem\RadioItem:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\Style\RadioStyle;$menu = (newCliMenuBuilder)    ->modifyRadioStyle(function (RadioStyle$style) {$style->setUncheckedMarker('[ ]')            ->setCheckedMarker('[✔]');    })    ->addRadioItem('Go shopping',function () {})    ->addRadioItem('Go camping',function () {})    ->build();

Item Extra

You can optionally display some arbitrary text on the right hand side of an item. You can customise this text andyou indicate which items to display it on. We use it to display[COMPLETED] on completed exercises, where the menu listsexercises for a workshop application.

Item Extra is currently limited to only selectable items (menus, checkboxes & radios included)

The third parameter toaddItem is a boolean whether to show the item extra or not. It defaults to false.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;usePhpSchool\CliMenu\Style\SelectableStyle;$menu = (newCliMenuBuilder)    ->modifySelectableStyle(function (SelectableStyle$style) {$style->setItemExtra('');    })    ->addItem('Exercise 1',function (CliMenu$menu) {echo'I am complete!'; },true)    ->build();

If no items have display extra set to true, then the item extra will not be displayed. If you toggle the item to showit's item extra in a callback or at runtime it will render incorrectly.

In order to fix that you need to tell the menu to display item extra explicitly. You can do this when constructing themenu like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$menu = (newCliMenuBuilder)    ->setItemExtra('')    ->addItem('Exercise 1',function (CliMenu$menu) {$selectedItem =$menu->getSelectedItem();if ($selectedItem->showsItemExtra()) {$selectedItem->hideItemExtra();        }else {$selectedItem->showItemExtra();        }           })    ->displayExtra()    ->build();

Menu Methods

The next set of documentation applies to methods available directly on the\PhpSchool\CliMenu\CliMenu instance. Typicallyyou will invoke these methods whilst your menu is open in you action callbacks.

Redrawing the Menu

You can modify the menu and its style when executing an action and then you can redraw it! In this example we will toggle the backgroundcolour in an action.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$menu->getStyle()->setBg($menu->getStyle()->getBg() ==='red' ?'blue' :'red');$menu->redraw();};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

If you change the menu drastically, such as making the width smaller, when it redraws you might see artifacts of the previous drawasredraw only draws over the top of the terminal. If this happens you can passtrue toredraw and it will first clearthe terminal before redrawing.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$menu->getStyle()->setWidth($menu->getStyle()->getWidth() ===100 ?80 :100);$menu->redraw(true);};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Getting, Removing and Adding items

You can also interact with the menu items in an action. You can add, remove and replace items. If you do this, youwill likely want to redraw the menu as well so the new list is rendered.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;usePhpSchool\CliMenu\MenuItem\LineBreakItem;$itemCallable =function (CliMenu$menu) {foreach ($menu->getItems()as$item) {$menu->removeItem($item);    }//add single item$menu->addItem(newLineBreakItem('-'));//add multiple items$menu->addItems([newLineBreakItem('-'),newLineBreakItem('*')]);//replace all items$menu->setItems([newLineBreakItem('+'),newLineBreakItem('-')]);$menu->redraw();};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Custom Control Mapping

This functionality allows to map custom key presses to a callable. For example we can set the key press "x" to close the menu:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$exit =function(CliMenu$menu) {$menu->close();};$menu = (newCliMenuBuilder)    ->addItem('Item 1',function(CliMenu$menu) {})    ->build();$menu->addCustomControlMapping("x",$exit);$menu->open();

Another example is mapping shortcuts to a list of items:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$myCallback =function(CliMenu$menu) {echo"Client 1\nClient 2\nClient 3\n";};$menu = (newCliMenuBuilder)    ->addItem('List of [C]lients',$myCallback)    ->build();// Now, pressing Uppercase C (it's case sensitive) will call $myCallback$menu->addCustomControlMapping('C',$myCallback);$menu->open();

Item Keyboard Shortcuts

If you enable auto shortcutsCliMenuBuilder will parse the items text and check for shortcuts. Any single character inside square bracketswill be treated as a shortcut. Pressing that character when the menu is open will trigger that items callable.

This functionality works for split items as well as sub menus. The same characters can be used inside sub menus and thecallable which is invoked will depend on which menu is currently open.

Note: all shortcuts are lower cased.

To enable this automatic keyboard shortcut mapping simply call->enableAutoShortcuts():

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$myCallback =function(CliMenu$menu) {echo"Client 1\nClient 2\nClient 3\n";};$menu = (newCliMenuBuilder)    ->enableAutoShortcuts()    ->addItem('List of [C]lients',$myCallback)    ->build();$menu->open();//Pressing c will execute $myCallback.

You can customise the shortcut matching by passing your own regex toenableAutoShortcuts. Be careful to only matchone character in the first capture group or an exception will be thrown.

Dialogues

Flash

Show a one line message over the top of the menu. It has a separate style object which is colored by default differentto the menu. It can be modified to suit your own style. The dialogue is dismissed with any key press. In the examplebelow we change the background color on the flash to green.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;require_once(__DIR__ .'/../vendor/autoload.php');$itemCallable =function (CliMenu$menu) {$flash =$menu->flash("PHP School FTW!!");$flash->getStyle()->setBg('green');$flash->display();};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Confirm

Prompts are very similar to flashes except that a button is shown which has to be selected to dismiss them. The buttontext can be customised.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$menu->confirm('PHP School FTW!')        ->display('OK!');};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Inputs

Inputs - added in version 3.0 ofcli-menu allow to prompt the user for input and validate it. The following types are supported:text, number and password. Inputs can be executed in any item callback. They have separate style objects which are colored by default different to the menu.They can be modified to suit your own style.

Each input is created by calling one of theask* methods which will return aninstance of the input you requested. To execute the prompt and wait for the input you mustcallask() on the input. When the input has been received and validated,ask() will returnan instance ofInputResult.InputResult exposes the methodfetch to grab the raw input.

Text Input

The text input will prompt for a string and when the enter key is hit it will validate thatthe string is not empty. As well as the style you can modify the prompt text (the default is 'Enter text:'), theplaceholder text (the default is empty) and the validation failed text (the default is 'Invalid, try again').

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$result =$menu->askText()        ->setPromptText('Enter your name')        ->setPlaceholderText('Jane Doe')        ->setValidationFailedText('Please enter your name')        ->ask();var_dump($result->fetch());};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('Enter text',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Number Input

The number input will prompt for an integer value (signed or not) and when the enter key is hit it will validate thatthe input is actually a number (/^-?\d+$/). As well as the style you can modify the prompt text (the default is 'Enter a number:'), theplaceholder text (the default is empty) and the validation failed text (the default is 'Not a valid number, try again').

When entering a number you can use the up/down keys to increment and decrement the number.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$result =$menu->askNumber()        ->setPromptText('Enter your age')        ->setPlaceholderText(10)        ->setValidationFailedText('Invalid age, try again')        ->ask();var_dump($result->fetch());};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('Enter number',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Password Input

The password input will prompt for a text value and when the enter key is hit it will validate that the input is 16 characters or longer.As well as the style you can modify the prompt text (the default is 'Enter password:'), theplaceholder text (the default is empty) and the validation failed text (the default is 'Invalid password, try again'). You can also seta custom password validator as a PHP callable. When typing passwords they are echo'd back to the user as an asterisk.

Ask for a password with the default validation:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$result =$menu->askPassword()        ->setPromptText('Please enter your password')        ->setValidationFailedText('Invalid password, try again')        ->setPlaceholderText('')        ->ask();var_dump($result->fetch());};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('Enter password',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Validators can be any PHP callable. The callable will be passed the input value and must return a boolean, false indicatingvalidation failure and true indicating validation success. If validation fails then the validation failure text will be shown.

It is also possible to customise the validation failure message dynamically, but only when using aClosure as a validator.The closure will be binded to thePassword input class which will allow you to callsetValidationFailedText inside the closure.

Ask for a password with custom validation. Here we validate the password is not equal topassword and that thepassword is longer than 20 characters.

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$result =$menu->askPassword()        ->setPromptText('Please enter your password')        ->setValidationFailedText('Invalid password, try again')        ->setPlaceholderText('')        ->setValidator(function ($password) {return$password !=='password' &&strlen($password) >20;                    })        ->ask();var_dump($result->fetch());};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('Enter password',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Ask for a password with custom validation and set the validation failure message dynamically:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;$itemCallable =function (CliMenu$menu) {$result =$menu->askPassword()        ->setPromptText('Please enter your password')        ->setValidationFailedText('Invalid password, try again')        ->setPlaceholderText('')        ->setValidator(function ($password) {if ($password ==='password') {$this->setValidationFailedText('Password is too weak');returnfalse;            }elseif (strlen($password) <=20) {$this->setValidationFailedText('Password is not long enough');returnfalse;            }returntrue;        })        ->ask();var_dump($result->fetch());};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('Enter password',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Custom Input

If you need a new type of input which is not covered by the bundled selection then you can create your own by implementing\PhpSchool\CliMenu\Input\Input - take a look at existing implementations to see how they are built. If all you need is some customvalidation - extend the\PhpSchool\CliMenu\Input\Text class and overwrite thevalidate method. You can then use it inyour menu item actions like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;usePhpSchool\CliMenu\MenuStyle;usePhpSchool\CliMenu\Input\Text;usePhpSchool\CliMenu\Input\InputIO;$itemCallable =function (CliMenu$menu) {$style = (newMenuStyle())        ->setBg('yellow')        ->setFg('black');$input =newclass (newInputIO($menu,$menu->getTerminal()),$style)extends Text {publicfunctionvalidate(string$value) :bool        {//some validationreturntrue;        }    };$result =$input->ask();var_dump($result->fetch());};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('Enter password',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Dialogues & Input Styling

All of the dialogues and inputs expose agetStyle() method which you can use to customise the appearance of them. However, ifyou want to create a consistent style for all your dialogues and inputs without configuring it for each oneyou can build up aMenuStyle object and pass it to the dialogue and input methods like so:

<?phpusePhpSchool\CliMenu\Builder\CliMenuBuilder;usePhpSchool\CliMenu\CliMenu;usePhpSchool\CliMenu\MenuStyle;$popupStyle = (newMenuStyle)    ->setBg('green')    ->setFg('magenta');$itemCallable =function (CliMenu$menu)use ($popupStyle) {$menu->flash("PHP School FTW!!",$popupStyle)->display();$menu->confirm('PHP School FTW!',$popupStyle)->display('OK!');$menu->askNumber($popupStyle)->ask();};$menu = (newCliMenuBuilder)    ->setTitle('Basic CLI Menu')    ->addItem('First Item',$itemCallable)    ->addItem('Second Item',$itemCallable)    ->addItem('Third Item',$itemCallable)    ->addLineBreak('-')    ->build();$menu->open();

Once you get going you might just end up with something that looks a little like this...

Learn You PHP CLI Menu

You can see the construction code here for more clarity on how to perform advanced configuration:PHP School

Integrations

About

🖥 Build beautiful PHP CLI menus. Simple yet Powerful. Expressive DSL.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors24

Languages


[8]ページ先頭

©2009-2026 Movatter.jp