Generic PHP command line flags parse library

Last update: Mar 2, 2022

PHP Flag

License GitHub tag (latest SemVer) Actions Status Php Version Support Latest Stable Version

Generic PHP command line flags parse library

Features

  • Generic CLI options and arguments parser.
  • Support set value data type(int,string,bool,array), will auto format input value.
  • Support set default value for option/argument.
  • Support read flag value from ENV var.
  • Support set option/argument is required.
  • Support set validator for check input value.
  • Support auto generate help message.

Arguments:

  • Support binding named arguemnt
  • Support define array argument

Options:

  • Support long option. eg: --long --long value
  • Support short option -s -a value, allow set multi short names.
  • Support define array option
    • eg: --tag php --tag go will get tag: [php, go]

Install

composer

composer require toolkit/pflag

Flags Usage

Flags - is an cli flags(options&argument) parser and manager.

example codes please see example/flags-demo.php

Create Flags

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();
// can with some config
$fs->setScriptFile($scriptFile);
/** @see Flags::$settings */
$fs->setSettings([
    'descNlOnOptLen' => 26
]);

// ...

Define options

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 rule
$fs->addOptByRule('name,n', 'string;this is a string option;true');

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

// - use array rule
/** @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']),
]);

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

Define Arguments

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 rule
$fs->addArgByRule('intArg2', 'int;this is a int arg and with default value;no;89');

// - use 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);

Parse Input

use Toolkit\PFlag\Flags;
use Toolkit\PFlag\FlagType;

// ...

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

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

Show help

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

Output:

flags-demo

Run demo:

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

Output:

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)
}
array(3) {
  [0]=> string(4) "arg0"
  [1]=> int(80)
  [2]=> array(2) {
    [0]=> string(4) "arr0"
    [1]=> string(4) "arr1"
  }
}

SFlags Usage

SFlags - is an simple flags(options&argument) parser and manager.

Examples

use Toolkit\PFlag\SFlags;

$flags = ['--name', 'inhere', '--age', '99', '--tag', 'php', '-t', 'go', '--tag', 'java', '-f', 'arg0'];

$optRules = [
    'name', // string
    'age'   => 'int;an int option;required', // set required
    'tag,t' => FlagType::ARRAY,
    'f'     => FlagType::BOOL,
];
$argRules = [
    // some argument rules
];

$fs->setOptRules($optRules);
$fs->setArgRules($argRules);
$fs->parse($rawFlags);
// or use
// $fs->parseDefined($flags, $optRules, $argRules);

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

Output:

array(3) {
  ["name"]=> string(6) "inhere"
  ["tag"]=> array(3) {
    [0]=> string(3) "php"
    [1]=> string(2) "go"
    [2]=> string(4) "java"
  }
  ["f"]=> bool(true)
}
array(1) {
  [0]=> string(4) "arg0"
}

Parse CLI Input

write the codes to an php file(see example/sflags-demo.php)

use Toolkit\PFlag\SFlags;

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

$optRules = [
    // some option rules
    'name', // string
    'age'   => 'int;an int option;required', // set required
    'tag,t' => FlagType::ARRAY,
    'f'     => FlagType::BOOL,
];
$argRules = [
    // some argument rules
    'string',
    // set name
    'arrArg' => 'array',
];

$fs = SFlags::new();
$fs->parseDefined($rawFlags, $optRules, $argRules);

Run demo:

php example/sflags-demo.php --name inhere --age 99 --tag go -t php -t java -f arg0 arr0 arr1

Output:

array(4) {
  ["name"]=> string(6) "inhere"
  ["age"]=> int(99)
  ["tag"]=> array(3) {
    [0]=> string(2) "go"
    [1]=> string(3) "php"
    [2]=> string(4) "java"
  }
  ["f"]=> bool(true)
}
array(2) {
  [0]=> string(4) "arg0"
  [1]=> array(2) {
    [0]=> string(4) "arr0"
    [1]=> string(4) "arr1"
  }
}

Show help

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

Get Value

Options

$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"}

Arguments

$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"}

Flag Rule

The options/arguments rules

  • string value is rule(type;desc;required;default;shorts).
  • array is define item SFlags::DEFINE_ITEM
  • supportted type see FlagType::*
$rules = [
     // v: only value, as name and use default type FlagType::STRING
     // k-v: key is name, value can be string|array
     'long,s',
     // name => rule
     'long,s' => 'int',
     'f'      => 'bool',
     'long'   => FlagType::STRING,
     'tags'   => 'array', // can also: ints, strings
     'name'   => 'type;the description message;required;default', // with desc, default, required
]

For options

  • option allow set shorts

TIP: name long,s - first is the option name. remaining is short names.

For arguments

  • arguemnt no alias/shorts
  • array value only allow defined last

Definition item

The const 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
];

Costom settings

Settings for parse

    // -------------------- settings for parse option --------------------

    /**
     * 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;

    // -------------------- settings for parse argument --------------------

    /**
     * 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;

Setting for render help

support some settings for render help

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

    /**
     * Auto render help on provide '-h', '--help'
     *
     * @var bool
     */
    protected $autoRenderHelp = true;

    /**
     * Show flag data type on render help.
     *
     * if False:
     *
     * -o, --opt    Option desc
     *
     * if True:
     *
     * -o, --opt STRING   Option desc
     *
     * @var bool
     */
    protected $showTypeOnHelp = true;

    /**
     * Will call it on before print help message
     *
     * @var callable
     */
    private $beforePrintHelp;
  • custom help message renderer
$fs->setHelpRenderer(function (\Toolkit\PFlag\FlagsParser $fs) {
    // render help messages
});

Unit tests

phpunit --debug

test with coverage:

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

Project use

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

  • inhere/console Full-featured php command line application library.
  • kite Kite is a tool for help development.
  • More, please see Packagist

License

MIT

GitHub

https://github.com/php-toolkit/pflag
You might also like...

A simple command-line tool whose aim is to facilitate the continous delivery of PHP apps

A simple command-line tool whose aim is to facilitate the continous delivery of PHP apps

Deployer Simple command-line tool that aims to facilitate the continous delivery of PHP apps, particularly Laravel apps. Imagine you want to update yo

Sep 8, 2021

🍃 In short, it's like Tailwind CSS, but for the PHP command-line applications.

🍃 In short, it's like Tailwind CSS, but for the PHP command-line applications.

Termwind Termwind allows you to build unique and beautiful PHP command-line applications, using the Tailwind CSS API. In short, it's like Tailwind CSS

May 27, 2022

A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies.

Front End Compiler A PHP Command Line tool that makes it easy to compile, concat, and minify front-end Javascript and CSS/SCSS dependencies. The minif

Nov 12, 2021

php command line script to DCA crypto from Coinbase Pro

dca.php A simple php script designed to be run via the command line via a cron job. This will connect to coinbase pro and buy the crypto coins specifi

Oct 22, 2021

Command-Line Interface tools

Aura.Cli Provides the equivalent of request ( Context ) and response ( Stdio ) objects for the command line interface, including Getopt support, and a

May 6, 2022

Another Command Line Argument Parser

Optparse — Another Command Line Argument Parser Install 1. Get composer. 2. Put this into your local composer.json: { "require": { "chh/optparse

Nov 1, 2019

👨🏻‍🚀 A command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀

👨🏻‍🚀 A command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀

Alpine Day Schedule a command-line tool that gives you the Alpine Day 2021 schedule in your timezone. 🚀 Quick start Requires PHP 7.4+ # First, instal

Jun 10, 2021

A command line code generator for Drupal.

Drupal Code Generator A command line code generator for Drupal. Installation Download the latest stable release of the code generator.

May 20, 2022

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone.

Laracon Schedule a command-line tool that gives you the Laracon Online schedule in your timezone. 🚀 Quick start Requires PHP 7.4+ # First, install: c

Dec 13, 2021
Comments
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 5.4 and above. Releases For an overview of the releas

May 24, 2022
A PHP library for command-line argument processing

GetOpt.PHP GetOpt.PHP is a library for command-line argument processing. It supports PHP version 7.1 and above. Releases For an overview of the releas

May 20, 2022
BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.
BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

BetterWPCLI - a small, zero-dependencies, PHP library that helps you build enterprise WordPress command-line applications.

May 3, 2022
PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal.
PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal.

PHP Interminal is a command-line tool that gives you access to PHP Internals discussions in your terminal. ??

Dec 12, 2021
Lovely PHP wrapper for using the command-line

ShellWrap What is it? It's a beautiful way to use powerful Linux/Unix tools in PHP. Easily and logically pipe commands together, capture errors as PHP

May 3, 2022
Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check.
Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check.

Patrol is an elegant command-line tool that keeps your PHP Project's dependencies in check. Installation / Usage Requires PHP 8.0+ First, install Patr

May 6, 2022
Twitter raffles in the command line, with PHP and minicli
Twitter raffles in the command line, with PHP and minicli

Rafflebird Rafflebird is a highly experimental CLI application for giveaways / raffles on Twitter, built in PHP with Minicli. Disclaimer: The recent s

May 14, 2022
A PHP command line tool used to install shlink
A PHP command line tool used to install shlink

Shlink installer A PHP command line tool used to install shlink. Installation Install this tool using composer.

Jan 10, 2022
Command-line control panel for Nginx Server to manage WordPress sites running on Nginx, PHP, MySQL, and Let's Encrypt
Command-line control panel for Nginx Server to manage WordPress sites running on Nginx, PHP, MySQL, and Let's Encrypt

EasyEngine v4 EasyEngine makes it greatly easy to manage nginx, a fast web-server software that consumes little memory when handling increasing volume

May 22, 2022