eureka/component-console

用于运行脚本的组件控制台,与 Eureka 框架结合使用

6.2.0 2024-08-21 10:20 UTC

README

Current version Supported PHP version CI Quality Gate Status Coverage

控制台组件,用于运行脚本。您可以通过内核控制台轻松将其集成到 Eureka 框架应用程序中,并使用依赖注入。

控制台提供了类似 Linux 系统上其他命令的参数管理器。控制台提供了一些定义的类,可以帮助您编写很多漂亮的脚本。

执行

vendor/bin/console --script="My\Class\Name"
vendor/bin/console --script=My/Class/Script
vendor/bin/console My/Class/Script
vendor/bin/console my/class/script # first character of each part can omit upper case

文档

选项与参数

这些选项与 Unix 参数类似。支持完整和简写别名。

因此,您可以根据命令选项拥有动态的脚本。

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\AbstractScript;
use Eureka\Component\Console\Help;
use Eureka\Component\Console\Option\Option;
use Eureka\Component\Console\Option\Options;

class ExampleScript extends AbstractScript
{
    public function __construct()
    {
        $this->setExecutable();
        $this->setDescription('Example script');

        $this->initOptions(
            (new Options())
                ->add(
                    new Option(
                        shortName:   'u',
                        longName:    'user',
                        description: 'User name',
                        mandatory:   true,
                        hasArgument: true,
                        default:     'Joe doe',
                    )
                )
                ->add(
                    new Option(
                        shortName:   'n',
                        longName:    'is-night',
                        description: 'If is night'
                    )
                )
        );
    }

    public function help(): void
    {
        (new Help(self::class, $this->declaredOptions(), $this->output(), $this->options()))
            ->display()
        ;
    }

    /**
     * @return void
     */
    public function run(): void
    {
        $user = $this->options()->get('user', 'u')->getArgument();
        $say  = $this->options()->get('is-night', 'n')->getArgument() ? 'Good night' : 'Hello';
        
        //~ Can also use short version:
        // $user = $this->options()->value('user', 'u');
        // $say  = $this->options()->value('is-night', 'n') ? 'Good night' : 'Hello';

        $this->output()->writeln("$say $user!");
    }
}

保留选项

一些选项是保留的

  • -h, --help: 显示帮助
  • --no-color: 禁用颜色/样式(也可以使用 NO_COLOR 环境变量禁用)
  • --debug: 激活调试模式(如果脚本因异常而终止,则跟踪异常)
  • --time-limit=ARG: 指定秒数的时间限制(默认:0 - 无限制)
  • --memory-limit=ARG: 指定内存限制(128M, 1024M, 4G... - 默认:256M)
  • --error-reporting=ARG: 指定错误报告的值(默认:-1 - 所有)
  • --error-display=ARG: 指定 display_errors 设置的值。值:0|1 默认:1(显示)
  • --quiet: 强制禁用控制台输出(如果消息写入流输出)
  • --with-header: 启用控制台库消息头
  • --with-footer: 启用控制台库消息脚
  • --script=ARG(或只需ARG):要运行的控制台类脚本(例如:database/console)- 必须的

帮助

提供类帮助,以便在您为脚本使用 --help 参数时具有漂亮的参数格式。

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\Help;
use Eureka\Component\Console\Option\Option;
use Eureka\Component\Console\Option\Options;
use Eureka\Component\Console\Output\NullOutput;

$output  = new NullOutput();
$options = (new Options())
    ->add(
        new Option(
            shortName:   'u',
            longName:    'user',
            description: 'User name',
            mandatory:   true,
            hasArgument: true,
            default:     'Joe doe',
        )
    )
    ->add(
        new Option(
            shortName:   'n',
            longName:    'is-night',
            description: 'If is night'
        )
    )
);
$help = new Help('Application/My/Script', $options, new NullOutput());
$help->display();
Use    : bin/console Examples\ExampleScript [OPTION]...
OPTIONS:
  -u ARG, --user=ARG                    User name - MANDATORY
  -n,     --is-night                    If is night

输入/输出

输入

输入由 Input 接口处理。可以处理来自用户的提示控制台。

输出

输出由 Output 接口处理。可以在标准输出、文件、内存(根据传递给 OutputStream 类的流资源)上显示内容。

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\Output\StreamOutput;

$output = new StreamOutput(\STDOUT, false);
$output->writeln('Hello!'); // PHP_EOL is added to the line
$output->write('Hello!');   // No new line

$output = new StreamOutput(\STDERR, false);
$output->writeln('Error message for "error output (stderr)');

样式

控制台输出支持样式和颜色

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\Color\Bit4HighColor;
use Eureka\Component\Console\Color\Bit4StandardColor;
use Eureka\Component\Console\Style\Style;

$whiteBold      = (new Style())->bold();
$greenHighlight = (new Style())->color(Bit4StandardColor::Green);
$bgErrorRed     = (new Style())->background(Bit4HighColor::Red);

echo $bgErrorRed->apply('An error as occurred!');

颜色

控制台现在嵌入 4 位颜色、8 位颜色和 24 位颜色。8 位和 24 位颜色的支持取决于终端应用程序(8 位颜色具有正确的支持,而 24 位颜色则不支持)

  • 4 位颜色列在两个 Enum 中(用于常规和高强度颜色)
  • 8 位基本颜色列在两个 Enum 中(用于常规和高强度颜色)
  • 8 位复杂颜色使用 RGB 类(+ 带强度的灰度类)
  • 24 位使用 RGB 类

漂亮的表格

您可以使用 Table 及相关类轻松显示漂亮的表格

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\Table\Table;

//~ Table with header
$table = new Table(3, new Border(Border::BASE);
$table->newRow(['Col 1', 'Col 2', 'Col 3'], true);
$table->newRow([1, 2, 3]);
$table->newRow(["text", "very long text", 1.2]);
$table->newRowSpan('Spanned row');
echo $table->render();

输出将如下所示

╔══════════╤══════════╤══════════╗
║ Col 1    │ Col 2    │ Col 3    ║
╠══════════╪══════════╪══════════╣
║ 1        │ 2        │ 3        ║
║ text     │ very lo… │ 1.2      ║
║          Spanned row           ║
╚════════════════════════════════╝

以及非扩展 ASCII 字符

+----------+----------+----------+
| Col 1    | Col 2    | Col 3    |
+----------+----------+----------+
| 1        | 2        | 3        |
| text     | very lo… | 1.2      |
|          Spanned row           |
+--------------------------------+

漂亮的进度条/百分比

您可以使用进度条或百分比轻松显示

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\Progress\ProgressBar;

$maxIteration = 10;
$maxSize      = 20;
$progress = new ProgressBar(new Options(), $maxIteration, $maxIteration);
$progress->setTypeDisplay(ProgressOld::TYPE_BAR);

for ($i = 0; $i < $maxIteration; $i++) {
    $progress->display('iteration #' . $i);
}

类型栏

第一次迭代后

│██░░░░░░░░░░░░░░░░░░│ iteration #0

第二次迭代后

│████░░░░░░░░░░░░░░░░│ iteration #1

最后

│████████████████████│ iteration #9

类型百分比

第一次迭代后

[ 10.00%] iteration #0

第二次迭代后

[ 20.00%] iteration #1

最后

[100.00%] iteration #9

终端与光标

现在,您可以通过终端获取有关终端宽度和高度的信息,并在此处操作光标

<?php

declare(strict_types=1);

namespace Examples;

use Eureka\Component\Console\Output\NullOutput;use Eureka\Component\Console\Output\StreamOutput;use Eureka\Component\Console\Terminal\Terminal;

$output   = new StreamOutput(\STDOUT, false);
$terminal = new Terminal(new NullOutput());

//~ Get Terminal sizes
$output->writeln("{$terminal->getWidth()}x{$terminal->getHeight()}");

//~ Clear terminal
$terminal->clear();

//~ Get cursor and manipulate it
$terminal->cursor()->down();

贡献

请参阅CONTRIBUTING 文件。

安装/更新项目

您可以使用以下命令安装项目

make install

并使用以下命令更新

make update

注意:对于组件,composer.lock 文件未提交。

测试与 CI(持续集成)

测试

您可以使用以下命令在您的端上运行测试(带有覆盖率)

make tests

为了更美观的输出(但不包含覆盖率),您可以使用以下命令

make testdox # run tests without coverage reports but with prettified output

代码风格

您还可以使用以下命令运行代码风格检查

make phpcs

您还可以使用以下命令运行代码风格修复

make phpcbf

静态分析

为了对您的代码进行静态分析(默认使用phpstan,级别9),您可以使用以下命令

make phpstan

为了确保您的代码仍然与Deezer当前支持的版本以及未来的PHP版本兼容,您需要运行以下命令(两者都是完整支持所必需的)

最低支持版本

make php81compatibility

最高支持版本

make php82compatibility

CI 模拟

最后,“辅助”命令,您可以在提交和推送之前运行的是

make ci  

许可证

component-console遵循MIT许可证 - 详细内容请参阅LICENSE文件