molovo/graphite
一组构建美观命令行工具的辅助函数。
v0.1.3
2016-03-09 23:38 UTC
This package is auto-updated.
Last update: 2024-08-29 04:31:03 UTC
README
一组构建美观命令行工具的辅助函数。
$graphite = new Molovo\Graphite\Graphite; echo $graphite->green->underline('I believe in unicorns!');
安装
使用 composer 安装
composer require molovo/graphite
基本用法
一旦实例化,Graphite 类就变成一个可重用的字符串渲染工具。它包含多个方法,使用 ANSI 转义码对字符串的前景色、背景色和样式进行样式设置。
echo $graphite->red('A string'); // "\033[0;31mA string\033[0;m"
当作为属性访问,或没有参数的方法时,这些方法允许样式链的连续。当传入一个字符串作为第一个参数时,它会返回应用了所有链式样式的字符串。
echo $graphite->red->yellowbg()->underline('A string'); // "\033[4;31;43mA string\033[0;m"
可以使用 setGlobalIndentation()
方法设置全局缩进。一旦定义,当调用 render()
方法时,传递给它的字符串将带有定义的缩进前缀,并在末尾添加换行符。
$graphite->setGlobalIndentation(2); echo $graphite->yellow->render('A string'); // " \033[0;33mA string\033[0;m\n"
可用的样式方法
黑色
黑色背景
红色
红色背景
绿色
绿色背景
黄色
黄色背景
蓝色
蓝色背景
品红色
品红色背景
青色
青色背景
白色
白色背景
灰色
灰色背景
加粗
斜体
下划线
反转
删除线
其他方法
除了上述样式方法外,以下辅助方法也是可用的。
strip(string $str)
strip()
方法从传入的字符串中移除所有 ANSI 转义码,并返回它。
$str = "\033[0;31mA string with ANSI escaping\033[0;m" echo $graphite->strip($str); // "A string with ANSI escaping"
repeat(string $character, int $length)
repeat()
方法返回由定义的 $character
组成的字符串,重复 $length
次。
echo $graphite->repeat('+', 5); // "+++++"
盒子
Box
类在字符串(或字符串数组,其中每个元素是一行)周围添加边框。
$box = new Molovo\Graphite\Box('Rainbows!'); echo $box; // ┌─────────┐ // │Rainbows!│ // └─────────┘
可以通过传递样式数组作为第二个参数来以多种方式设置盒子的样式。
$box = new Box('Unicorns!', [ 'borderColor' => Graphite::WHITE, // The color of the border (and title) 'borderStyle' => Box::SINGLE, // The border style 'marginX' => 0, // The number of characters to add to left and right 'marginY' => 0, // The number of lines to add above and below 'paddingX' => 0, // The number of characters to add as left and right padding 'paddingY' => 0, The number of lines to add as top and bottom padding ]);
以下样式可用
Box::SINGLE
┌──────────┐
│The string│
└──────────┘
Box::DOUBLE
╔══════════╗
║The string║
╚══════════╝
Box::ROUNDED
╭──────────╮
│The string│
╰──────────╯
Box::SINGLE_DOUBLE
╓──────────╖
║The string║
╙──────────╜
Box::DOUBLE_SINGLE
╒══════════╕
│The string│
╘══════════╛
Box::CLASSIC
+----------+
|The string|
+----------+
您还可以使用 Box::NO_BORDER
为没有边框的字符串添加边距和填充。
$box = new Box("Unicorns and\nrainbows", [ 'borderStyle' => Box::NO_BORDER, 'paddingX' => 2, 'paddingY' => 1 ]); echo $box; // // Unicorns and // rainbows //
您还可以为盒子添加标题。这些标题在边框内渲染,颜色相同。
$box = new Box('The string', ['paddingX' => 1]); $box->setTitle('My Box'); echo $box; // ┌ My Box ────┐ // │ The string │ // └────────────┘
表格
$data = [ ['First', 'Second', 'Third'], [1, 2, 3], [11, 22, 33], ]; $table = new Table($data, [ 'cellPadding' => 1, 'columnSeparator' => '│', 'headerColor' => Graphite::WHITE, 'headerSeparator' => '═', 'marginX' => 0, 'marginY' => 0, 'separatorColor' => Graphite::WHITE, ]); echo $table; // First │ Second │ Third // ══════════════════════════ // 1 │ 2 │ 3 // 11 │ 22 │ 33