Generic PHP command line flags parse library

Overview

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

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

🍃 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

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

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

Pheature flags main repository
Pheature flags main repository

Pheature Flags Hi there! Welcome to our project 👋 We are a group of online business professionals who want to learn, grow and enjoy making our jobs a

Laravel Feature Flags allows instant, zero-deployment toggling of application features.

Dynamic Feature Flags for Laravel Laravel Feature Flags allows instant, zero-deployment toggling of application features. The state of each feature fl

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

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

👨🏻‍🚀 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

Comments
Releases(v2.0.6)
  • v2.0.6(Nov 5, 2022)

    Change Log

    Update

    • up: update flags parse option logic https://github.com/php-toolkit/pflag/commit/1636bce3583d0ea3e5896ff9699d5424b37bdd06

    Other

    • chore: update release action codes https://github.com/php-toolkit/pflag/commit/6619dc82da0bd9a1253fb53af4338759fe170ae8
    Source code(tar.gz)
    Source code(zip)
  • v2.0.5(Jul 19, 2022)

    Change Log

    Fixed

    • fix: validator tips not display on render help https://github.com/php-toolkit/pflag/commit/b83477f5306bbac0f34dabe3dcb1d9e4dbcbcd09
    • fix: short option check and sort options map https://github.com/php-toolkit/pflag/commit/62bb1f2ed9be200b73376995e4519bea98eeb9f0

    Update

    • up: update some for string to bool value https://github.com/php-toolkit/pflag/commit/190cf6f5190eb9177acb37d705b8e3de401eb026
    • up: update the cmd, flags help render logic https://github.com/php-toolkit/pflag/commit/315aac66402054afc26626bd9edd39490ef654d1
    • up: use the gookit/gitw chlog for generate changelog https://github.com/php-toolkit/pflag/commit/6628805d55af3516725d6bcac60d362aa264ebfe

    Other

    • chore(deps): bump actions/checkout from 2 to 3 https://github.com/php-toolkit/pflag/commit/d44eaf4a5c3cf6e002eaab5a060ff565fec97153
    • chore(deps): bump actions/cache from 2 to 3 https://github.com/php-toolkit/pflag/commit/c275b6bca878e3df96a7d0c949604b7418b1d752
    • chore: update some preview images and update readme docs https://github.com/php-toolkit/pflag/commit/2772c349848c434d27b37f55231cbad0f8a638cd
    Source code(tar.gz)
    Source code(zip)
  • v2.0.4(Jan 25, 2022)

    Change Log

    • fix: next is option value check error https://github.com/php-toolkit/pflag/commit/df8d27b8c9e79e087309900a7f6ce13f2463625e
    • fix: collect array argument error https://github.com/php-toolkit/pflag/commit/624654121e6b41c8427974b2aba9a53d2d09db6c
    Source code(tar.gz)
    Source code(zip)
  • v2.0.3(Jan 19, 2022)

    Change Log

    Update

    • up: support more custom setting for add arg flag https://github.com/php-toolkit/pflag/commit/96b4050b12b21f86fc60b1c758e3b9218f85ab38

    Fixed

    • fix: the remian args collect error https://github.com/php-toolkit/pflag/commit/682212337b20a00fb02cb93d0ec48c1604465749
    Source code(tar.gz)
    Source code(zip)
  • v2.0.2(Jan 2, 2022)

    Change Log

    Fixed

    • fix: remian args is not string list https://github.com/php-toolkit/pflag/commit/8e364507629571f90aad720a5874d8a978d0bc39

    Other

    • chore: run php-cs-fixer for the ./ https://github.com/php-toolkit/pflag/commit/24d17d59af251c843605174619be59a63c45c448
    Source code(tar.gz)
    Source code(zip)
  • v2.0.1(Dec 14, 2021)

    Change Log

    • up: optimize CliApp code https://github.com/php-toolkit/pflag/commit/b1099efec608aacf495e1501c2e7b454d398e020
    • update: add new methods for cli cmd,app https://github.com/php-toolkit/pflag/commit/7a99f46dcdda596ab15f0a6eb071557d348b3d4d
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Dec 9, 2021)

    Change Log

    Update

    • upgrade: only tests on php 8.0+ https://github.com/php-toolkit/pflag/commit/c3ecac78feea5a72c2edf62473739a806818741a
    • update: migrate code syntax to php 8.0+ https://github.com/php-toolkit/pflag/commit/1b407de1644268476af7ec32ee390b361600a3cb

    Fixed

    • fix: unit tests error https://github.com/php-toolkit/pflag/commit/9bf54aca9e99e67811846f9a19d2467f9e9f1470

    Feature

    • feat: support add CmdHandler class to CliApp https://github.com/php-toolkit/pflag/commit/f085b1678cc7959d186f36ce765b8dcd64d5ddee
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Dec 5, 2021)

    Change Log

    Fixed

    • fix: flag type check error https://github.com/php-toolkit/pflag/commit/2ad6fd54ae0b8489ec40e6710dce24697a72bf18
    • fix: syntax error on php 7.4 https://github.com/php-toolkit/pflag/commit/00be0779add16a21c58ec536d06f19692c52738c
    • fix: syntax error on < php 7.4 https://github.com/php-toolkit/pflag/commit/1fcb150eeb0da41450c13a2467381360f836465c

    Feature

    • feat: add built in simple app and cmd builder https://github.com/php-toolkit/pflag/commit/36903c172ab1d51fab9266975e3b6e0e8348c364

    Update

    • update: add an util methods, update readme https://github.com/php-toolkit/pflag/commit/6bf883c668502d03c6dc0ebd02dfcd1c94c0c49e

    Other

    • prof: add some helper methods from cli-utils https://github.com/php-toolkit/pflag/commit/32270514c85c7291c7d0fb0f1adc944d2face250
    • style: update readme, remove some unused codes https://github.com/php-toolkit/pflag/commit/2987de90c785e42010a0077508c4eabebc3f405f
    • chore: add some tests for CliApp https://github.com/php-toolkit/pflag/commit/65c727c97b4482e25fceab8186a84d57c94f9e0a
    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Nov 26, 2021)

    Change Log

    Update

    • up: use php 8.0 for gen tag release https://github.com/php-toolkit/pflag/commit/d733ce40fc21f046e7ab5aa7bd05609497321b94

    Fixed

    • fix unit test error https://github.com/php-toolkit/pflag/commit/5a746ff2112e55cfad0dc49dada9eacfd4a50a79
    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Nov 26, 2021)

    Change Log

    Feature

    • feat: add new methods for get str as array https://github.com/php-toolkit/pflag/commit/4ffe85f9d14bab119a759bce98c086367b79332b
    • feat: support add multi alises for an option https://github.com/php-toolkit/pflag/commit/fb447ff424dae00376f98425b09b3232727016b0

    Optimize

    • prof: has multi words, is an desc. auto padding type: string https://github.com/php-toolkit/pflag/commit/c165362c95faae0f2e34bd0fed29695e5a09940a
    • prof: display option alias on render help https://github.com/php-toolkit/pflag/commit/ea91aa262bb12e96d07ccdfd93e6b5f0f2da0f35

    Other

    • style: update readme, add docsify config https://github.com/php-toolkit/pflag/commit/b32b3bdb8ffeb38eeadf07e8e4b7749bbdfee12f
    • chore: update navbar config https://github.com/php-toolkit/pflag/commit/90f35d631aef16cd07b097217dbb6190f73f915c
    • doc: user remote repo navbar config https://github.com/php-toolkit/pflag/commit/dc705bd7b10b0e62507ee727a97de49d99df8fa8
    • doc: update docs config https://github.com/php-toolkit/pflag/commit/e6e8b41f56096d4c20990514fd8ea3b9e4eae5d6
    • doc: update some doc config https://github.com/php-toolkit/pflag/commit/679f9a085cc95e7855b768b103ae67e54268f7d7
    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Oct 26, 2021)

    Change Log

    Update

    • update readme https://github.com/php-toolkit/pflag/commit/28ff0eaf003f2d71bcd2c9efa9fbb90d4b796ecd
    • up: add an new helper class https://github.com/php-toolkit/pflag/commit/00c33bface78b8b73228e7ea5cafbe825235481e

    Feature

    • feat: add new method getMustArg for get required arg https://github.com/php-toolkit/pflag/commit/9ece2c6b08689e4fe3cd8651394e5e53160e0a6f
    • feat: add new method getMustOpt for get required opt https://github.com/php-toolkit/pflag/commit/1242dd7974a947bb108b2795d24045254e44dffd
    • feat: support add hidden flag options https://github.com/php-toolkit/pflag/commit/3bffa4e2ebb46a91f137041c560c45b24204fb5e

    Other

    • breaking: refactor the get opt help data https://github.com/php-toolkit/pflag/commit/454ca17feda42238c9f87bc0f9a8875e60e71abb
    Source code(tar.gz)
    Source code(zip)
  • v1.0.7(Sep 29, 2021)

  • v1.0.6(Sep 29, 2021)

    Change Log

    Fixed

    • fix: number should not as option name. eg -9 https://github.com/php-toolkit/pflag/commit/2ad5db9e8d2531280077ed8aa336152935e10021

    Feature

    • feat: add zh-CN readme https://github.com/php-toolkit/pflag/commit/c6cd2a055ca59d162222c50fa15a26f2bc388f0b

    Update

    • update readme https://github.com/php-toolkit/pflag/commit/cbf0de07c34214859ca5036d9b5c40677c5d42d7
    • update some for output coverage report https://github.com/php-toolkit/pflag/commit/951b56d6d7fa8dc756b40b88e81e72cc29f2ec55

    Other

    • style: update readme https://github.com/php-toolkit/pflag/commit/76689adbb3ad30eb9b4022fb278ea40c6a844134
    Source code(tar.gz)
    Source code(zip)
Owner
PHP Toolkit
Some basic Toolkit for the PHP
PHP Toolkit
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

null 324 Dec 8, 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

null 324 Dec 8, 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.

Snicco 5 Oct 7, 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. ??

Nuno Maduro 32 Dec 26, 2022
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

James Hall 745 Dec 30, 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. Installation / Usage Requires PHP 8.0+ First, install Patr

Nuno Maduro 237 Nov 14, 2022
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

Erika Heidi 33 Nov 16, 2022
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.

null 8 Nov 3, 2022
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

EasyEngine 2k Jan 4, 2023