phasync
Console and logging / Console

Class

Console

Terminal output from markup: styled on a terminal, plain text when piped to a file, and laid out the same way in both.

Introduction#

<!…> opens a span, <!> closes the last one opened; spans nest. A span takes styles and layout, in any order:

Text from elsewhere goes through escape() first. Widths count terminal columns: East Asian wide characters and emoji take 2, combining marks and zero-width characters 0.

Class synopsis#

final class Console {
    /* Methods */
    public Console::__construct($stream = STDOUT, ?bool $color = null)
    public Console::write(string $markup): void
    public Console::log(
        string $level,
        Stringable|string $message,
        array $context = [],
        string $source = ''
    ): void
    public Console::render(string $markup): string
    public Console::hasColor(): bool
    public static Console::columns(): int
    public static Console::strip(string $markup): string
    public static Console::escape(string $text): string
    public static Console::width(string $markup): int
    public static Console::pad(
        string $markup,
        int $width,
        int $align = STR_PAD_RIGHT,
        string $pad = ' '
    ): string
    public static Console::cut(string $markup, int $width, string $ellipsis = ''): string
}

Methods#

MethodDescription
__constructCreates a console writing to $stream.
writeWrites $markup to the stream, styled or plain as the console is.
logWrites a log line, in one format everywhere.
render$markup as this console writes it: styled, or plain.
hasColorReturns whether this console writes styled output.
columnsThe terminal's width in columns: $COLUMNS, else 80.
strip$markup as plain text, laid out.
escape$text made safe to embed in markup: shown as it is.
widthThe columns $markup takes on a terminal.
padReturns $markup padded with $pad to $width columns.
cut$markup cut to at most $width columns, ending with $ellipsis when anything was cut; the styles still open are closed.

Examples#

Example 1
$out = new Console();
$out->write("<!bold pad 12>--http<!><!dim>Serve HTTP here<!>\n");
$out->write("<!lpad 8>1.2 MB<!> <!pad 40>$name<!>\n");