nowise/uup-application-options

统一的命令行和HTTP请求选项。

1.0.6 2022-01-25 02:13 UTC

This package is auto-updated.

Last update: 2024-09-25 07:39:34 UTC


README

支持从CLI命令和HTTP请求中透明/统一地处理运行时选项。

此包支持短/长选项、其他选项,并从终端读取密码(掩码回显输出)。对于HTTP请求选项,可以应用一个可选的过滤器。

用法

在您的命令操作类中,定义一个方法以检查是否返回命令行选项(CLI)或请求选项(HTTP)。

private function getApplicationOptions(): ApplicationOptionsInterface
{
    if (php_sapi_name() == 'cli') {
        return new CommandLineOptions();
    } else {
        return new HttpRequestOptions();
    }
}

调用 getApplicationOptions 将提供对应用选项的统一访问,无论这些选项来自命令行还是HTTP请求。从您的应用角度来看,选项的来源是透明的。

在应用内部,可以使用一些方便的方法来检查是否传递了选项,并以类型安全的方式检索它们。

public function setup() 
{
    $this->options = $this->getApplicationOptions();
}

public function execute(): void 
{
    // 
    // Example of setting defaults:
    // 
    if ($this->options->isMissing('user')) {
        $this->options->setOption('user', 'adam');
    }
    
    // 
    // Take action if option is defined:
    // 
    if ($this->options->hasOption('email')) {
        $this->sendEmail($this->options->getString('email'));
    }
}

存在许多其他获取器,例如用于布尔值、浮点数和整数值的获取器。如果选项缺失,则返回第二个默认值。

来源

如果来源很重要,可以进行检查

if ($this->options->getOrigin() == ApplicationOptionsInterface::ORIGIN_HTTP) {
    throw new RuntimeException("This action can't be run from a HTTP context");
}

选项别名

对于命令行选项,默认行为是返回通过删除前导连字符 ('-') 的选项。为了支持映射到长选项的短命令选项,请传递一个映射数组。

private function getApplicationOptions(): ApplicationOptionsInterface
{
    if (php_sapi_name() == 'cli') {
        return new CommandLineOptions([
            '-f' => 'file',
            '-U' => 'user'
        ]);
    } else {
        return new HttpRequestOptions();
    }
}

这两个短选项现在将成为其等效长选项的别名。一些内置别名默认处理命令行选项。这些短选项包括

  • -h => help
  • -V => version
  • -d => debug
  • -v => verbose
  • -q => quiet

这些在用户定义映射之前处理,使得可以轻松重定义内置映射。

选项值

选项值是等号 ('=') 之后的任何值。对于没有值的选项,选项键将读取为布尔值 true。

连字符

命令行选项(CLI)的处理将删除前导连字符,并使用剩余的字符串作为命令选项键。

选项过滤

命令行选项被认为是安全的。对于HTTP请求,可以传递一个要应用的卫生过滤器的数组。

private function getApplicationOptions(): ApplicationOptionsInterface
{
    if (php_sapi_name() == 'cli') {
        return new CommandLineOptions();
    } else {
        return new HttpRequestOptions(
            new HttpRequestFilter([
                'user'  => FILTER_SANITIZE_STRING,
                'email' => FILTER_SANITIZE_EMAIL
            ])
        );
    }
}

默认行为是不过滤HTTP请求选项。对于大型应用,可以使用可能包装在实现 FilterInterface 的类中的HTML输入净化框架,而不是传递 HttpRequestFilter 类的实例。

布尔值

实现了对布尔选项的特殊处理。例如,选项值 "1"、"true"、"on" 和 "yes" 导致 true。类似的 "0"、"false"、"off" 和 "no" 导致 false。

示例:调用 getBoolean 以将过滤器选项的值评估为布尔值。

$this->options->getBoolean("filter");