-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathAnsiColor.php
More file actions
110 lines (97 loc) · 2.89 KB
/
AnsiColor.php
File metadata and controls
110 lines (97 loc) · 2.89 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
namespace TryLib\Util;
use InvalidArgumentException;
use BadMethodCallException;
use Exception;
/**
* Helpful tool for generating colored text on the linux prompt
*
* Usage:
* To use, just call methods in any order to build up the style you want
* (see below for available options.) After you output the string, the
* terminal is automatically reset.
*
* Examples:
*
* # bold, red text
* echo $clr->bold()->red("Some text");
* # The prompt is automatically reset after the text is output.
*
* # To do background colors, just prepend "on" to a color:
* echo $clr->onred('Text')
*
* # blinking red text on intense blue background:
* echo $clr->blink()->bold()->oniblue()->red('Text');
*
* Supported colors:
* black, red, green, yellow, blue, purple, cyan, white, iblack, ired,
* igreen, iyellow, iblue, ipurple, icyan, iwhite
*
* Supported text styles:
* bold, underline, blink, reverse
*
*/
class AnsiColor {
public function __construct() {
if (!(defined('STDERR') && posix_isatty(STDERR))) {
throw new DisplayException('Colored output not supported');
}
}
private $color_opts = [
'black' => '30',
'red' => '31',
'green' => '32',
'yellow' => '33',
'blue' => '34',
'purple' => '35',
'cyan' => '36',
'white' => '37',
'iblack' => '90',
'ired' => '91',
'igreen' => '92',
'iyellow' => '93',
'iblue' => '94',
'ipurple' => '95',
'icyan' => '96',
'iwhite' => '97',
];
private $text_opts = [
'bold' => '1',
'underline' => '4',
'blink' => '5',
'reverse' => '7',
];
private $seq = '';
public function __call($name, $args) {
if (count($args) > 1) {
throw new InvalidArgumentException("$name expects 0 or 1 arguments");
}
$bg = false;
if (strpos($name, 'on') === 0) {
$bg = true;
$name = substr($name, 2);
}
if (isset($this->color_opts[$name])) {
if ($bg) {
$color = intval($this->color_opts[$name]) + 10;
$this->seq .= sprintf("\033[%sm", $color);
} else {
$this->seq .= sprintf("\033[%sm", $this->color_opts[$name]);
}
} else if (isset($this->text_opts[$name])) {
$this->seq .= sprintf("\033[%sm", $this->text_opts[$name]);
} else {
throw new BadMethodCallException('Function name must be in $color_opts or $text_opts');
}
if (count($args) == 1) {
$this->seq .= $args[0];
}
return $this;
}
public function __toString() {
$seq = $this->seq."\033[0m";
$this->seq = '';
return $seq;
}
}
class DisplayException extends Exception {};