pflag - better PHP command line options parsing library

Keywords: PHP console

PHP toolkit / pflag is a general command line flag (options and parameters) parsing library written in PHP.

Github warehouse: php-toolkit/pflag

Function description

  • Common command line options and parameter parsers
  • Supports setting value data types (int,string,bool,array), and will automatically format the input value
  • Supports setting default values for options / parameters
  • Multiple short names can be set for one option
  • Supports reading flag values from environment variables
  • Support setting options / parameters as required
  • Supports setting up validators to check input values
  • Support automatic rendering beautiful help information.

Command line options:

  • Options begin with - or -- and the first character must be a letter
  • Long options starting with - -. eg: --long --long value
  • Short options starting with - are - s -a value
  • Support for defining array options
    • eg: --tag php --tag go will get $tag = [php, go]

Command line parameters:

  • If the options cannot be met, they will be regarded as parameters
  • Support binding named parameters
  • Support to define array parameters

install

composer installation

composer require toolkit/pflag

Flags usage

Flags - is a command line flag (options and parameters) parser and manager.

For example code, see example/flags-demo.php

Create parser

Create and initialize parser

use Toolkit\PFlag\Flags;

require dirname(__DIR__) . '/test/bootstrap.php';

$flags = $_SERVER['argv'];
// NOTICE: must shift first element.
$scriptFile = array_shift($flags);

$fs = Flags::new();

// Optionally, you can add some custom settings
$fs->setScriptFile($scriptFile);
/** @see Flags::$settings */
$fs->setSettings([
    'descNlOnOptLen' => 26
]);

// ...

Define options

Define options - define the supported option settings. When parsing, the input will be parsed according to the definitions

Example of adding an option definition:

use Toolkit\PFlag\Flag\Option;
use Toolkit\PFlag\FlagType;
use Toolkit\PFlag\Validator\EnumValidator;

// add options
// - quick add
$fs->addOpt('age', 'a', 'this is a int option', FlagType::INT);

// -Use string rules to quickly add option definitions
$fs->addOptByRule('name,n', 'string;this is a string option;true');

// --Add multiple options at once
$fs->addOptsByRules([
    'tag,t' => 'strings;array option, allow set multi times',
    'f'     => 'bool;this is an bool option',
]);

// -Use array definition
/** @see Flags::DEFINE_ITEM for array rule */
$fs->addOptByRule('name-is-very-lang', [
    'type'   => FlagType::STRING,
    'desc'   => 'option name is to lang, desc will print on newline',
    'shorts' => ['d','e','f'],
    // TIP: add validator limit input value.
    'validator' => EnumValidator::new(['one', 'two', 'three']),
]);

// -Using Option objects
$opt = Option::new('str1', "this is  string option, \ndesc has multi line, \nhaha...");
$opt->setDefault('defVal');
$fs->addOption($opt);

Define parameters

Define parameters - define the supported option settings. When parsing, the input will be parsed according to the definitions

Example of adding parameter definitions:

use Toolkit\PFlag\Flag\Argument;
use Toolkit\PFlag\FlagType;

// add arguments
// - quick add
$fs->addArg('strArg1', 'the is string arg and is required', 'string', true);

// -Use string rules to quickly add definitions
$fs->addArgByRule('intArg2', 'int;this is a int arg and with default value;no;89');

// -Using the Argument object
$arg = Argument::new('arrArg');
// OR $arg->setType(FlagType::ARRAY);
$arg->setType(FlagType::STRINGS);
$arg->setDesc("this is an array arg,\n allow multi value,\n must define at last");

$fs->addArgument($arg);

Parsing command line input

Finally, call parse() to parse the command line to input data.

// ...

if (!$fs->parse($flags)) {
    // on render help
    return;
}

vdump($fs->getOpts(), $fs->getArgs());

Show help

When you enter - h or -- help, help information is automatically rendered.

$ php example/flags-demo.php --help

Output:

Running example:

$ php example/flags-demo.php --name inhere --age 99 --tag go -t php -t java -d one -f arg0 80 arr0 arr1

Output results:

# Option data
array(6) {
  ["str1"]=> string(6) "defVal"
  ["name"]=> string(6) "inhere"
  ["age"]=> int(99)
  ["tag"]=> array(3) {
    [0]=> string(2) "go"
    [1]=> string(3) "php"
    [2]=> string(4) "java"
  }
  ["name-is-very-lang"]=> string(3) "one"
  ["f"]=> bool(true)
}

# Parameter data 
array(3) {
  [0]=> string(4) "arg0"
  [1]=> int(80)
  [2]=> array(2) {
    [0]=> string(4) "arr0"
    [1]=> string(4) "arr1"
  }
}

Get input value

Getting the flag value is very simple. You can use the method getOpt(string $name) getArg($nameOrIndex)

TIP: the input value will be automatically formatted by the defined data type

Option data

$force = $fs->getOpt('f'); // bool(true)
$age  = $fs->getOpt('age'); // int(99)
$name = $fs->getOpt('name'); // string(inhere)
$tags = $fs->getOpt('tags'); // array{"php", "go", "java"}

Parameter data

$arg0 = $fs->getArg(0); // string(arg0)
// get an array arg
$arrArg = $fs->getArg(1); // array{"arr0", "arr1"}
// get value by name
$arrArg = $fs->getArg('arrArg'); // array{"arr0", "arr1"}

Extensions: rule definitions

Option parameter rule. Use rules to quickly define an option or parameter.

  • String the string rule is semicolon; Split each part (complete rule: type;desc;required;default;shorts)
  • array rules are defined by SFlags::DEFINE_ITEM setting definition
  • For supported type constants, see FlagType:*
use Toolkit\PFlag\FlagType;

$rules = [
     // v: Only values are used as names and the default type is FlagType::STRING
     // k-v: the key is the name, and the value can be a string | array
     'long,s',
     // name => rule
     'long,a,b' => 'int;an int option', // long is option name, a and b is shorts.
     'f'      => FlagType::BOOL,
     'str1'   => ['type' => 'int', 'desc' => 'an string option'],
     'tags'   => 'array; an array option', // can also: ints, strings
     'name'   => 'type;the description message;required;default', // with desc, default, required
]

For options

  • Option allows you to set short names

TIP: for example, long,a,b - long is the option name. The remaining a,b are its short option names

For parameters

  • Parameter has no alias or short name
  • Array parameters are only allowed to be defined at the end

Array definition item

Constant Flags::DEFINE_ITEM:

public const DEFINE_ITEM = [
    'name'      => '',
    'desc'      => '',
    'type'      => FlagType::STRING,
    'helpType'  => '', // use for render help
    // 'index'    => 0, // only for argument
    'required'  => false,
    'default'   => null,
    'shorts'    => [], // only for option
    // value validator
    'validator' => null,
    // 'category' => null
];

Custom settings

Parsing settings

    // --------------------Options resolution settings--------------------

    /**
     * Stop parse option on found first argument.
     *
     * - Useful for support multi commands. eg: `top --opt ... sub --opt ...`
     *
     * @var bool
     */
    protected $stopOnFistArg = true;

    /**
     * Skip on found undefined option.
     *
     * - FALSE will throw FlagException error.
     * - TRUE  will skip it and collect as raw arg, then continue parse next.
     *
     * @var bool
     */
    protected $skipOnUndefined = false;

    // --------------------Parameter resolution settings--------------------

    /**
     * Whether auto bind remaining args after option parsed
     *
     * @var bool
     */
    protected $autoBindArgs = true;

    /**
     * Strict match args number.
     * if exist unbind args, will throw FlagException
     *
     * @var bool
     */
    protected $strictMatchArgs = false;

Render help settings

support some settings for render help

    // -------------------- settings for built-in render help --------------------

    /**
     * Auto render help information when you enter the '- h', '--help' option
     *
     * @var bool
     */
    protected $autoRenderHelp = true;

    /**
     * Displays the data type on the rendered help information
     *
     * if False:
     *
     * -o, --opt    Option desc
     *
     * if True:
     *
     * -o, --opt STRING   Option desc
     *
     * @var bool
     */
    protected $showTypeOnHelp = true;

    /**
     * It will be called before printing the help message.
     *
     * @var callable
     */
    private $beforePrintHelp;

Custom help message rendering:

$fs->setHelpRenderer(function (\Toolkit\PFlag\FlagsParser $fs) {
    // render help messages
});

unit testing

phpunit --debug

test with coverage:

phpdbg -qrr $(which phpunit) --coverage-text

Projects using pflag

Check out these projects, which use github.com/php-toolkit/pflag :

Github warehouse: php-toolkit/pflag

Posted by BenMo on Sun, 10 Oct 2021 03:45:57 -0700