swew / cli
SWEW/CLI:一个用于简化命令行界面(CLI)开发的PHP包,提供直观的API以创建自定义命令、处理输入/输出和轻松执行命令逻辑。通过快速开发简化您的CLI应用程序开发。
v1.1.20
2024-08-12 12:39 UTC
Requires
- php: >=8.1
Requires (Dev)
- laravel/pint: 1.9.0
- phpstan/phpstan: ^1.10.53
- psalm/phar: ^5.18.0
- swew/dd: ^1.3.1
- swew/test.phar: ^1.5.13
README
此包是一个用于以面向对象的方式构建控制台应用程序和命令的PHP库。它提供了一个简单直观的API来定义命令和处理参数和选项。它还包括用于与控制台交互的实用程序,例如着色输出和提示用户输入。使用此包,您可以快速创建强大的命令行工具并自动化开发工作流程中的重复性任务。
SWEW开发的包
安装
composer require swew/cli
使用示例
创建命令
<?php namespace My\Cli\Commands; use Swew\Cli\Command; class ShowTimeCommand extends Command { const NAME = 'show:time {prefix}'; const DESCRIPTION = 'The function shows the current time.'; public function __invoke(): int { $prefix = $this->arg('prefix')->getValue(); $time = $prefix . ' ' . date('H:i:s'); $this->output->writeLn($time); return self::SUCCESS; } }
创建CLI程序
<?php namespace My\Cli; use Swew\Cli\SwewCommander; use My\Cli\Commands\ShowTimeCommand; class MySuperCli extends SwewCommander { protected array $commands = [ ShowTimeCommand::class, ]; }
运行CLI程序
<?php // index.php require __DIR__.'/vendor/autoload.php'; use My\Cli\MySuperCli; (new MySuperCli($argv))->run();
php index.php 'show:time at'
API / DOC
控制台 — 用户命令
SWEW-CLI创建命令的示例。
命令必须继承自Swew\Cli\Command
类,并且该类必须可以通过__invoke
方法调用。
该类还必须有两个必需的常量。
NAME
- 必须调用命令,它还可以包含参数。DESCRIPTION
是命令的描述,用于调用help
消息。
命令执行的结果应该返回结果 - 状态码。如果一切顺利,它是0
。
class SendEmail extends Command { const NAME = 'send:email'; const DESCRIPTION = 'Command to send email'; public function __invoke(): int { // ... return self::SUCCESS; } }
通过继承类Command
- 我们还获得了其中定义的辅助方法。
init(): void
- 在执行之前运行(可以重写)arg(string $key):
CommandArgument` - 获取传递给命令的参数argv(string $key): mixed
- 获取值getHelpMessage(): string
- 获取命令的帮助消息(可以重写)isValid(): bool
- 检查是否正确传递了所有必需的参数给命令getErrorMessage():string
- 获取错误消息call(string $command, ?array $args:) int
- 调用另一个命令
处理命令参数,参数描述
// Only command name, no arguments const NAME = 'send:email'; // One required argument userId, the argument is always wrapped in curly braces const NAME = 'send:email {--userId}'; // Optional argument userId is empty string const NAME = 'send:email {--userId=}'; // Optional argument with default value is string const NAME = 'send:email {--userId=1}'; // Optional argument, userId as array const NAME = 'send:email {--userId=[]}'; /** Typing */ // Argument with typing const NAME = 'send:email {--userId (int)}'; // Argument with typing const NAME = 'send:email {--userId (float)}'; // Argument with typing, default userId === 0 const NAME = 'send:email {--userId= (int)}'; // Argument with typing, default userId === '' const NAME = 'send:email {--userId= (str)}'; // Argument with typing, default userId === false const NAME = 'send:email {--userId= (bool)}'; // Argument with typing, default: userId === false // if command: `send:email` userId === true // if command: `send:email --userId` userId === true const NAME = 'send:email {--userId= (bool)}'; // Alias for argument const NAME = 'send:email {-S|--silent}'; /** Description */ const NAME = 'send:email {mail : The description, will be reflected in help}'; /** Example command with one argument in the full description */ const NAME = 'send:email {--count|-C=1 (int) : Count of mails}'; // command | argument|alias|default | type | description
编写输出
write / writeLn / info / warn / error
$this->output->write('Hello '); $this->output->write('world', '<b>%s <br></>'); // formatting $this->output->writeLn('Hello'); // write with new line $this->output->writeLn('world', '<b>%s <br></>'); $this->output->info('Some good news'); $this->output->warn('A little attention'); $this->output->error('Something has gone wrong'); $this->output->clear(); // Reset terminal window
宽度 / 高度
$this->output->width(); $this->output->height();
格式化
$this->output->write('<b><black><bgRed>Hello world</>'); // OR $format = '<b><black><bgRed>%s</>'; $this->output->write('Hello world', $format);
符号
</>
- 转义<br>
- 换行<b>
- 加粗<u>
- 下划线
颜色
光标
<saveCursor>
<restoreCursor>
<eraseToEndLine>
<eraseToStartLine>
<eraseLine>
<eraseToBottom>
<eraseToTop>
无格式
如果您不想使用格式化,请指定此选项
$this->output->setAnsi(false);
清除bash颜色
从字符串中移除bash颜色符号
$this->output->clearColor($text); // no color string
空行
// Write a single blank line... $this->output->newLine(); // Write three blank lines... $this->output->newLine(3);
链接
$this->output->getLink($url, $text);
输入提示
询问
public function __invoke(): int { $name = $this->output->ask('What is your name?'); // ... return self::SUCCESS; }
询问是或否
public function __invoke(): int { $name = $this->output->askYesNo('Is this the best CLI utility?', true); // ... return self::SUCCESS; }
秘密
public function __invoke(): int { $password = $this->output->secret('What is the password?'); // ... return self::SUCCESS; }
选择问题
public function __invoke(): int { /** @var string */ $answer = $this->output->choice( 'What is your name?', ['Leo', 'Mike', 'Don', 'Raph'], $isRequired = true // optional ); $this->output->writeLn($answer); // ... return self::SUCCESS; }
多选
public function __invoke(): int { /** @var array */ $answer = $this->output->select( 'What is your name?', ['Leo', 'Mike', 'Don', 'Raph'], $selectedIndex = [], // optional $isRequired = true, // optional $isMultiple = true, // optional ); // ... return self::SUCCESS; }
表格
$title = ['Name', 'Age', 'Weapon']; $list = [ ['Leo', 22, 'Swords'], ['Mike', 21.6, 'Nunchaks'], ['Don', 21.9, 'Bo'], ['Raphael', 21.5, 'Saii'], ]; $this->output->table($title, $list);
进度条
$bar = $this->output->createProgressBar(count($users)); $bar->start(); // show progress bar foreach ($users as $user) { $this->someTask($user); $bar->increment(); // progress } $bar->finish(); // remove progressbar
输出
如果您只需要将输出输出到控制台,您可以使用 Output
类单独使用。
<?php require __DIR__ . '/../vendor/autoload.php'; use Swew\Cli\Terminal\Output; $output = new Output(); $output->writeLn('Hello world!');