|
10 | 10 | final class Colorizer
|
11 | 11 | {
|
12 | 12 | /**
|
13 |
| - * Color name => [foreground code, background code] |
| 13 | + * @see https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit |
14 | 14 | */
|
15 | 15 | private const COLORMAP = [
|
16 |
| - 'black' => ['30', '40'], |
17 |
| - 'red' => ['31', '41'], |
18 |
| - 'green' => ['32', '42'], |
19 |
| - 'yellow' => ['33', '43'], |
20 |
| - 'blue' => ['34', '44'], |
21 |
| - 'magenta' => ['35', '45'], |
22 |
| - 'cyan' => ['36', '46'], |
23 |
| - 'white' => ['37', '47'], |
24 |
| - 'gray' => ['90', '100'], |
| 16 | + 'black' => 0, |
| 17 | + 'red' => 1, |
| 18 | + 'green' => 2, |
| 19 | + 'yellow' => 3, |
| 20 | + 'blue' => 4, |
| 21 | + 'magenta' => 5, |
| 22 | + 'cyan' => 6, |
| 23 | + 'white' => 7, |
| 24 | + 'gray' => 8, |
25 | 25 | ];
|
26 | 26 |
|
27 | 27 | private function __construct()
|
@@ -65,19 +65,9 @@ public static function colorize(string $string): string
|
65 | 65 | $pos = \strpos($string, $match[0]);
|
66 | 66 | $len = \strlen($match[0]);
|
67 | 67 | $text = \strip_tags($match[0]);
|
68 |
| - $fg = $attr['fg'] ?? null; |
69 |
| - $bg = $attr['bg'] ?? null; |
70 |
| - $colors = []; |
71 |
| - if (isset(self::COLORMAP[$fg][0])) { |
72 |
| - $colors[] = self::COLORMAP[$fg][0]; |
73 |
| - } |
74 |
| - if (isset(self::COLORMAP[$bg][1])) { |
75 |
| - $colors[] = self::COLORMAP[$bg][1]; |
76 |
| - } |
77 |
| - if ($colors === []) { |
78 |
| - continue; |
79 |
| - } |
80 |
| - $formattedString = \sprintf("\e[%sm%s\e[0m", \implode(';', $colors), $text); |
| 68 | + $color = self::COLORMAP[$attr['fg'] ?? $attr['bg']] ?? $attr['fg'] ?? $attr['bg']; |
| 69 | + $isFg = isset($attr['fg']); |
| 70 | + $formattedString = \sprintf("\e[%s:5:%sm%s\e[0m", $isFg ? '38' : '48', $color, $text); |
81 | 71 | $string = \substr_replace($string, $formattedString, $pos, $len);
|
82 | 72 | }
|
83 | 73 |
|
|
0 commit comments