weew/console-formatter

命令行输出格式化工具。

v2.1.2 2016-07-21 11:17 UTC

This package is not auto-updated.

Last update: 2024-09-10 21:52:44 UTC


README

Build Status Code Quality Test Coverage Version Licence

目录

安装

composer require weew/console-formatter

介绍

此包允许您使用非常简单且类似HTML的语法来格式化终端文本。您将能够更改文字颜色文字背景文字格式

此包未在Windows上测试,并且我不打算这样做。欢迎为Windows支持做出贡献。

添加样式

在您能够使用样式之前,您必须先创建它们。

$formatter = new ConsoleFormatter();

$style = (new ConsoleStyle('alert'))
    ->setColor(ConsoleColor::WHITE)
    ->setBackground(ConsoleBackground::RED)
    ->setFormat([ConsoleFormat::BOLD, ConsoleFormat::UNDERLINE]);
$formatter->addStyle($style);

// or

$formatter->style('alert')
    ->setColor(ConsoleColor::WHITE)
    ->setBackground(ConsoleBackground::RED)
    ->setFormat([ConsoleFormat::BOLD, ConsoleFormat::UNDERLINE]);

// or

$formatter->style('alert')
    ->parseStyle('clr=white bg=red fmt=bold,underline');

使用样式

一旦您注册了一个样式,它就会应用于匹配的标签。如果样式未知,则标签将被忽略。以下示例将输出格式正确的文本。

echo $formatter->format('<alert>text</alert>');

使用内联样式

您可以直接应用样式,而无需注册新的样式。要做到这一点,您必须使用<style></style>标签。

echo $formatter->format('<style clr=red bg=white>red text on white background</style>');

您也可以在预定义样式上使用内联样式。

$formatter->format('<alert clr=yellow>alert style with yellow text</alert>');

样式隔离

当您有嵌套样式时,一个样式可能从父级继承。默认情况下,这是禁用的,以防止不希望的风格更改。您可以为每个样式单独启用它。

$formatter->style('name')
   ->setAllowInheritance(true);

禁用ANSI

如果您正在使用不支持ANSI的终端,您可以禁用格式化。所有已知的样式标签都将从字符串中删除。

$formatter->setEnableAnsi(false);
// will return: alert <unknown>tag</unknown>
$formatter->format('<style clr=red><alert>alert <unknown>tag</unknown></alert></style>');

示例

您可以通过运行examples.php文件来查看它是否在您的系统上工作。