php-toolkit/pflag
是一個(gè)PHP編寫的,通用的命令行標(biāo)志(選項(xiàng)和參數(shù))解析庫。
Github 倉庫: php-toolkit/pflag(https://github.com/php-toolkit/pflag)
功能說明
- 通用的命令行選項(xiàng)和參數(shù)解析器
- 支持設(shè)置值數(shù)據(jù)類型(
int,string,bool,array
),將自動(dòng)格式化輸入值 - 支持為選項(xiàng)/參數(shù)設(shè)置默認(rèn)值
- 支持為一個(gè)選項(xiàng)設(shè)置多個(gè)短名稱
- 支持從環(huán)境變量讀取標(biāo)志值
- 支持設(shè)置選項(xiàng)/參數(shù)為必須的(
required
) - 支持設(shè)置驗(yàn)證器以檢查輸入值
- 支持自動(dòng)渲染漂亮的幫助信息。
命令行選項(xiàng):
- 選項(xiàng)以
-
或者--
開頭的,且首字符必須是字母 - 以
--
開頭的為長選項(xiàng). eg:--long
--long value
- 以
-
開頭的為短選項(xiàng)-s -a value
- 支持定義數(shù)組選項(xiàng)
- eg:
--tag php --tag go
將會(huì)得到$tag = [php, go]
- eg:
命令行參數(shù):
- 不能滿足選項(xiàng)的都認(rèn)作參數(shù)
- 支持綁定命名參數(shù)
- 支持定義數(shù)組參數(shù)
安裝
composer 安裝
composer require toolkit/pflag
Flags 使用
Flags – 是一個(gè)命令行標(biāo)志(選項(xiàng)和參數(shù))解析器和管理器。
示例代碼請(qǐng)參見 example/flags-demo.php
創(chuàng)建解析器
創(chuàng)建和初始化解析器
use ToolkitPFlagFlags;require dirname(__DIR__) . '/test/bootstrap.php';$flags = $_SERVER['argv'];// NOTICE: must shift first element.$scriptFile = array_shift($flags);$fs = Flags::new();// (可選的)可以添加一些自定義設(shè)置$fs->setScriptFile($scriptFile);/** @see Flags::$settings */$fs->setSettings([ 'descNlOnOptLen' => 26]);// ...
定義選項(xiàng)
定義選項(xiàng) – 定義好支持的選項(xiàng)設(shè)置,解析時(shí)將會(huì)根據(jù)定義來解析輸入
添加選項(xiàng)定義的示例:
use ToolkitPFlagFlagOption;use ToolkitPFlagFlagType;use ToolkitPFlagValidatorEnumValidator;// add options// - quick add$fs->addOpt('age', 'a', 'this is a int option', FlagType::INT);// - 使用字符串規(guī)則快速添加選項(xiàng)定義$fs->addOptByRule('name,n', 'string;this is a string option;true');// -- 一次添加多個(gè)選項(xiàng)$fs->addOptsByRules([ 'tag,t' => 'strings;array option, allow set multi times', 'f' => 'bool;this is an bool option',]);// - 使用數(shù)組定義/** @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']),]);// - 使用 Option 對(duì)象$opt = Option::new('str1', "this is string option, ndesc has multi line, nhaha...");$opt->setDefault('defVal');$fs->addOption($opt);
定義參數(shù)
定義參數(shù) – 定義好支持的選項(xiàng)設(shè)置,解析時(shí)將會(huì)根據(jù)定義來解析輸入
添加參數(shù)定義的示例:
use ToolkitPFlagFlagArgument;use ToolkitPFlagFlagType;// add arguments// - quick add$fs->addArg('strArg1', 'the is string arg and is required', 'string', true);// - 使用字符串規(guī)則快速添加定義$fs->addArgByRule('intArg2', 'int;this is a int arg and with default value;no;89');// - 使用 Argument 對(duì)象$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);
解析命令行輸入
最后調(diào)用 parse()
解析命令行輸入數(shù)據(jù)
// ...if (!$fs->parse($flags)) { // on render help return;}vdump($fs->getOpts(), $fs->getArgs());
顯示幫助
當(dāng)輸入 -h
或 --help
會(huì)自動(dòng)渲染幫助信息。
$ php example/flags-demo.php --help
Output:
運(yùn)行示例:
$ php example/flags-demo.php --name inhere --age 99 --tag go -t php -t java -d one -f arg0 80 arr0 arr1
輸出結(jié)果:
# 選項(xiàng)數(shù)據(jù)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)}# 參數(shù)數(shù)據(jù) array(3) { [0]=> string(4) "arg0" [1]=> int(80) [2]=> array(2) { [0]=> string(4) "arr0" [1]=> string(4) "arr1" }}
獲取輸入值
獲取flag值很簡單,使用方法 getOpt(string $name)
getArg($nameOrIndex)
即可.
TIP: 將通過定義的數(shù)據(jù)類型自動(dòng)格式化輸入值
選項(xiàng)數(shù)據(jù)
$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"}
參數(shù)數(shù)據(jù)
$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"}
擴(kuò)展:規(guī)則定義
選項(xiàng)參數(shù)規(guī)則。使用規(guī)則可以快速定義一個(gè)選項(xiàng)或參數(shù)?!就扑]:PHP視頻教程】
- string 字符串規(guī)則以分號(hào)
;
分割每個(gè)部分 (完整規(guī)則:type;desc;required;default;shorts
). - array 規(guī)則按
SFlags::DEFINE_ITEM
設(shè)置定義 - 支持的類型常量請(qǐng)看
FlagType::*
use ToolkitPFlagFlagType;$rules = [ // v: 只有值,作為名稱并使用默認(rèn)類型 FlagType::STRING // k-v: 鍵是名稱,值可以是字符串|數(shù)組 '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]
對(duì)于選項(xiàng)
- 選項(xiàng)允許設(shè)置短名稱
shorts
TIP: 例如
long,a,b
–long
是選項(xiàng)名稱. 剩余的a,b
都是它的短選項(xiàng)名.
對(duì)于參數(shù)
- 參數(shù)沒有別名或者短名稱
- 數(shù)組參數(shù)只允許定義在最后
數(shù)組定義項(xiàng)
常量 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];
自定義設(shè)置
解析設(shè)置
// -------------------- 選項(xiàng)解析設(shè)置 -------------------- /** * 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; // -------------------- 參數(shù)解析設(shè)置 -------------------- /** * 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;
渲染幫助設(shè)置
support some settings for render help
// -------------------- settings for built-in render help -------------------- /** * 自動(dòng)渲染幫助信息當(dāng)輸入 '-h', '--help' 選項(xiàng)時(shí) * * @var bool */ protected $autoRenderHelp = true; /** * 在渲染的幫助信息上顯示數(shù)據(jù)類型 * * if False: * * -o, --opt Option desc * * if True: * * -o, --opt STRING Option desc * * @var bool */ protected $showTypeOnHelp = true; /** * 將在打印幫助消息之前調(diào)用它 * * @var callable */ private $beforePrintHelp;
自定義幫助消息渲染:
$fs->setHelpRenderer(function (ToolkitPFlagFlagsParser $fs) { // render help messages});
單元測試
phpunit --debug
test with coverage:
phpdbg -qrr $(which phpunit) --coverage-text
使用pflag的項(xiàng)目
Check out these projects, which use 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
Github 倉庫: php-toolkit/pflag(https://github.com/php-toolkit/pflag)