An open API service indexing awesome lists of open source software.

https://github.com/eftec/clione

A minimanist PHP library to manage the Command Line operations (CLI)
https://github.com/eftec/clione

cli command-line php

Last synced: 5 months ago
JSON representation

A minimanist PHP library to manage the Command Line operations (CLI)

Awesome Lists containing this project

README

          

# CliOne

This library helps to create command line (CLI) operator for PHP in Windows, Mac and Linux

[![Packagist](https://img.shields.io/packagist/v/eftec/CliOne.svg)](https://packagist.org/packages/eftec/CliOne)
[![Total Downloads](https://poser.pugx.org/eftec/CliOne/downloads)](https://packagist.org/packages/eftec/CliOne)
[![Maintenance](https://img.shields.io/maintenance/yes/2025.svg)]()
[![composer](https://img.shields.io/badge/composer-%3E1.6-blue.svg)]()
[![php](https://img.shields.io/badge/php-7.4-green.svg)]()
[![php](https://img.shields.io/badge/php-8.4-green.svg)]()
[![CocoaPods](https://img.shields.io/badge/docs-70%25-yellow.svg)]()

## Features

✅ Windows, Linux and Mac Compatible.

✅ This library truly minimalist and simple, it only consists of 2 classes and nothing more and no external dependency.

✅ Arguments & user input

✅ This library was aimed to (optionally) fallback to user-input if the argument is missing.

✅ Colors available

✅ The design is mostly fluent (it adjusts to the width of the screen)

✅ Validation of values

✅ Support NO_COLOR environment variable. See https://no-color.org/

![](docs/examplecomplete.jpg)

## Getting started

Add the library using composer:

> composer require eftec/clione

And create a new instance of the library

```php
$cli=new CliOne(); // instance of the library
```

## Usage

For example, let's say we need to create a CLI code to read an information and save into a file.

```shell
>php basic.php read -o result.json
```

We have two arguments, the first (read) is in the first position, and it doesn't have any "-". The second is "-o" that
it is our flag with a value.

So we could create our arguments.

```php
$cli=new CliOne();
$cli->createParam('read',[],'first')->add(); // a positional argument (the first one) value-less
$cli->createParam('o',[],'flag')->add(); // a simple flag "-o"
```

And we could evaluate as

```php
$cli->evalParam('read');
$cli->evalParam('o');
// So we could obtain our values as:
var_dump($cli->getParameter('read')->value);
var_dump($cli->getParameter('o')->value);
// or as
var_dump($cli->getValue('read'));
var_dump($cli->getValue('o'));
```

It will return **false** if we don't set a value, and it will return the value it we set it.

```shell
>php basic.php read -o result.json
string(4) "read"
string(11) "result.json"
```

> **The parameters are created and evaluated separately because it allows to do more powerful operations with it.**
>
> For example, sometimes we want to show the help (the list of parameters available) without evaluating the parameters.

Ok, but now what if we want to create an alias of "-o"

```php
var_dump($cli->getParameter('o',['output','outputresult'])->value);
```

So we could call using this line

```shell
php basic.php read --output result.json
# or also
php basic.php read --outputresult result.json
# or also
php basic.php read -o=result.json
```

> **If the parameter is a flag, then the alias is a longflag ("--"). If the parameter is a longflag then the alias is a
flag.**

But let's say we need to ask for a password, however we want to be entered interactively.

```php
$cli->createParam('pwd',[],'flag') // we create the parameter
->setInput(true,'password') // and we ask (if the parameter is not entered as flag)
//for user input of the type password (however the password is not hidden visually)
->add();
$cli->evalParam('pwd'); // and don't forget to evaluate the parameter
```

So it will look like:

```shell
> php .\basic.php read -o result.json
Select the value of pwd [*****] :123
```

Now, let's say something more advanced, multiple options, we want to select the type of file: json, csv, html and xml

Our code

```php
$cli->createParam('type',[],'flag')
->setInput(true,'option',['json','csv','xml','html'])
->add();
```

And the result:

```shell
PS > php .\basic.php read -o result.json
Select the value of pwd [*****] :111
[1] json
[2] csv
[3] xml
[4] html
Select the value of type [] :2 #you could use TAB key for autocomplete, cool!
```

> **List of values are divided in two values, the visual value (simply called value), and the key-value.**. In this
> example, "csv" is a value and its key-value is "2".
>
> The list of values allows associative arrays and indexed arrays. Indexed arrays are renumbered to start in 1.

You could also enter

> php .\basic.php read -o result.json -pwd 123 -type json

Now, you can show the parameters ("show the syntax help") as follows:

```php
$cli->showParamSyntax2('parameters:');
```

But it will look plain.

It is because you can add a description, change the question and add more help information

```php
$cli->createParam('type',[],'flag')
->setDescription('it is the type of output','what is the option?',['it is the help1','example: -option xml'])
->setInput(true,'option',['json','csv','xml','html'])
->add();
```

So it will look like: (in colors)

```shell
parameters:
read The command [read]
-o, --output, --outputresult The output file without extension [result.json]
example: -o file
-pwd It is the password [*****]
-type it is the type of output [csv]
it is the help1
example: -option xml
```

There are more operations available but the basic is there.

# Table of contents

* [CliOne](#clione)
* [Features](#features)
* [Getting started](#getting-started)
* [Usage](#usage)
* [Table of contents](#table-of-contents)
* [Flow](#flow)
* [Input as arguments](#input-as-arguments)
* [Input interactive](#input-interactive)
* [User input (interactive)](#user-input-interactive)
* [Customize user input](#customize-user-input)
* [CliOne Class](#clione-class)
* [Method __construct()](#method-__construct)
* [Parameters:](#parameters)
* [Method getWindowsVersion()](#method-getwindowsversion)
* [Method instance()](#method-instance)
* [Parameters:](#parameters-1)
* [Method hasInstance()](#method-hasinstance)
* [Method hasMenu()](#method-hasmenu)
* [Method clearMenu()](#method-clearmenu)
* [Parameters:](#parameters-2)
* [Method addMenu()](#method-addmenu)
* [Parameters:](#parameters-3)
* [Method addMenuItem()](#method-addmenuitem)
* [Parameters:](#parameters-4)
* [Method addMenuItems()](#method-addmenuitems)
* [Parameters:](#parameters-5)
* [Method addMenuService()](#method-addmenuservice)
* [Parameters:](#parameters-6)
* [Method evalMenu()](#method-evalmenu)
* [Parameters:](#parameters-7)
* [Method getErrorType()](#method-geterrortype)
* [Method getMemory()](#method-getmemory)
* [Method setVariable()](#method-setvariable)
* [Parameters:](#parameters-8)
* [Method getVariable()](#method-getvariable)
* [Parameters:](#parameters-9)
* [Method addVariableCallBack()](#method-addvariablecallback)
* [Parameters:](#parameters-10)
* [Method callVariablesCallBack()](#method-callvariablescallback)
* [Method hasColorSupport()](#method-hascolorsupport)
* [Method testArguments()](#method-testarguments)
* [Parameters:](#parameters-11)
* [Method testUserInput()](#method-testuserinput)
* [Parameters:](#parameters-12)
* [Method setMemory()](#method-setmemory)
* [Parameters:](#parameters-13)
* [Method setErrorType()](#method-seterrortype)
* [Parameters:](#parameters-14)
* [Method findVendorPath()](#method-findvendorpath)
* [Parameters:](#parameters-15)
* [Method createParam()](#method-createparam)
* [Parameters:](#parameters-16)
* [Method createOrReplaceParam()](#method-createorreplaceparam)
* [Method downLevel()](#method-downlevel)
* [Parameters:](#parameters-17)
* [Method evalParam()](#method-evalparam)
* [Parameters:](#parameters-18)
* [Method throwError()](#method-throwerror)
* [Parameters:](#parameters-19)
* [Method showWarning()](#method-showwarning)
* [Parameters:](#parameters-20)
* [Method addHistory()](#method-addhistory)
* [Parameters:](#parameters-21)
* [Method setHistory()](#method-sethistory)
* [Parameters:](#parameters-22)
* [Method clearHistory()](#method-clearhistory)
* [Method listHistory()](#method-listhistory)
* [Method getArrayParams()](#method-getarrayparams)
* [Parameters:](#parameters-23)
* [Method getColSize()](#method-getcolsize)
* [Method getParameter()](#method-getparameter)
* [Parameters:](#parameters-24)
* [Method getValue()](#method-getvalue)
* [Parameters:](#parameters-25)
* [Method readArgument()](#method-readargument)
* [Parameters:](#parameters-26)
* [Method showHelp()](#method-showhelp)
* [Parameters:](#parameters-27)
* [Method makeBigWords()](#method-makebigwords)
* [Parameters:](#parameters-28)
* [Method getValueKey()](#method-getvaluekey)
* [Parameters:](#parameters-29)
* [Method isCli()](#method-iscli)
* [Method getSTDIN()](#method-getstdin)
* [Method readData()](#method-readdata)
* [Parameters:](#parameters-30)
* [Method readDataPHPFormat()](#method-readdataphpformat)
* [Parameters:](#parameters-31)
* [Method isParameterPresent()](#method-isparameterpresent)
* [Parameters:](#parameters-32)
* [Method addExtensionFile()](#method-addextensionfile)
* [Parameters:](#parameters-33)
* [Method saveData()](#method-savedata)
* [Parameters:](#parameters-34)
* [Method saveDataPHPFormat()](#method-savedataphpformat)
* [Parameters:](#parameters-35)
* [Method setAlign()](#method-setalign)
* [Parameters:](#parameters-36)
* [Method setArrayParam()](#method-setarrayparam)
* [Parameters:](#parameters-37)
* [Method reconstructPath()](#method-reconstructpath)
* [Parameters:](#parameters-38)
* [Method getPhpOriginalFile()](#method-getphporiginalfile)
* [Method setPhpOriginalFile()](#method-setphporiginalfile)
* [Parameters:](#parameters-39)
* [Method setColor()](#method-setcolor)
* [Parameters:](#parameters-40)
* [Method setParam()](#method-setparam)
* [Parameters:](#parameters-41)
* [Method setParamUsingArray()](#method-setparamusingarray)
* [Parameters:](#parameters-42)
* [Method createContainer()](#method-createcontainer)
* [Parameters:](#parameters-43)
* [Method getValueAsArray()](#method-getvalueasarray)
* [Parameters:](#parameters-44)
* [Method setPatternTitle()](#method-setpatterntitle)
* [Parameters:](#parameters-45)
* [Method setPatternCurrent()](#method-setpatterncurrent)
* [Parameters:](#parameters-46)
* [Method setPatternSeparator()](#method-setpatternseparator)
* [Parameters:](#parameters-47)
* [Method setPatternContent()](#method-setpatterncontent)
* [Parameters:](#parameters-48)
* [Method setStyle()](#method-setstyle)
* [Parameters:](#parameters-49)
* [Method show()](#method-show)
* [Parameters:](#parameters-50)
* [Method showBread()](#method-showbread)
* [Parameters:](#parameters-51)
* [Method showCheck()](#method-showcheck)
* [Parameters:](#parameters-52)
* [Method showFrame()](#method-showframe)
* [Parameters:](#parameters-53)
* [Method showLine()](#method-showline)
* [Parameters:](#parameters-54)
* [Method clearScreen()](#method-clearscreen)
* [Method cursorHome()](#method-cursorhome)
* [Method cursorMove()](#method-cursormove)
* [Parameters:](#parameters-55)
* [Method bell()](#method-bell)
* [Method getCursorPosition()](#method-getcursorposition)
* [Method showMessageBox()](#method-showmessagebox)
* [Parameters:](#parameters-56)
* [Method alignLinesVertically()](#method-alignlinesvertically)
* [Parameters:](#parameters-57)
* [Method maxWidth()](#method-maxwidth)
* [Method showParamSyntax()](#method-showparamsyntax)
* [Parameters:](#parameters-58)
* [Method showParamSyntax2()](#method-showparamsyntax2)
* [Parameters:](#parameters-59)
* [Method setDefaultStream()](#method-setdefaultstream)
* [Parameters:](#parameters-60)
* [Method setNoColor()](#method-setnocolor)
* [Parameters:](#parameters-61)
* [Method isNoColor()](#method-isnocolor)
* [Method setNoANSI()](#method-setnoansi)
* [Parameters:](#parameters-62)
* [Method isNoANSI()](#method-isnoansi)
* [Method wrapLine()](#method-wrapline)
* [Parameters:](#parameters-63)
* [Method showProgressBar()](#method-showprogressbar)
* [Parameters:](#parameters-64)
* [Method getPageSize()](#method-getpagesize)
* [Method showTable()](#method-showtable)
* [Parameters:](#parameters-65)
* [Method showValuesColumn()](#method-showvaluescolumn)
* [Parameters:](#parameters-66)
* [Method showWaitCursor()](#method-showwaitcursor)
* [Parameters:](#parameters-67)
* [Method hideWaitCursor()](#method-hidewaitcursor)
* [Method hideCursor()](#method-hidecursor)
* [Method showCursor()](#method-showcursor)
* [Method showparams()](#method-showparams)
* [Method showParamValue()](#method-showparamvalue)
* [Parameters:](#parameters-68)
* [Method strlen()](#method-strlen)
* [Parameters:](#parameters-69)
* [Method removechar()](#method-removechar)
* [Parameters:](#parameters-70)
* [Method upLevel()](#method-uplevel)
* [Parameters:](#parameters-71)
* [Method getCh()](#method-getch)
* [Parameters:](#parameters-72)
* [Method colorText()](#method-colortext)
* [Parameters:](#parameters-73)
* [Method colorLess()](#method-colorless)
* [Parameters:](#parameters-74)
* [Method colorMask()](#method-colormask)
* [Parameters:](#parameters-75)
* [Method initialEndStyle()](#method-initialendstyle)
* [Parameters:](#parameters-76)
* [Method replaceCurlyVariable()](#method-replacecurlyvariable)
* [Parameters:](#parameters-77)
* [menu](#menu)
* [addMenu()](#addmenu)
* [addMenuItem()](#addmenuitem)
* [addMenuItems()](#addmenuitems)
* [evalMenu()](#evalmenu)
* [clearMenu()](#clearmenu)
* [example](#example)
* [Examples](#examples)
* [Example using arguments](#example-using-arguments)
* [Example using user input](#example-using-user-input)
* [Example with a game](#example-with-a-game)
* [Example colors](#example-colors)
* [Example tables](#example-tables)
* [Types of user input](#types-of-user-input)
* [Types of colors](#types-of-colors)
* [Definitions](#definitions)
* [debug](#debug)
* [Compatibility](#compatibility)
* [Changelog](#changelog)

## Flow

* (optional) you can set the current value using the method setParam()
* If the type of parameter is not "onlyinput" and "none", then it reads the parameter
* Example: php program.php -param1 value --param2 -param3="hello world" parampositional
* If the parameter is found, then it is returned, **end of the flow**.
* If the parameter is not found then
* If setCurrentAsDefault() is set, and the current value is not null, then the default value is the current value.
* Otherwise, the default value is the value set using the method setDefault(). If none, then it uses null.
* if input is true setInput(true) then it asks to user-input the value
* if the user doesn't fill the information, then it returns the default value (if any), **end of the flow**
* if the user fills the information, but it is incorrect, then it asks again and again.
* if the user fills the right information, then it returns this value, **end of the flow**
* if input is true setInput(false) then
* Note: we were unable to read the values of the argument, and we don't want to read from user input.
* it returns the default value, and it could raise an error, **end of the flow**

Note:

* isRequired() if the value is missing, then it shows an error.
* setAllowEmpty() if the value is empty (not missing), then it allows to enter an empty value

## Input as arguments

```shell
php mycli.php subcommandfirst subcommandsecond -flag valueflag --longflag valueflag2 subcommandlatest
```

The system allows reading multiple types of arguments

* **first**: this argument does not have value, and it is position (in the very first position),
it must be not be prefixed with a "-", otherwise it would be considered a flag instead of a positional argument.

```shell
cliprogram.php first # the value obtained is "first".
```

* **command**: it is similar to **first,** but it does not compare the name of the argument.

```shell
cliprogram.php com -flag # first returns "com" if the argument is named first. command returns "com" regardless of its name.
```

* **second**: this argument is also positional (second position) and does not have any value

```shell
cliprogram.php first second -someflag # the value obtained is "second"
```

* **last**: this argument is also positional, and it is always at the latest argument

```shell
cliprogram.php first second last # the value obtained is "last"
```

* **flag**: the argument is prefixed with a single "-". This argument not need to be a single character.

```shell
cliprogram.php -flag hello # the value of the flag called "flag" is "hello"
```

* **longflag**: the argument is prefixed with a double "--"

```shell
cliprogram.php --flag hello # the value of the doubleflag called "flag" is "hello"
```

* **onlyinput/none**: the system never read it as argument, so it could be user-input.
* none means that the argument is only user-input, and it must not be stored.

```shell
cliprogram.php # "onlyinput/none" could not be obtained via command line
```

The argument could be created as:

```php
// program.php -f hello
// or
// program.php -f=hello
// or
// program.php -f "hello world"
$cli->createParam('f','flag')->add(); // add() is important otherwise the parameter will not be create.
```

And it could be read as:

```php
$result=$cli->evalParam('name'); // $result->value will return "hello"
```

Now, what if you want to create multiples alias for the same parameter.

```php
// program.php -h
// or
// program.php --help
$cli->createParam('h','flag',['help'])->add(); // it adds an alias longflag called "help"
```

## Input interactive

There are several configuration to set an input interactively.

By default, every parameter is read as argument. If the value is read as argument, then it is not asked interactively.

However, if the parameter is of the type "**none**" or "**onlyinput**", then they are only obtained by user input (
interactively).

Example:

```php
$cli->$t->createParam('paramname',[],'none');
```

### User input (interactive)

With the method setInput() we set that this parameter could also be read interactively.

```php
$cli->$t->createParam('paramname',[],'none')->setInput();
```

Example, let's say the next example:

```php
$cli=new CliOne();
$cli->createParam('p1',[],'none')
->setInput()
->add(); // we create the param
$cli->evalParam('p1'); // and we evaluated the parameter
```

![](docs/basic1.jpg)

Now, this input accepts any kind of text. But there is many kind of user input.

| type | description | argument | example |
|-------------|-----------------------------------------------------------------------|-------------------------------------|----------------------------------------------------------------|
| number | It allows any kind of number | | setInput(true,"number") |
| range | it only allow number between a range of values | [1,20] | setInput(true,"range",[1,10]) |
| string | It allows any type of value | (used for auto complete) | setInput(true,"string") |
| password | It allows any type of value but the default value is never displayed | setInput(true,"password") | |
| multiple | it allows to check one or multiple values using 1 column | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"multiple",['key1'=>'value1','key2'=>'value2']) |
| multiple2 | it allows to check one or multiple values using 2 columns | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"multiple2",['key1'=>'value1','key2'=>'value2']) |
| multiple3 | it allows to check one or multiple values using 3 columns | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"multiple3",['key1'=>'value1','key2'=>'value2']) |
| multiple4 | it allows to check one or multiple values using 4 columns | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"multiple4",['key1'=>'value1','key2'=>'value2']) |
| option | it allows to select a value from a list using 1 column | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"option",['key1'=>'value1','key2'=>'value2']) |
| option2 | it allows to select a value from a list using 2 columns | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"option2",['key1'=>'value1','key2'=>'value2']) |
| option3 | it allows to select a value from a list using 3 columns | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"option3",['key1'=>'value1','key2'=>'value2']) |
| option4 | it allows to select a value from a list using 4 columns | ['key1'=>'value1','key2'=>'value2'] | setInput(true,"option4",['key1'=>'value1','key2'=>'value2']) |
| optionshort | It allows a selection of values | ["yes","no"] | setInput(true,"multiple4",['key1'=>'value1','key2'=>'value2']) |

Option returns a value and a value-key. Value is the content visible. And value-key, is the content selected by the
user.

**Example Option:**

```php
$cli=new CliOne();
$cli->createParam('p1',[],'none')
->setInput(true,'option2',['key1'=>'value1','key2'=>'value2','key3'=>'value3','key4'=>'value4'])
->add(); // we create the param
$cli->evalParam('p1');
$cli->showLine("value :".$cli->getValue('p1'));
$cli->showLine("valuekey :".$cli->getValueKey('p1'));
```

![](docs/basic2.jpg)

**Example Multiple:**

```php
$cli=new CliOne();
$cli->createParam('p1',[],'none')
->setInput(true,'option2',['key1'=>'value1','key2'=>'value2','key3'=>'value3','key4'=>'value4'])
->add();
$cli->evalParam('p1'); // value returns an associative array with the values selected, example: ["value1","value3"]
```

![](docs/basic3.jpg)

### Customize user input

It is possible to customize the input by changing the help description, changing the question, showing an example or
showing a value to the argument

```php
$cli=new CliOne();
$cli->createParam('p1',[],'none')
->setInput()
->setDescription('it is for help','what is the value of p1?',['help line1','help line 2'],'the argument is called p1')
->add();
$cli->evalParam('p1');
```

## CliOne Class
CliOne - A simple creator of command-line argument program.

### Method __construct()

The constructor. If there is an instance, then it replaces the instance.

#### Parameters:

* **$origin** you can specify the origin script file. If you specify the origin script
then, isCli will only return true if the file is called directly using its file. (string|null)
* **$ignoreCli** if true, then it will run no matter if it is running on cli or not. (bool)

### Method getWindowsVersion()

It returns the current Windows version as a decimal number.

If no version is found then it returns 6.1 (Windows 7).

Windows 10 and Windows 11 versions are returned as 10.xxxx instead of 10.0.xxxx

### Method instance()

It gets the current instance of the library.

If the instance does not exist, then it is created

#### Parameters:

* **$origin** you can specify the origin script file. If you specify the origin script
then, isCli will only return true if the file is called directly using its file. (string|null)

### Method hasInstance()

Returns true if there is an instance of CliOne.

### Method hasMenu()

It returns true if CliOne has a menu defined. It will return false if there is no menu or there is no instance.

### Method clearMenu()

It clears a menu and the services associated.

#### Parameters:

* **$idMenu** If null, then it clears all menus (string|null)

### Method addMenu()

It adds a new menu that could be called by evalMenu()

**Example:**

```
//"fnheader" call to $this->menuHeader(CliOne $cli);
$this->addMenu('idmenu','fnheader',null,'What do you want to do?','option3');
// you can use a callable argument, the first argument is of type CliOne.
$this->addMenu('idmenu',function($cli) { echo "header";},function($cli) { echo "footer;"});
```

#### Parameters:

* **$idMenu** The unique name of the menu (string)
* **$headerFunction** Optional, the name of the method called every time the menu is
displayed

The method called must have a prefix menu.Ex:"opt1",method:menuopt1"
If $headerFunction is callable, then it calls the function. (string|null|callable)
* **$footerFunction** Optional, the name of the method called every time the menu end its
display. The method called must have a prefix "menu".

If $footerFunction is callable, then it calls the function (string|null|callable)
* **$question** The input question. (string)
* **$size** =['option','option2','option3','option4','wide-option','wide-option2'][$i]
The size of the option menu. (string)

### Method addMenuItem()

It adds a menu item.

**Example:**

```
$this->addMenu('menu1');
// if op1 is selected then it calls method menufnop1(), the prefix is for protection.
$this->addMenuItem('menu1','op1','option #1','fnop1');
// if op1 is selected then it calls method menuop2()
$this->addMenuItem('menu1','op2','option #2');
$this->addMenuItem('menu1','op3','go to menu2','navigate:menu2');
$this->addMenuItem('menu1','op4','call function',function(CliOne $cli) { });
$this->evalMenu('menu1',$obj);
// the method inside $obj
public function menufnop1($caller):void {
}
public function menuop2($caller):string {
return 'EXIT'; // if any function returns EXIT (uppercase), then the menu ends (simmilar to "empty to
exit")
}
```

#### Parameters:

* **$idMenu** The unique name of the menu (string)
* **$indexMenuItem** The unique index of the menu. It is used for selection and action
(if no action is supplied). (string)
* **$description** The description of the menu (string)
* **$action** The action is the method called (the method must have a prefix
"menu").
If action starts with "navigate:" then it opens
the menu indicated.
If action is "exit:" then exit of the
menu.
If action is callable, then it calls the function (string|null|callable)

### Method addMenuItems()

It adds multiples items to a menu

**Example:**

```
$this->addMenu('menu1');
$this->addMenuItems('menu1',[
'op1'=>['operation #1','action1'], // with description & action
'op2'=>'operation #2']); // the action is "op2"
```

#### Parameters:

* **$idMenu** The unique name of the menu (string)
* **$items** An associative array with the items to add. Examples:

[index=>[description,action]]

[index=>description]
(array|null)

### Method addMenuService()

It adds a service object to be evaluated when we run evalMenu()

You can add menu services. Every service is evaluated in order, so if both service objects has the same method,
then it is only called by the first object.

If evalMenu() uses a service then, the services defined here are ignored.

**Example:**

```
$objService=new Class1();
$this->addMenuService('menu1',$objService);
// or:
$this->addMenuService('menu1',Class1:class);
```

#### Parameters:

* **$idMenu** The unique name of the menu (string)
* **$service** The service object or the name of the class.

If it is a name of a class, then it creates an instance of it. (object|string)

### Method evalMenu()

Eval (executes) a menu previously defined.

**Example:**

```
$this->addMenu('menu1');
// pending: add items to the menu
$this->evalMenu('menu1',$myService);
// or also
$this->>addMenu('menu1')->addMenuService('menu1',$myService)->evalMenu('menu1');
```

#### Parameters:

* **$idMenu** The unique name of the menu (string)
* **$caller** The caller object(s). It is used to the events and actions.

If null, then it use the services defined by addMenuService();

If it is an array, then it calls the first object that has the method

If this argument is used then addMenuService() is ignored (object|null|array)

### Method getErrorType()

### Method getMemory()

### Method setVariable()

It sets a value into an array.

#### Parameters:

* **$variableName** the name of the variable. If the variable exists, then it is replaced. (string)
* **$value** the value to assign. (mixed)
* **$callBack** if the value is true (default), then every modification (if the value is changed)
will call the functions defined in addVariableCallBack()
if fallse, then it does
not call the callback functions. (bool)

### Method getVariable()

It gets the value of a variable

#### Parameters:

* **$variableName** The name of the variable (string)
* **$valueIfNotFound** If not found then it returns this value (mixed|null)

### Method addVariableCallBack()

It adds a callback function.

**Example:**

```
$t->addVariableCallBack('call1', function(CliOne $cli) {
$cli->setVariable('v2', 'world',false); // the false is important if you don't want recursivity
});
```

This function is called every setVariable() if the value is different as the defined.

#### Parameters:

* **$callbackName** the name of the function. If the function exists, then it is replaced. (string)
* **$function** If the function is null, then it deleted the function assigned.

The function could be defined using an argument of the type CliOne. (callable|null)

### Method callVariablesCallBack()

It calls the callback functions. Usually they are called every time we setVariable() (and the value is changed).

### Method hasColorSupport()

This function is based in Symfony

### Method testArguments()

It is used for testing. You can simulate arguments using this function

This function must be called before the creation of the instance

#### Parameters:

* **$arguments** param array $arguments (array)

### Method testUserInput()

It is used for testing. You can simulate user-input using this function

This function must be called before every interactivity

This function is not resetted automatically, to reset it, set $userInput=null

#### Parameters:

* **$userInput** param ?array $userInput (?array)
* **$throwNoInput** (def:true) if true then it throws an exception if not input

if false, then if no more input then it cleans the userinput (bool)

### Method setMemory()

It sets the value stored into the memory stream

If the memory stream has values, then they are deleted and replaced.

#### Parameters:

* **$memory** The value to store (string)

### Method setErrorType()

It sets if you want to display errors or not. This flag is reseted every time it is used.

#### Parameters:

* **$errorType** =['silent','show','throw'][$i] (default is show) (string)

### Method findVendorPath()

It finds the vendor path starting from a route. The route must be inside the application path.

#### Parameters:

* **$initPath** the initial path, example __DIR__, getcwd(), 'folder1/folder2'. If null, then
__DIR__ (?string)

### Method createParam()

It creates a new parameter to be read from the command line and/or to be input manually by the user

**Example:**

```
$this->createParam('k1','first'); // php program.php thissubcommand
$this->createParam('k1','flag',['flag2','flag3']); // php program.php -k1 or --flag2 or --flag3

```

#### Parameters:

* **$key** The key or the parameter. It must be unique. (string)
* **$alias** A simple array with the name of the arguments to read without "-" or
flag: (default) it reads a flag "php program.php -thisflag
value"

first: it reads the first argument "php program.php thisarg"
(without value)

second: it reads the second argument "php program.php sc1
thisarg" (without value)

last: it reads the second argument "php program.php ... thisarg"
(without value)

longflag: it reads a longflag "php program --thislongflag
value

last: it reads the second argument "php program.php ...
thisvalue" (without value)

onlyinput: the value means to be user-input, and it is
stored

none: the value it is not captured via argument, so it could be
user-input, but it is not stored
none parameters could always be
overridden, and they are used to "temporary" input such as validations
(y/n). (array|string)
* **$type** =['command','first','last','second','flag','longflag','onlyinput','none'][$i]

"-"
if the type is a flag, then the alias is a double flag
"--".
if the type is a double flag, then the alias is a flag. (string)
* **$argumentIsValueKey** true the argument is value-key

false (default) the argument is a value (bool)

### Method createOrReplaceParam()

### Method downLevel()

Down a level in the breadcrub.

If down more than the number of levels available, then it clears the stack.

#### Parameters:

* **$number** number of levels to down. (int)

### Method evalParam()

It evaluates the parameters obtained from the syntax of the command.

The parameters must be defined before call this method

**Example:**

```
// shell:
php mycode.php -argument1 hello -argument2 world
// php code:
$t=new CliOne('mycode.php');
$t->createParam('argument1')->add();
$result=$t->evalParam('argument1'); // an object ClieOneParam where value is "hello"
```

#### Parameters:

* **$key** the key to read.

If $key='*' then it reads the first flag and returns its value (if any). (string)
* **$forceInput** it forces input no matter if the value is already inserted. (bool)
* **$returnValue** If true, then it returns the value obtained.

If false (default value), it returns an instance of CliOneParam. (bool)

### Method throwError()

It throws an error. Depending on the type, it could show an error or throw a runtime exception.

#### Parameters:

* **$msg** param string $msg (string)

### Method showWarning()

It shows a warning

#### Parameters:

* **$msg** param array|string $msg (array|string)

### Method addHistory()

Add a value to the history

#### Parameters:

* **$prompt** the value(s) of the history to add (string|array)

### Method setHistory()

It sets the history (deleting the old history) with the new values

#### Parameters:

* **$prompt** param string|array $prompt (string|array)

### Method clearHistory()

It clears the global history (if any).

### Method listHistory()

It retrieves the global history (if any)

### Method getArrayParams()

It returns an associative array with all the parameters of the form [key=>value]

Parameters of the type "none" are ignored

#### Parameters:

* **$excludeKeys** you can add a key that you want to exclude. (array)

### Method getColSize()

It returns the number of columns present on the screen. The columns are calculated in the constructor.

### Method getParameter()

It gets the parameter by the key or an empty parameter with a null key if null.

#### Parameters:

* **$key** the key of the parameter (string)

### Method getValue()

It reads a value of a parameter.
**Example:**

```
// [1] option1
// [2] option2
// select a value [] 2
$v=$this->getValueKey('idparam'); // it will return "option2".
```

#### Parameters:

* **$key** the key of the parameter to read the value (string)

### Method readArgument()

It reads a parameter as an argument or flag.

#### Parameters:

* **$parameter** param CliOneParam $parameter (CliOneParam)

### Method showHelp()

It shows the help

#### Parameters:

* **$parameter** param CliOneParam $parameter (CliOneParam)
* **$verbose** param bool $verbose (bool)

### Method makeBigWords()

#### Parameters:

* **$word** the words to display. (string)
* **$font** =['atr','znaki'][$i] (string)
* **$trim** if true then, if the first line and/or the last line is empty, then it is removed. (bool)
* **$bit1** the visible character, if null then it will use a block code (?string)
* **$bit0** the invisible character (string)

### Method getValueKey()

It reads the value-key of a parameter selected. It is useful for a list of elements.

**Example:**

```
// [1] option1
// [2] option2
// select a value [] 2
$v=$this->getValueKey('idparam'); // it will return 2 instead of "option2"
```

#### Parameters:

* **$key** the key of the parameter to read the value-key (string)

### Method isCli()

It will return true if the PHP is running on CLI

If the constructor specified a file, then it is also used for validation.
**Example:**

```
// page.php:
$inst=new CliOne('page.php'); // this security avoid calling the cli when this file is called by others.
if($inst->isCli()) {
echo "Is CLI and the current page is page.php";
}
```

### Method getSTDIN()

It gets the STDIN exclusively if the value is passed by pipes. If not, it returns null;

### Method readData()

It reads information from a file. The information will be de-serialized.

#### Parameters:

* **$filename** the filename with or without extension. (string)
* **$defaultExtension** the default extension. (string)

### Method readDataPHPFormat()

It reads information from a file. The information is evaluated, so the file must be safe.

#### Parameters:

* **$filename** the filename with or without extension. (string)
* **$defaultExtension** the default extension. (string)

### Method isParameterPresent()

Returns true if the parameter is present with or without data.

The parameter is not changed, neither the default values nor user input are applied

Returned Values:



  • none the value is not present, ex:


  • empty the value is present but is empty, ex: -arg1


  • value the value is present, and it has a value, ex: -arg1 value

#### Parameters:

* **$key** param string $key (string)

### Method addExtensionFile()

Util class. It adds a default extension to a filename only if the filename doesn't have extension.

#### Parameters:

* **$filename** The filename full or partial, example "file.jpg", "file", "/folder/file" (string)
* **$extension** The extension to add including the dot, example ".ext".

The default value is ".config.php" (string)

### Method saveData()

It saves the information into a file. The content will be serialized.

#### Parameters:

* **$filename** the filename (without extension) to where the value will be saved. (string)
* **$content** The content to save. It will be serialized. (mixed)
* **$defaultExtension** The default extension. (string)

### Method saveDataPHPFormat()

It saves the information into a file. The content will be converted into a PHP file.

**Example:**

```
$this->saveDataPHPFormat('file',[1,2,3]); // it will save a file with the next content: $config=[1,2,3];
```

#### Parameters:

* **$filename** the filename (without extension) to where the value will be saved. (string)
* **$content** The content to save. It will be serialized. (mixed)
* **$defaultExtension** The default extension. (string)
* **$namevar** The name of the variable, excample: config or $config (string)

### Method setAlign()

It sets the alignment. This method is stackable.

**Example:**

```
$cli->setAlign('left','left','right')->setStyle('double')->showTable($values);
```

#### Parameters:

* **$title** =['left','right','middle'][$i] the alignment of the title (string)
* **$content** =['left','right','middle'][$i] the alignment of the content (string)
* **$contentNumeric** =['left','right','middle'][$i] the alignment of the content (numeric) (string)

### Method setArrayParam()

It sets the parameters using an array of the form [key=>value]

It also marks the parameters as missing=false

#### Parameters:

* **$array** the associative array to use to set the parameters. (array)
* **$excludeKeys** you can add a key that you want to exclude.

If the key is in the array and in this list, then it is excluded (array)
* **$includeKeys** the whitelist of elements that only could be included.

Only keys that are in this list are added. (array|null)

### Method reconstructPath()

It is used internally to reconstruct the path of the current script.

#### Parameters:

* **$includePHP** param bool $includePHP (bool)
* **$trimArguments** param int $trimArguments (int)

### Method getPhpOriginalFile()

It gets the php original file

### Method setPhpOriginalFile()

It sets the php original file

#### Parameters:

* **$phpOriginalFile** param string $phpOriginalFile (string)

### Method setColor()

It sets the color in the stack

#### Parameters:

* **$colors** =['red','yellow','green','white','blue','black',cyan','magenta'][$i] (array)

### Method setParam()

It sets the value or value-key of a parameter manually.

It also marks the origin of the argument as "set" and it markes the argument as missing=false

#### Parameters:

* **$key** the key of the parameter (string)
* **$value** the value (or the value-key) to assign. (mixed)
* **$isValueKey** if false (default) then the argument $value is the value of the
parameter
if true then the argument $value is the value-key. (bool)
* **$createIfNotExist** If true and the parameter doesn't exist, then it is created with the default
configuration. (bool)

### Method setParamUsingArray()

Set the values of the parameters using an array.

If the parameter does not exist, then it is created with the default values

#### Parameters:

* **$assocArray** An associative array of the form ['key'=>'value'] (array|null)
* **$fields** if null, then is set all values of the array

If not null, then it is used to determine which fields will be used (array|null)

### Method createContainer()

USE FUTURE. It creates a container.

#### Parameters:

* **$width** param $width ()
* **$height** param $height ()

### Method getValueAsArray()

It gets the values of the parameters are an associative array.

#### Parameters:

* **$fields** If the fields are null then it returns all parameters, including "none". (array|null)
* **$asAssocArray** (def:true) if true then it returns the values as an associative array

if false, then it returns as an indexed array. (bool)

### Method setPatternTitle()

It sets the pattern used for the title. This operation is used in a stack.
{value} {type}

#### Parameters:

* **$pattern1Stack** if null then it will use the default value. (?string)

### Method setPatternCurrent()

{value}{type}

#### Parameters:

* **$pattern2Stack** if null then it will use the default value. (?string)

### Method setPatternSeparator()

">"

#### Parameters:

* **$pattern3Stack** if null then it will use the default value. (?string)

### Method setPatternContent()

Not used yet.

#### Parameters:

* **$pattern4Stack** if null then it will use the default value. (?string)

### Method setStyle()

It sets the styles used by different elements

#### Parameters:

* **$style** =['mysql','simple','double','minimal','style'][$i] (string)
* **$waitingIconStyle** =['triangle','braille','pipe','braille2','bar','bar2','bar3','arc','waiting'][$i]

if is an array, then it uses the elements of array to show the waiting
icon (string|array)

### Method show()

It's similar to showLine, but it keeps in the current line.

#### Parameters:

* **$content** param string $content (string)
* **$stream** =['stdout','stderr','memory'][$i] (?string)

### Method showBread()

It shows a breadcrumb.

To add values you could use the method uplevel()

To remove a value (going down a level) you could use the method downlevel()

You can also change the style using setPattern1(),setPattern2(),setPattern3()

```
$cli->setPattern1('{value}{type}') // the level
->setPattern2('{value}{type}') // the current level
->setPattern3(' -> ') // the separator
->showBread();
```

It shows the current BreadCrumb if any.

#### Parameters:

* **$showIfEmpty** if true then it shows the breadcrumb even if it is empty (empty line)

if false (default) then it doesn't show the breadcrumb if it is empty. (bool)

### Method showCheck()

It shows a label messages in a single line, example: [ERROR] Error message

#### Parameters:

* **$label** param string|array $label (string|array)
* **$color** =['red','yellow','green','white','blue','black',cyan','magenta'][$i] (string)
* **$content** param string|array $content (string|array)
* **$stream** =['stdout','stderr','memory'][$i] (string)

### Method showFrame()

It shows a border frame.

#### Parameters:

* **$lines** the content. (string|string[])
* **$titles** if null then no title. (string|string[]|null)

### Method showLine()

It shows (echo) a colored line. The syntax of the color is similar to html as follows:

**Example:**

```
error; (color red)
warning (color yellow)
information (blue)
yellow (yellow)
green (color green)
italic
bold
error; (color background red, it also works for the other colors )
dim
invisible (it could not work in some terminals)
underline
strikethrough
cyan (color light cyan)
magenta (color magenta)
columns. col0=0
(left),col1--col5 every column of the page.
it shows all the options available (if the input has some options)
```

#### Parameters:

* **$content** content to display (string|string[])
* **$cliOneParam** param ?CliOneParam $cliOneParam (?CliOneParam)
* **$stream** =['stdout','stderr','memory'][$i] (?string)

### Method clearScreen()

It clears the current screen

**Example:**

```
$this->clearScreen(); // clear the screen
$this->clearScreen()->cursorHome(); // clear the screen and put the cursor at the home position
```

### Method cursorHome()

It sets the cursor to the top left position

**Example:**

```
$this->cursorHome(); // put the cursor at the home position
```

### Method cursorMove()

It moves the cursor at some specific position

**Example:**

```
$this->cursorMove('up',5); // move relatively 5 up
$this->cursorMove('upmost',1); // move to the up position down 1.
$this->cursorMove('down',5); // move relatively 5 down
$this->cursorMove('downmost',2); // move to the down position up 2
$this->cursorMove('right',10); // move relatively 5 right
$this->cursorMove('rightmost',5); // move to the rightmost position, minus 5
$this->cursorMove('left',10); // move relatively 5 left
$this->cursorMove('leftmost',5); // move to the leftmost position, minus 5
$this->cursorMove('pos',[10,10]); // move absolute to the position 10,10
```

#### Parameters:

* **$type=['up','upmost','down','downmost','right','rightmost','left','leftmost','pos'][$i]**

* **up** : it moves the cursor up "n" parameter

* **down** : it moves the cursor down "n" parameter

* **right** : it moves the cursor right "n" parameter

* **left** : it moves the cursor left "n" parameter

* **upmost** : it moves the cursor to the upper minus "n"

* **downmost** : it moves the cursor to the down minus "n"

* **rightmost** : it moves the cursor to the rightmost minus "n"

* **leftmost** : it moves the cursor to the leftmost minus "n"

* **pos** : it moves the cursor to the [x,y] parameter
(string)
* **$parameter** param mixed $parameter (mixed)

### Method bell()

### Method getCursorPosition()

It gets the current position of the cursor

> It requires getCh() executable up and configured in Windows
> **Example:**

```
$arr=$this->getCursorPosition(); // [x,y]
```

### Method showMessageBox()

It shows a message box consisting of two columns.

#### Parameters:

* **$lines** (right side) (string|string[])
* **$titles** (left side) (string|string[])
* **$wrapLines** if true, then $lines could be wrapped (if the lines are too long) (bool)

### Method alignLinesVertically()

#### Parameters:

* **$lines** The lines to align (string[])
* **$numberLines** the number of lines vertically to use to align the text. (int)
* **$align** =['middle','top','bottom'][$i] (string)

### Method maxWidth()

### Method showParamSyntax()

It shows the syntax of a parameter.

#### Parameters:

* **$key** the key to show. "*" means all keys. (string)
* **$tab** the first separation. Values are between 0 and 5. (int)
* **$tab2** the second separation. Values are between 0 and 5. (int)
* **$excludeKey** the keys to exclude. It must be an indexed array with the keys to skip. (array)

### Method showParamSyntax2()

It shows the syntax of the parameters.

#### Parameters:

* **$title** A title (optional) (?string)
* **$typeParam** =['command','first','last','second','flag','longflag','onlyinput','none'][$i] the
type of parameter (array)
* **$excludeKey** the keys to exclude (array)
* **$includeKeys** the whitelist of elements that only could be included.

Only keys that are in this list are added. (array|null)
* **$related** if not null then it only shows all the parameteres that are related.

use $param->setRelated() to set the relation. (string|null)
* **$size** the minimum size of the first column (?int)

### Method setDefaultStream()

#### Parameters:

* **$stream** =['stdout','stderr','memory'][$i] (string)

### Method setNoColor()

#### Parameters:

* **$noColor** if true then it will not show colors

if false, then it will show the colors. (bool)

### Method isNoColor()

### Method setNoANSI()

if true then the console is in old-cmd mode (no colors, no utf-8 characters, etc.)

#### Parameters:

* **$noANSI** param bool $noANSI (bool)

### Method isNoANSI()

returns true if the

### Method wrapLine()

it wraps a line and returns one or multiples lines

The lines wrapped does not open or close tags.

#### Parameters:

* **$texts** The text already formatted. (string|array)
* **$width** The expected width (int)
* **$keepStyle** if true then it keeps the initial and end style tag for every new line.

if false, then it just wraps the lines. (bool)

### Method showProgressBar()

#### Parameters:

* **$currentValue** the current value (numeric)
* **$max** the max value to fill the bar. (numeric)
* **$columnWidth** the size of the bar (in columns) (int)
* **$currentValueText** the current value to display at the left.

if null then it will show the current value (with a space in between) (?string)

### Method getPageSize()

it gets the size of the page (number of rows) to display in a table

### Method showTable()

It shows an associative array. This command is the end of a stack.

#### Parameters:

* **$assocArray** An associative array with the values to show. The key is used for the index. (array)
* **$notop** if true then it will not show the top border (bool)
* **$nosides** if true then it will not show the side borders (bool)
* **$nobottom** if true then it will not show the bottom border (bool)
* **$maxColumns** The max number of columns to show.

If the table has 15 columns and maxColumns is 5, then only the
first 5 columns will be displayed. (int)
* **$reduceRows** The number of rows to reduce considering the size of the screen.

If the screen has 30 rows, then the table will use 30-3=27 rows

If set to >-99999, then it will display all rows. (int)
* **$curpage** The number of page (base 1) to display. (int)

### Method showValuesColumn()

It shows the values as columns.

#### Parameters:

* **$values** the values to show. It could be an associative array or an indexed array. (array)
* **$type** ['multiple','multiple2','multiple3','multiple4','option','option2','option3','option4'][$i] (string)
* **$patternColumn** the pattern to be used, example: "[{key}] {value}" (?string)

### Method showWaitCursor()

It shows a waiting cursor.

**Example:**

```
$this->hideCursor()->showWaitCursor(true);
$this->showWaitCursor(); // inside a loop.
$this->hideWaitCursor()->showCursor(); // at the end of the loop
```

#### Parameters:

* **$init** the first time this method is called, you must set this value as true. Then,
every update must be false. (bool)
* **$postfixValue** if you want to set a profix value such as percentage, advance, etc. (string)

### Method hideWaitCursor()

### Method hideCursor()

### Method showCursor()

### Method showparams()

It will show all the parameters by showing the key, the default value and the value

It is used for debugging and testing.

### Method showParamValue()

#### Parameters:

* **$parameter** param CliOneParam $parameter (CliOneParam)

### Method strlen()

It determines the size of a string

#### Parameters:

* **$content** param $content ()
* **$visual** visual means that it considers the visual lenght, false means it considers characters. (bool)

### Method removechar()

remove visible characters at the end of the string. It ignores invisible (such as colors) characters.

#### Parameters:

* **$content** param string $content (string)
* **$numchar** param int $numchar (int)

### Method upLevel()

Up a level in the breadcrumb

#### Parameters:

* **$content** the content of the new line (string)
* **$type** the type of the content (optional) (string)

### Method getCh()

It reads an input character. It does not work with special characters

This function is basic, it does not work with all keystrokes, and it could be CPU intensive (for a loop)

> In Windows, it uses the getch.exe in any path folder (or you can set the path with $this->getChWinExe).

> You can download from here https://github.com/escuelainformatica/getch/releases
> **Example:**

```
$chNumber=$this->getCh(); // wait until it reads a character
while(true) {
$chNumber=$this->getCh(false); // does not wait.
usleep(50); // if you don't add a pause, it uses the CPU 100%
}
$chChar=$this->getCh(false,false); // it gets a character instead of a number
```

#### Parameters:

* **$waitUntilKeyPress** if true (default), it waits until a key is pressed (bool)
* **$asNumber** if true (default), returns the result as a two byte integer. (bool)

### Method colorText()

It sets the color of the cli

```
error (color red)
warning (color yellow)
information (blue)
yellow (yellow)
green (color green)
italic
bold
underline
strikethrough
cyan (color light cyan)
magenta (color magenta)
columns. col0=0 (left),col1--col5 every column of the page.
it shows all the options available (if the input has some options)
```

#### Parameters:

* **$content** param string $content (string)
* **$cliOneParam** param ?CliOneParam $cliOneParam (?CliOneParam)

### Method colorLess()

It removes all the escape characters of a content

#### Parameters:

* **$content** param string $content (string)

### Method colorMask()

It masks (with a char 250) all the escape characters.

#### Parameters:

* **$content** param $content ()

### Method initialEndStyle()

It returns the initial and end style of a text.

If the text only contains an initial or final style, then nothing is returned

#### Parameters:

* **$contentAnsi** the content text already formatted in Ansi (string)
* **$initial** (this value is returned) (?string)
* **$end** (this value is returned) (?string)

### Method replaceCurlyVariable()

Replaces all variables defined between {{ }} by a variable inside the dictionary of values.

**Example:**

```
replaceCurlyVariable('hello={{var}}',['var'=>'world']) // hello=world
replaceCurlyVariable('hello={{var}}',['varx'=>'world']) // hello=
replaceCurlyVariable('hello={{var}}',['varx'=>'world'],true) // hello={{var}}
```

#### Parameters:

* **$string** The input value. It could contain variables defined as {{namevar}} (string)
* **$notFoundThenKeep** [false] If true and the value is not found, then it keeps the value.
Otherwise, it is replaced by an empty value (bool)

## menu

You can create a menu using the next methods

### addMenu()
It creates a new menu

### addMenuItem()
It adds an option to a menu

### addMenuItems()
It adds multiple options to a menu

### evalMenu()
It executes a menu

### clearMenu()
It clears a menu.

### example
```php
class ClassService {
public function menuHeader(CliOne $cli) { /* todo: add header code */ }
public function menuFooter(CliOne $cli) { /* todo: add footer code */ }
public function menuOption1(CliOne $cli) { /* todo: add menu option 1 code */ }
public function menuOption2(CliOne $cli) { /* todo: add menu option 2 code */ }
}
$obj=new ClassService();

$cli = new CliOne();
$cli->addMenu('menu1', 'header','footer');
$cli->addMenuItem('menu1','option1', 'option #1'
,function($cli) {$cli->showLine('calling action1');$this->assertTrue(true, true);});
$cli->addMenuItem('menu1','option2', 'option #2');
$cli->addMenuItem('menu1','option3', 'option #3','navigate:menu1.1');
$cli->addMenuItems('menu1',['option4'=>'option #4','option5'=> 'option #5']); // adding multiples options

$cli->addMenu('menu1.1', 'header2','footer2');
$cli->addMenuItem('menu1.1','option1', 'option #1.1');
$cli->addMenuItem('menu1.1','option2', 'option #2.1');
$cli->addMenuItem('menu1.1','option3', 'option #3.1');
$cli->addMenuItem('menu1.1','option4', 'option #4.1');
$cli->addMenuItem('menu1.1','option5', 'option #5.1');
$cli->evalMenu('menu1',$obj); // runs the menu.
$cli->showLine('exit ok');
$cli->clearMenu();
```

## Examples

### Example using arguments

[example/example1.php](example/example1.php)

And create the next code

```php
// example1.php
// don't forget to add autoloader, namespace, etc.
$cli=new CliOne(); // instance of the library
if($cli->isCli()) { // we validate if we are running a CLI or not.
$cli->createParam('param1') // the name of the parameter
->setDescription('Some description','question?') // description and question
->setRequired(true) // if the field is required
->setDefault('param1') // the default value If the value is not found
->add(); // it adds a parameter to the cli
$param1=$cli->evalParam('param1'); // then we evaluate the parameter.
var_dump($param1->value);
}
```

So you can run as:

![](docs/example1.jpg)

### Example using user input

You can ask for user input of the user.

[example/example2.php](example/example2.php)

```php
$cli=new CliOne();
if($cli->isCli()) {
$cli->createParam('param1')
->setDescription('This field is called param1 and it is required')
->setInput(true,'string')
->setRequired(true)
->setDefault('param1')
->add();
$param1 = $cli->evalParam('param1');
var_dump($param1->value);
}
```

It will show the next result

![](docs/example2.jpg)

### Example with a game

[example/examplegame.php](example/examplegame.php)

![docs/guess.jpg](docs/guess.jpg)
Image (c) George Beker

![docs/examplegame.jpg](docs/examplegame.jpg)

### Example colors

You can see the tags available in [Types of colors](#types-of-colors)

[example/examplecolor.php](example/examplecolor.php)

```php
$cli->showLine("bold");
$cli->showLine("dim");
$cli->showLine("background red");
$cli->showLine("background red");
$cli->showLine("background white ");
$cli->showLine("background yellow");
$cli->showLine("error (color red)");
$cli->showLine("warning (color yellow)");
$cli->showLine("information (blue)");
$cli->showLine("yellow (yellow)");
$cli->showLine("green (color green)");
$cli->showLine("italic");
$cli->showLine("bold");
$cli->showLine("bold yellow");
$cli->showLine("stike");
$cli->showLine("underline");
$cli->showLine("cyan (color cyan)");
$cli->showLine("magenta (color magenta)");
$cli->showLine("bold cyan (color cyan)");
$cli->showLine("bold magenta (color magenta)");
$cli->showLine(" col0");
$cli->showLine(" col1");
$cli->showLine(" col2");
$cli->showLine(" col3");
$cli->showLine(" col4");
$cli->showLine(" col1 col3 col5");
$cli->showLine("The parameters of option are: ",$cli->getParameter('test'));
```

![](docs/examplecolor.jpg)

### Example tables

[example/exampletables.php](example/exampletables.php)

![docs/exampletable.jpg](docs/exampletable.jpg)

## Types of user input

| userinput | description |
|--------------|-------------------------------------------------------------------------|
| number | the value must be a number |
| range | the value must be a number between a range of values |
| string | the value must be a string (by default, nulls are not string) |
| password | the value must be a string (and if it is displayed, then it shows ****) |
| multiple | It allows to select one or many values displated in 1 column |
| multiple2 | The same than multiple but displayed in 2 columns |
| multiple3 | The same than multiple but displayed in 3 columns |
| multiple4 | The same than multiple but displayed in 4 columns |
| option | It allows to select one from many values displayed in a column |
| option2 | The same than option but displayed in 2 columns |
| option3 | The same than option but displayed in 3 columns |
| option4 | The same than option but displayed in 4 columns |
| optionsimple | It allows to select one from many values. It doesn't use columns |

## Types of colors

| tag | description |
|--------------------------------------------|-------------------------------|
| error | color red |
| warning | color yellow |
| information | blue |
| black | black |
| white | white |
| success | color green |
| italic | italic |
| bold