Aura.Cli
Aura.Cli
Provides the equivalent of request ( Context ) and response ( Stdio )
objects for the command line interface, including Getopt support, and an
independent Help object for describing commands.
Foreword
Installation
This library requires PHP 7.2 or later; we recommend using the latest available version of PHP as a matter of principle. If you are interested in using this package for older PHP versions, use version 2.x for PHP 5.3+.
It has no userland dependencies.
It is installable and autoloadable via Composer as aura/cli.
Alternatively, download a release or clone this repository, then require or include its autoload.php file.
Quality
To run the unit tests at the command line, issue composer install
and then composer test
at the package root. This requires Composer to be available as composer
.
This library attempts to comply with PSR-1, PSR-2, and PSR-4. If
you notice compliance oversights, please send a patch via pull request.
Community
To ask questions, provide feedback, or otherwise communicate with the Aura community, please join our Google Group, follow @auraphp on Twitter, or chat with us on #auraphp on Freenode.
Getting Started
Context Discovery
The Context object provides information about the command line environment,
including any option flags passed via the command line. (This is the command
line equivalent of a web request object.)
Instantiate a Context object using the CliFactory; pass it a copy of
$GLOBALS
.
<?php use AuraCliCliFactory; $cli_factory = new CliFactory; $context = $cli_factory->newContext($GLOBALS); ?>
You can access the $_ENV
, $_SERVER
, and $argv
values with the $env
,
$server
, and $argv
property objects, respectively. (Note that these
properties are copies of those superglobals as they were at the time of
Context instantiation.) You can pass an alternative default value if the
related key is missing.
<?php // get copies of superglobals $env = $context->env->get(); $server = $context->server->get(); $argv = $context->argv->get(); // equivalent to: // $value = isset($_ENV['key']) ? $_ENV['key'] : null; $value = $context->env->get('key'); // equivalent to: // $value = isset($_ENV['key']) ? $_ENV['key'] : 'other_value'; $value = $context->env->get('key', 'other_value'); ?>
Getopt Support
The Context object provides support for retrieving command-line options and
params, along with positional arguments.
To retrieve options and arguments parsed from the command-line $argv
values,
use the getopt()
method on the Context object. This will return a
GetoptValues object for you to use as as you wish.
Defining Options and Params
To tell getopt()
how to recognize command line options, pass an array of
option definitions. The definitions array format is similar to, but not
exactly the same as, the one used by the getopt()
function in PHP. Instead of defining short flags in a string and long options
in a separate array, they are both defined as elements in a single array.
Adding a *
after the option name indicates it can be passed multiple times;
its values will be stored in an array.
<?php $options = array( 'a', // short flag -a, parameter is not allowed 'b:', // short flag -b, parameter is required 'c::', // short flag -c, parameter is optional 'foo', // long option --foo, parameter is not allowed 'bar:', // long option --bar, parameter is required 'baz::', // long option --baz, parameter is optional 'g*::', // short flag -g, parameter is optional, multi-pass ); $getopt = $context->getopt($options); ?>
N.b.: When we say “required” here, it means “the option, when present,
must have a parameter.” It does not mean “the option must be present.”
These are options, after all. If a particular value must be passed,
consider using positional arguments instead.
Use the get()
method on the returned GetoptValues object to retrieve the
option values. You can provide an alternative default value for when the
option is missing.
<?php $a = $getopt->get('-a', false); // true if -a was passed, false if not $b = $getopt->get('-b'); $c = $getopt->get('-c', 'default value'); $foo = $getopt->get('--foo', 0); // true if --foo was passed, false if not $bar = $getopt->get('--bar'); $baz = $getopt->get('--baz', 'default value'); $g = $getopt->get('-g', []); ?>
If you want to alias one option name to another, comma-separate the two names.
The values will be stored under both names;
<?php // alias -f to --foo $options = array( 'foo,f:', // long option --foo or short flag -f, parameter required ); $getopt = $context->getopt($options); $foo = $getopt->get('--foo'); // both -f and --foo have the same values $f = $getopt->get('-f'); // both -f and --foo have the same values ?>
If you want to allow an option to be passed multiple times, add a ‘*’ to the end
of the option name.
<?php $options = array( 'f*', 'foo*:' ); $getopt = $context->getopt($options); // if the script was invoked with: // php script.php --foo=foo --foo=bar --foo=baz -f -f -f $foo = $getopt->get('--foo'); // ['foo', 'bar', 'baz'] $f = $getopt->get('-f'); // [true, true, true] ?>
If the user passes options that do not conform to the definitions, the
GetoptValues object retains various errors related to the parsing
failures. In these cases, hasErrors()
will return true
, and you can then
review the errors. (The errors are actually AuraCliException
objects,
but they don’t get thrown as they occur; this is so that you can deal with or
ignore the different kinds of errors as you like.)
<?php $getopt = $context->getopt($options); if ($getopt->hasErrors()) { $errors = $getopt->getErrors(); foreach ($errors as $error) { // print error messages to stderr using a Stdio object $stdio->errln($error->getMessage()); } }; ?>
Positional Arguments
To get the positional arguments passed to the command line, use the get()
method and the argument position number:
<?php $getopt = $context->getopt($options); // if the script was invoked with: // php script.php arg1 arg2 arg3 arg4 $val0 = $getopt->get(0); // script.php $val1 = $getopt->get(1); // arg1 $val2 = $getopt->get(2); // arg2 $val3 = $getopt->get(3); // arg3 $val4 = $getopt->get(4); // arg4 ?>
Defined options will be removed from the arguments automatically.
<?php $options = array( 'a', 'foo:', ); $getopt = $context->getopt($options); // if the script was invoked with: // php script.php arg1 --foo=bar -a arg2 $arg0 = $getopt->get(0); // script.php $arg1 = $getopt->get(1); // arg1 $arg2 = $getopt->get(2); // arg2 $foo = $getopt->get('--foo'); // bar $a = $getopt->get('-a'); // 1 ?>
N.b.: If a short flag has an optional parameter, the argument immediately
after it will be treated as the option value, not as an argument.
Standard Input/Output Streams
The Stdio object allows you to work with standard input/output streams.
(This is the command line equivalent of a web response object.)
Instantiate a Stdio object using the CliFactory.
<?php use AuraCliCliFactory; $cli_factory = new CliFactory; $stdio = $cli_factory->newStdio(); ?>
It defaults to using php://stdin
, php://stdout
, and php://stderr
, but
you can pass whatever stream names you like as parameters to the newStdio()
method.
The Stdio object methods are …
-
getStdin()
,getStdout()
, andgetStderr()
to return the respective
Handle objects; -
outln()
andout()
to print to stdout, with or without a line ending; -
errln()
anderr()
to print to stderr, with or without a line ending; -
inln()
andin()
to read from stdin until the user hits enter;inln()
leaves the trailing line ending in place, whereasin()
strips it.
You can use special formatting markup in the output and error strings to set
text color, text weight, background color, and other display characteristics.
See the formatter cheat sheet below.
<?php // print to stdout $stdio->outln('This is normal text.'); // print to stderr $stdio->errln('<<red>>This is an error in...