PHPackages                             evo/cli - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. evo/cli

ActiveLibrary[CLI &amp; Console](/categories/cli)

evo/cli
=======

Command line interface

2.3.0(1y ago)337GPL-3.0PHPPHP &gt;=8.3

Since Oct 30Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ArtisticPhoenix/Cli)[ Packagist](https://packagist.org/packages/evo/cli)[ RSS](/packages/evo-cli/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (8)Dependencies (2)Versions (10)Used By (0)

Command line interface options parser

The purpose of this library is to make a more user friendly way of setting command line arguments for programs.

It's fairly strait forward so I'll jump right in with an example (will call it 'program'):

```
    //command line call (typically for the help doc)
    > php {pathto}example.php -h

    > php {pathto}example.php -o
```

This is the form of a typical command line call, here we are assuming only that PHP is executable on calling `php`. For windows users you may have to add the `php.exe` to the system environmental variables to call PHP this way. It's not hard to do and there are plenty of tutorials on how to do this for your version of windows. Otherwise you can always call PHP using the full path to the executable on your setup.

### Class refrence

[](#class-refrence)

```
	//get an instance of Cli, this is a singleton class
	public static function getInstance(): self;
	//set arguments with a config array
	public function fromConfig(array $conf): self;
	//set an argument to accept
	public function setArgument(string $shortName, ?string $longName=null, string $doc='', array $options=[]): self;
	//(changed in 2.0) get a list of the argument set with setArgument
	public function getArguments() : array;
	//(added in 2.0) get a single argument set
	public function getArgument(string $which): array;
	//(added in 2.0) convert an arguments name to the short version ( safe for leading hypen and short names)
	public function toShortName(string $long_name): string|false;
	//(added in 2.0) convert an arguments name to the long version ( safe for leading hypens and long names)
	public function toLongName(string $short_name): string|false;
	//set the allowed request types (for overriding)
	public function setAllowedRequestTypes(int $requestType): self;
	//set the current request types (for overriding auto detection)
	public function setCurrentRequestType(int $requestType): self;
	//get the current request type (as of version 1.0.2)
	public function getCurrentRequestType(): int;
	//set a request (for overriding)
	public function setRequest(array $request): self;
	//(added in 2.0) get the value of an argument from the request or null to get the request as an array
	public function getRequest(?string $which=null, mixed $default=null): mixed;
	//(added in 2.2) Use this callback method as the default to throw an evo\OutOfBoundsException for an unknown request key
	public static function throwUnknownRequestKey(): callable
	//(added in 2.0) is an argument set in the request or is the request itself set
	public function issetRequest(?string $which=null): bool
	//(added in 2.1) is an argument empty in the request or is the request itself empty
	public function isEmptyRequest(?string $which=null): bool
	//get a list of the allowed options (see options)
	public function getOptions(): array;
	//get the argument help doc as text
	public function getHelpDoc(): string;
	//output the argement help doc
	public function printHelpDoc(bool $exit=true): void;
	//(added in 2.2) Stream output instead of buffering it over HTTP
	public static function streamOutput(): void
```

### Cli Class Constants

[](#cli-class-constants)

NameTypeSinceDescriptionVERSIONstring2.0.0the current versionOPT\_VALUE\_EXPECTEDstring2.0.0**Option:** see Value ExpectedOPT\_MUST\_VALIDATEstring2.0.0**Option:** see Must ValidateOPT\_MULTIPLE\_EXPECTEDstring2.0.0**Option:** see Multiple ExpectedR\_ALLint1.0.0**Bitwise Flag** (composite of all bitwise other flags)REQUEST\_CLIint1.0.0**Bitwise Flag** Command line requestREQUEST\_POSTint1.0.0**Bitwise Flag** HTTP Post requestREQUEST\_GETint1.0.0**Bitwise Flag** HTTP Get requestREQUEST\_PUTint1.0.0**Bitwise Flag** HTTP Put/Post requestREQUEST\_DELETEint1.0.0**Bitwise Flag** HTTP Delete/Post request### General Argument Definitions

[](#general-argument-definitions)

NameTypeSinceDescription$confarray1.0.0An array of arguments to set (see below)$shortNamestring1.0.0An arguments short name max length of 1, a-z A-Z or 0-9$longNamestring1.0.0The long name for an argument or null, min length of 1, a-z A-Z or 0-9$whichstring1.0.0Argument's shortName or longName, get an arguments value from request, null for get all$defaultmixed1.0.0Default value to return when no value is set in the request ( can be a closure since 2.0.0 )$optionsarray1.0.0An array of options for the argument (see below)$requestTypeint1.0.0One of the Cli::REQUEST\_ constants or Cli::R\_ALL (bitwise)$requestarray1.0.0The request (typically auto detected)### Options (changed in 2.0.0)

[](#options-changed-in-200)

NameTypeSinceDescriptionOPT\_VALUE\_EXPECTEDbool2.0.0A value is expexed for this argument, if this is -a (false) otherwise -a (true)OPT\_MUST\_VALIDATEmixed2.0.0If this argument is present then it's value must meet this conditionOPT\_MULTIPLE\_EXPECTEDmixed2.0.0Multiple argements are exected, this argment value will always be an array when returned#### OPT\_VALUE\_EXPECTED

[](#opt_value_expected)

When this option is true a value is expected for this argument:

- If *true* and the argument is set without a value `prog.exe -a` then it is value "false", please note this is the opposite of below
- If *true* and the argument is set with a value `prog.exe -a=1` then it's value is set
- If *false* and the argument is set without a value `prog.exe -a` then it is value "true"
- If *false* and the argument is set with a value `prog.exe -a=1` then it is still "true" but the value is not given

#### OPT\_MUST\_VALIDATE

[](#opt_must_validate)

This option can be either a boolean value or a Closure (or any class that impliments the Callable interface):

- If it's set to *true*, the argement will always validate if it's in the request
- If it's set to *false*, the argement will never validate if it's in the request
- If it's set to a callback, then it's the callback's responsibillity to return true or false

#### OPT\_MULTIPLE\_EXPECTED

[](#opt_multiple_expected)

This option deturmines if an argument can have multiple values `prog.exe -a=1 -a=2 -a=3`

- If it's set to *true*, the argements value will always be represented by an array
- If it's set to *false*, the argements value never be represented by an array and only the last value is set

### Basic Usage

[](#basic-usage)

Usage is pretty simple, there are 3 main methods you will need and few others that are just nice to have.

```
	//instanciate
	$Cli = Cli::getInstance();
```

Cli is a "Singlton" which means you can only ever have one instance of the class. Calling getInstance again will return the same instance. This is fine because we can only handle one request at any give time. The main function you will use is `$Cli->setArgument` (or `$Cli->fromConfig()`) which defines what arguments you will accept from the request.

```
	//instanciate
	$Cli = Cli::getInstance();

	//setup a basic argument  (called -h or --help)
	$Cli->setArgument('h', 'help', 'Show this help document');
```

Above we are setting up a very basic argument to show the argument help document.

The first argument is shortName, `h` in this case, this is mainly what you use when referring to this argument. All incoming request data will be "normalized" to use the short name. Any items in the request that do not have a corresponding argument are simply ignored. In a command line call it will be referred to as `-h`, for a GET or POST request it will be referred to simply as `h`.

The second argument is the longName, `help` in this case. Any incoming arguments using the optional longName will be converted to their short name equivalent. In a command line call it will be referred to as `--help`, for a GET or POST request it will be referred to simply as `help`.

The third argument is the Help Doc. This string will be compiled with all the other arguments and retuned from `getHelpDoc` or output from `printHelpDoc`. It may also be appended to `InvalidArgument` exceptions thrown by the libary.

```
	//instanciate
	$Cli = Cli::getInstance();
	//setup a basic argument  (called -h or --help)
	$Cli->setArgument('h', 'help', 'Show this help document');
	//setup an argument that only accepts foo as the input
	$Cli->setArgument('f', 'foo', 'This is just foo, and must always be foo', [
		'accept' => function($shortName, $value){
			if($value == 'foo') return true;
			return false;
		}
	]);

	$Cli->setArgument('i', 'input', 'This is input that requires a value', [
		'requireValue' => true
	]);
```

The fourth argument is an array of options, currently only 2 options are supported

- 'accept' This is a callback that takes the `$shortName` and the \[request\]`$value` as inputs and should return true to accept the value. If false is returned the argument is removed from the request input. It is up to the developer to throw exceptions for invalid inputs. This can be easly done in the callback. The `$value` can be modified by reference by adding `&$value` (by reference).
- 'requiredValue' This is a boolen that makes a value required for the argument. If the value is not included with the argument then an `evo\exception\InvalidArgument` is thrown. This does not mean that the argument itself is required only that if the argument is present that an acceptable value is also included.

```
	//instanciate
	$Cli = Cli::getInstance();
	$Cli->fromConfig([
		[
			'shortName' => 'h',
			'longName' => 'help',
			'doc' => 'Show this help document'
		],[
			'shortName' => 'f',
			'longName' => 'foo',
			'doc' => 'This is just foo, and must always be foo',
			'options' => [
				$Cli::OPT_MUST_VALIDATE  => function($shortName, $value){
					if($value == 'foo') return true;
					return false;
				}
			]
		],[
			'shortName' => 'i',
			'longName' => 'input',
			'doc' => 'This is input that requires a value',
			$Cli::OPT_VALUE_EXPECTED ' => [
				'requireValue' => true
			]
		]
	]);
```

This is equivalent to the previous code block where each argument was provided individually. It is up to the developer to decide how this is saved. There are some limitation due to using a closure as the 'accept' option. However this could be saved in a PHP file as an array:

```
