rayanlevert/command-line-interface

无依赖的命令行界面(CLI),用于处理参数并轻松在PHP用户空间中自定义输出

v2.3.0 2024-09-27 04:35 UTC

README

Packagist Version PHP from Packagist codecov

RayanLevert\Cli\Arguments\Argument 定义了什么是参数

参数有一个名称和不同的选项,只能为 integerdoublestring 类型(如果使用 noValue 选项,则将是 bool

new \RayanLevert\Cli\Arguments\Argument(string $name, array $options = [])
- description (string) Description of the argument
- defaultValue (float|int|string) Default value if the argument is not handled
- required (bool) If the argument must be present and parsed
- castTo (string) PHP type - If the argument has a type other than string, its value will be casted
- noValue (bool) If a prefixed argument doesn't need a value -> boolean cast
- prefix (string) Short prefix (-u)
- longPrefix (string) Long prefix (--user)

如果选项不合规,则可以抛出 RayanLevert\Cli\Arguments\Exception(请参阅 __construct()

RayanLevert\Cli\Arguments 是一个参数集合,可以解析来自 argv(字符串数组)的值

new \RayanLevert\Cli\Arguments(\RayanLevert\Cli\Arguments\Argument ...$oArguments)

必须先声明必需参数,然后再声明非必需参数

通过方法 parse(string ...$arguments): void 恢复解析的值

要从实际的CLI解析参数,请使用 parse(...$argv)(如果您不在全局作用域中,请声明 global $argv;

将每个解析的值与其集合中的参数相关联

可以通过 ::get(string $argumentName) 恢复参数的解析值

默认情况下,返回 NULL;如果参数已解析且设置了选项 castTo,则可以返回 integerfloatstring

  • 如果 castTointegerfloat,则值必须是数字字符串(使用 is_numeric() 进行断言)
  • 如果 castTostring(默认值),则值将是解析后的值

实现

$oArguments = new Arguments(new Argument('arg1'));
$oArguments->get('arg1') // NULL

$oArguments = new Arguments(new Argument('arg1', ['defaultValue' => 'test']));
$oArguments->get('arg1') // test

$oArguments = new Arguments(new Argument('arg1', ['castTo' => 'float', 'defaultValue' => 14.3]));
$oArguments->get('arg1') // 14.3

$oArguments = new Arguments(new Argument('arg1', ['required' => true]));
$oArguments->parse(); // ParseException arg1 is required
$oArguments->parse('test'); // OK $oArguments->get('arg1') = test

// Parsing optional arguments
$oArguments = new Arguments(new Argument('arg1'), new Argument('arg2'));
$oArguments->parse('test1'); // $oArguments->get('arg1') = test1, $oArguments->get('arg1') = NULL
$oArguments->parse('test1', 'test2'); // $oArguments->get('arg1') = test1, $oArguments->get('arg1') = test2

// Parsing prefixed arguments
$oArguments = new Arguments(new Argument('arg1', ['prefix' => 'a', 'longPrefix' => 'arg']));
$oArguments->parse('-a=testValue'); // $oArguments->get('arg1') = testValue
$oArguments->parse('-a="test Value"'); // $oArguments->get('arg1') = test Value
$oArguments->parse('--arg=testValue'); // $oArguments->get('arg1') = testValue
$oArguments->parse('--arg="test Value"'); // $oArguments->get('arg1') = test Value

有多个方法可用

  • 添加参数 - set(Argument $oArgument): void
  • 删除一个 - remove(string $argumentName): void
  • 返回参数数量 - count(): int
  • 打印关于参数信息的清晰显示 - printArguments(): void
      Required arguments:
        arg1 (type: string)
        arg2 (type: integer)
    
      Optional arguments:
        arg3 --arg3=arg3 (type: integer)
        arg4 -arg4
    

通过更改显示文本的颜色和格式来自定义命令行界面

RayanLevert\Cli\Style 是一个仅具有静态方法的类

提供3个枚举来美化输出

  • RayanLevert\Cli\Style\Background:背景颜色
  • RayanLevert\Cli\Style\Foreground:文本颜色
  • RayanLevert\Cli\Style\Attributes:文本属性

使用2个主要方法来显示格式化文本

/**
 * Prints a string of a background color, text color and/or an attribute
*/
public static function inline(string $string, Background $bg = null, Foreground $fg = null, Attribute $at = null): void;

/**
 * Prints a string and breaks a line of a background color, text color and/or an attribute
*/
public static function outline(string $string, Background $bg = null, Foreground $fg = null, Attribute $at = null): void;

还有一个方法可以返回格式化字符串而不是打印它

public static function stylize(string $string, Background $bg = null, Foreground $fg = null, Attribute $at = null): string;

其他有用的方法也可用

/**
 * Prints a formatted string thanks to its tags of ANSI codes (Foreground, Background and Attribute)
 *
 * Useful is you want to use multiple styles in one single method call
 *
 * Tags to use are in the three enumerations thanks to the 'tryFromTag' method
*/
public static function tag(string $tag): void

====================================
。◕‿◕。 This is a title 。◕‿◕。
====================================
public static function title(string $title): void;

--- Flanked message ---\n
public static function flank(string $message, string $char = '-', int $length = 3): void;

  (◍•﹏•) Warning message\n
public static function warning(string $message): void; // colored text in yellow

  (◍•﹏•) Error message\n
public static function error(string $message): void; // colored text in red

public static function red(string $message): void; // displays a red colored text and breaks a line
public static function green(string $message): void; // displays a green colored text and breaks a line
public static function yellow(string $message): void; // displays a yellow colored text and breaks a line

// Displays according to a boolean status, a red or green text colored message and breaks a line
public static function outlineWithBool(bool $status, string $ifTrue, string $ifFalse, string $toPrecede = ''): void;

// Prints the details of an exception in red + its trace in white
public static function exception(\Exception $e, bool $withoutTrace = false): void;

RayanLevert\Cli\ProgressBar 通过进度条显示进度输出

/**
 * @param int $max Maximum value of iterations
 * @param int $numberOfSymbols Number of symbols added after each iteration
*/
$oProgressBar = new ProgressBar(int $max, int $numberOfSymbols = 50);

/**
 * @param string $title Title to add above the progress bar
 * @param Style\Foreground $fg Text color
*/
$oProgressBar->setTitle(string $title = '', Style\Foreground $fg = Style\Foreground::BLUE);

/**
 * Starts the progress bar (or restarts it, if not breaks two lines)
*/
$oProgressBar->start();

/**
 * Advances the progress bar of `$toAdvance` iterations updating the progression
*/
$oProgressBar->advance(int $toAdvance = 1);

// Finishes the progress bar (advances to the max value)
$oProgressBar->finish();

简单实现

// 10 is the max value -> a new symbol every new iteration
$oProgressBar = new ProgressBar(10);
$oProgressBar->start('My progress bar');

// Advances to 1 each iteration
foreach (range(1, 10) as $range) {
    $oProgressBar->advance();
}

  My progress bar
  1 / 10 [#         ]
  2 / 10 [##        ]
  ...
  10 / 10 [##########]