forked from adhocore/php-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColor.php
285 lines (240 loc) · 8.28 KB
/
Color.php
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
/*
* This file is part of the PHP-CLI package.
*
* (c) Jitendra Adhikari <[email protected]>
* <https://github.com/adhocore>
*
* Licensed under MIT license.
*/
namespace Ahc\Cli\Output;
use Ahc\Cli\Exception\InvalidArgumentException;
use Ahc\Cli\Helper\InflectsString;
use function array_intersect_key;
use function constant;
use function defined;
use function lcfirst;
use function method_exists;
use function preg_match_all;
use function str_ireplace;
use function str_replace;
use function stripos;
use function strtolower;
use function strtoupper;
use function strtr;
use const PHP_EOL;
/**
* Cli Colorizer.
*
* @author Jitendra Adhikari <[email protected]>
* @license MIT
*
* @link static https://github.com/adhocore/cli
*/
class Color
{
use InflectsString;
const BLACK = 30;
const RED = 31;
const GREEN = 32;
const YELLOW = 33;
const BLUE = 34;
const PURPLE = 35;
const CYAN = 36;
const WHITE = 37;
const GRAY = 47;
const DARKGRAY = 100;
protected string $format = "\033[:mod:;:fg:;:bg:m:txt:\033[0m";
/** @var array Custom styles */
protected static array $styles = [
'answer' => ['fg' => 37, 'mod' => 2],
'choice' => ['fg' => 36],
'comment' => ['fg' => 37, 'mod' => 2],
'error' => ['fg' => 31],
'help_category' => ['fg' => 32, 'mod' => 1],
'help_description_even' => ['fg' => 37, 'mod' => 2],
'help_description_odd' => ['fg' => 37, 'mod' => 2],
'help_example' => ['fg' => 33],
'help_footer' => ['fg' => 33],
'help_group' => ['fg' => 33, 'mod' => 1],
'help_header' => ['fg' => 37, 'mod' => 1],
'help_item_even' => ['fg' => 37, 'mod' => 1],
'help_item_odd' => ['fg' => 37, 'mod' => 1],
'help_summary' => ['fg' => 37, 'mod' => 2],
'help_text' => ['fg' => 37, 'mod' => 1],
'info' => ['fg' => 34],
'logo' => ['fg' => 37],
'ok' => ['fg' => 32],
'question' => ['fg' => 33],
'version' => ['fg' => 37, 'mod' => 1],
'warn' => ['fg' => 33],
];
/**
* Returns a line formatted as comment.
*/
public function comment(string $text, array $style = []): string
{
return $this->line($text, static::$styles['comment'] + $style);
}
/**
* Returns a line formatted as comment.
*/
public function error(string $text, array $style = []): string
{
return $this->line($text, static::$styles['error'] + $style);
}
/**
* Returns a line formatted as ok msg.
*/
public function ok(string $text, array $style = []): string
{
return $this->line($text, static::$styles['ok'] + $style);
}
/**
* Returns a line formatted as warning.
*/
public function warn(string $text, array $style = []): string
{
return $this->line($text, static::$styles['warn'] + $style);
}
/**
* Returns a line formatted as info.
*/
public function info(string $text, array $style = []): string
{
return $this->line($text, static::$styles['info'] + $style);
}
/**
* Returns the color code for a 256 background color.
*/
public static function bg256(int $code): string
{
return "48;5;{$code}";
}
/**
* Returns the color code for a 256 foreground color.
*/
public static function fg256(int $code): string
{
return "38;5;{$code}";
}
/**
* Returns a formatted/colored line.
*/
public function line(string $text, array $style = []): string
{
$style += ['bg' => null, 'fg' => static::WHITE, 'bold' => 0, 'mod' => null];
$format = $style['bg'] === null
? str_replace(';:bg:', '', $this->format)
: $this->format;
$line = strtr($format, [
':mod:' => (int) ($style['mod'] ?? $style['bold']),
':fg:' => $style['fg'],
':bg:' => is_int($style['bg']) ? ($style['bg'] + 10) : $style['bg'],
':txt:' => $text,
]);
return $line;
}
/**
* Prepare a multi colored string with html like tags.
*
* Example: "<errorBold>Text</end><eol/><bgGreenBold>Text</end><eol>"
*/
public function colors(string $text): string
{
$text = str_replace(['<eol>', '<eol/>', '</eol>', "\r\n", "\n"], '__PHP_EOL__', $text);
if (!preg_match_all('/<(\w+)>(.*?)<\/end>/', $text, $matches)) {
return str_replace('__PHP_EOL__', PHP_EOL, $text);
}
$end = "\033[0m";
$text = str_replace(['<end>', '</end>'], $end, $text);
foreach ($matches[1] as $i => $method) {
$part = str_replace($end, '', $this->{$method}(''));
$text = str_replace("<$method>", $part, $text);
}
return str_replace('__PHP_EOL__', PHP_EOL, $text);
}
/**
* Register a custom style.
*
* @param string $name Example: 'alert'
* @param array $style Example: ['fg' => Color::RED, 'bg' => Color::YELLOW, 'bold' => 1]
*
* @return void
*/
public static function style(string $name, array $style): void
{
$allow = ['fg' => true, 'bg' => true, 'bold' => true];
$style = array_intersect_key($style, $allow);
if (empty($style)) {
throw new InvalidArgumentException(self::translate('usingInvalidStyle'));
}
$invisible = (isset($style['bg']) && isset($style['fg']) && $style['bg'] === $style['fg']);
if ($invisible && method_exists(static::class, $name)) {
throw new InvalidArgumentException(self::translate('styleInvisible'));
}
static::$styles[$name] = $style;
}
/**
* Magically build styles.
*
* @param string $name Example: 'boldError', 'bgGreenBold' etc
* @param array $arguments
*
* @return string
*/
public function __call(string $name, array $arguments): string
{
if (!isset($arguments[0])) {
throw new InvalidArgumentException($this->translate('textRequired'));
}
[$name, $text, $style] = $this->parseCall($name, $arguments);
if (isset(static::$styles[$name])) {
return $this->line($text, static::$styles[$name] + $style);
}
if (defined($color = static::class . '::' . strtoupper($name))) {
$name = 'line';
$style += ['fg' => constant($color)];
}
if (!method_exists($this, $name)) {
throw new InvalidArgumentException($this->translate('undefinedStyle', [$name]));
}
return $this->{$name}($text, $style);
}
/**
* Parse the name argument pairs to determine callable method and style params.
*/
protected function parseCall(string $name, array $arguments): array
{
[$text, $style] = $arguments + ['', []];
$mods = ['bold' => 1, 'dim' => 2, 'italic' => 3, 'underline' => 4, 'flash' => 5];
foreach ($mods as $mod => $value) {
if (stripos($name, $mod) !== false) {
$name = str_ireplace($mod, '', $name);
$style += ['bold' => $value];
}
}
if (isset(static::$styles[strtolower($name)])) {
$name = strtolower($name);
}
if (!preg_match_all('/([b|B|f|F]g)?([A-Z][a-z]+)([^A-Z])?/', $name, $matches)) {
return [lcfirst($name) ?: 'line', $text, $style];
}
[$name, $style] = $this->buildStyle($name, $style, $matches);
return [$name, $text, $style];
}
/**
* Build style parameter from matching combination.
*/
protected function buildStyle(string $name, array $style, array $matches): array
{
foreach ($matches[0] as $i => $match) {
$name = str_replace($match, '', $name);
$type = strtolower($matches[1][$i]) ?: 'fg';
if (defined($color = static::class . '::' . strtoupper($matches[2][$i]))) {
$style += [$type => constant($color)];
}
}
return [lcfirst($name) ?: 'line', $style];
}
}