aboutsummaryrefslogtreecommitdiff
path: root/lib/ansi.php
blob: 9e0a42522a0c33be7f9afbf032a38b3f7d9f553a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php

enum AnsiColor: int {
    case BLACK   = 0;
    case RED     = 1;
    case GREEN   = 2;
    case YELLOW  = 3;
    case BLUE    = 4;
    case MAGENTA = 5;
    case CYAN    = 6;
    case WHITE   = 7;
}

function ansi(string $text,
              ?AnsiColor $fg = null,
              ?AnsiColor $bg = null,
              bool $bold = false,
              bool $fg_bright = false,
              bool $bg_bright = false): string {
    $codes = [];
    if (!is_null($fg))
        $codes[] = $fg->value + ($fg_bright ? 90 : 30);
    if (!is_null($bg))
        $codes[] = $bg->value + ($bg_bright ? 100 : 40);
    if ($bold)
        $codes[] = 1;

    if (empty($codes))
        return $text;

    return "\033[".implode(';', $codes)."m".$text."\033[0m";
}