danbettles / command-line-tools
仅包含一些基本类,可以更轻松地编写命令行脚本。当使用类似Symfony Console这样的工具过于强大时,可以使用这个库。
Requires
- php: ^7.4|^8.1.3
Requires (Dev)
- danbettles/codesniffer-standard: ^2.0
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-26 01:25:30 UTC
README
该库仅包含一些基本类,可以更轻松地编写命令行PHP脚本。它提供了运行外部程序的帮助器和向输出发送格式化消息的方法。当使用类似 Symfony Console 这样的工具过于强大时,可以使用这个库。
主要组件类包括 Output
、MessageFormatter
和 Host
。
Output
在屏幕上显示消息;它提供输出不同风格消息的方法。
例如
(new Output())->writeLine('A plain-looking message followed by a newline.'); (new Output())->danger('A brightly-coloured message about something that just went wrong, followed by a newline.');
运行 php tests/show_output_formats.php
查看Output能做什么。
MessageFormatter
提供用于创建格式化消息的流畅接口。 它使用类似CSS的方法,尽可能使用CSS命名约定,使Web开发者更容易、更直观地完成任务。
例如,以下两个调用都会在亮红色的背景上创建相同的加粗白色消息。
$formattedMessage = (new MessageFormatter()) ->fontWeight('bold') ->backgroundColor('maroon') ->format('A brightly-coloured message about something that just went wrong') ; $formattedMessage = MessageFormatter::createFromStyleDeclarations([ 'font-weight' => 'bold', 'background-color' => 'maroon', ])->format('A brightly-coloured message about something that just went wrong');
当从样式声明数组创建格式化器时,您可以使用CSS风格的连字符命名或驼峰命名。
MessageFormatter
将自动为前景使用对比色,如果只设置了背景色。
请参阅下文的样式参考部分,了解您可以做什么。
样式参考
运行 php tests/show_styles.php
查看每个样式设置的效果,并确定您的终端是否支持该样式。
Host
提供了一个有用的 passthru()
包装器,它除了输出其执行命令的输出外,还会在默认情况下在出现错误时抛出异常。
例如
$output = new Output(); $host = new Host($output); // Throws an exception if something goes wrong. $host->passthru('ls -al --color=always'); // Will not throw an exception if something goes wrong: instead, will display a formatted error message and return a value indicating the problem that occurred. $resultCode = $host->passthru('ls -al --color=always', false);
安装
除了PHP 7+之外没有其他依赖项。
使用Composer运行 composer require danbettles/command-line-tools
进行安装。
参考
- Fabien Loison(2018年8月9日)Bash技巧:颜色和格式化(ANSI/VT100控制序列) https://misc.flogisoft.com/bash/tip_colors_and_formatting 访问时间:2022年11月16日
- 维基百科(2022年11月9日)ANSI转义码 https://en.wikipedia.org/wiki/ANSI_escape_code#3-bit_and_4-bit 访问时间:2022年11月16日
- Chris Maunder(2022年4月7日)如何在Linux终端中更改文本颜色 CodeProject. https://codeproject.org.cn/Articles/5329247/How-to-change-text-color-in-a-Linux-terminal 访问时间:2022年11月16日
- MDN网络文档(2022年9月27日)font-weight Mozilla. https://mdn.org.cn/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping 访问时间:2022年11月16日
- MDN网络文档(2022年10月5日)<named-color> Mozilla. https://mdn.org.cn/en-US/docs/Web/CSS/named-color#value 访问时间:2022年11月16日