-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCLI.php
432 lines (414 loc) · 13.3 KB
/
CLI.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php declare(strict_types=1);
/*
* This file is part of Aplus Framework CLI Library.
*
* (c) Natan Felles <natanfelles@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Framework\CLI;
use Framework\CLI\Styles\BackgroundColor;
use Framework\CLI\Styles\ForegroundColor;
use Framework\CLI\Styles\Format;
use JetBrains\PhpStorm\Pure;
use Stringable;
use ValueError;
/**
* Class CLI.
*
* @see https://en.wikipedia.org/wiki/ANSI_escape_code
*
* @package cli
*/
class CLI
{
protected static string $reset = "\033[0m";
/**
* Tells if it is running on a Windows OS.
*
* @return bool
*/
#[Pure]
public static function isWindows() : bool
{
return \PHP_OS_FAMILY === 'Windows';
}
/**
* Get the screen width.
*
* @param int $default
*
* @return int
*/
public static function getWidth(int $default = 80) : int
{
if (static::isWindows()) {
return $default;
}
$width = (int) \shell_exec('tput cols');
if (!$width) {
return $default;
}
return $width;
}
/**
* Displays text wrapped to a certain width.
*
* @param string $text
* @param int|null $width
*
* @return string Returns the wrapped text
*/
public static function wrap(string $text, ?int $width = null) : string
{
$width ??= static::getWidth();
return \wordwrap($text, $width, \PHP_EOL, true);
}
/**
* Calculate the multibyte length of a text without style characters.
*
* @param string $text The text being checked for length
*
* @return int
*/
public static function strlen(string $text) : int
{
$codes = [];
foreach (ForegroundColor::cases() as $case) {
$codes[] = $case->getCode();
}
foreach (BackgroundColor::cases() as $case) {
$codes[] = $case->getCode();
}
foreach (Format::cases() as $case) {
$codes[] = $case->getCode();
}
$codes[] = static::$reset;
$text = \str_replace($codes, '', $text);
return \mb_strlen($text);
}
/**
* Applies styles to a text.
*
* @param string $text The text to be styled
* @param ForegroundColor|string|null $color Foreground color
* @param BackgroundColor|string|null $background Background color
* @param array<Format|string> $formats The text formats
*
* @throws ValueError For invalid color, background or format
*
* @return string Returns the styled text
*/
public static function style(
string $text,
ForegroundColor | string | null $color = null,
BackgroundColor | string | null $background = null,
array $formats = []
) : string {
$string = '';
if ($color !== null) {
$string = \is_string($color)
? ForegroundColor::from($color)->getCode()
: $color->getCode();
}
if ($background !== null) {
$string .= \is_string($background)
? BackgroundColor::from($background)->getCode()
: $background->getCode();
}
if ($formats) {
foreach ($formats as $format) {
$string .= \is_string($format)
? Format::from($format)->getCode()
: $format->getCode();
}
}
$string .= $text . static::$reset;
return $string;
}
/**
* Write a text in the output.
*
* Optionally with styles and width wrapping.
*
* @param string $text The text to be written
* @param ForegroundColor|string|null $color Foreground color
* @param BackgroundColor|string|null $background Background color
* @param int|null $width Width to wrap the text. Null to do not wrap.
*/
public static function write(
string $text,
ForegroundColor | string | null $color = null,
BackgroundColor | string | null $background = null,
?int $width = null
) : void {
if ($width !== null) {
$text = static::wrap($text, $width);
}
if ($color !== null || $background !== null) {
$text = static::style($text, $color, $background);
}
\fwrite(\STDOUT, $text . \PHP_EOL);
}
/**
* Prints a new line in the output.
*
* @param int $lines Number of lines to be printed
*/
public static function newLine(int $lines = 1) : void
{
for ($i = 0; $i < $lines; $i++) {
\fwrite(\STDOUT, \PHP_EOL);
}
}
/**
* Creates a "live line".
*
* Erase the current line, move the cursor to the beginning of the line and
* writes a text.
*
* @param string $text The text to be written
* @param bool $finalize If true the "live line" activity ends, creating a
* new line after the text
*/
public static function liveLine(string $text, bool $finalize = false) : void
{
// See: https://stackoverflow.com/a/35190285
$string = '';
if (!static::isWindows()) {
$string .= "\33[2K";
}
$string .= "\r";
$string .= $text;
if ($finalize) {
$string .= \PHP_EOL;
}
\fwrite(\STDOUT, $string);
}
/**
* Performs audible beep alarms.
*
* @param int $times How many times should the beep be played
* @param int $usleep Interval in microseconds
*/
public static function beep(int $times = 1, int $usleep = 0) : void
{
for ($i = 0; $i < $times; $i++) {
\fwrite(\STDOUT, "\x07");
\usleep($usleep);
}
}
/**
* Writes a message box.
*
* @param array<int,string>|string $lines One line as string or multi-lines as array
* @param BackgroundColor|string $background Background color
* @param ForegroundColor|string $color Foreground color
*/
public static function box(
array | string $lines,
BackgroundColor | string $background = BackgroundColor::black,
ForegroundColor | string $color = ForegroundColor::white
) : void {
$width = static::getWidth();
$width -= 2;
if (!\is_array($lines)) {
$lines = [
$lines,
];
}
$allLines = [];
foreach ($lines as &$line) {
$length = static::strlen($line);
if ($length > $width) {
$line = static::wrap($line, $width);
}
foreach (\explode(\PHP_EOL, $line) as $subLine) {
$allLines[] = $subLine;
}
}
unset($line);
$blankLine = \str_repeat(' ', $width + 2);
$text = static::style($blankLine, $color, $background);
foreach ($allLines as $line) {
$end = \str_repeat(' ', $width - static::strlen($line)) . ' ';
$end = static::style($end, $color, $background);
$text .= static::style(' ' . $line . $end, $color, $background);
}
$text .= static::style($blankLine, $color, $background);
static::write($text);
}
/**
* Writes a message to STDERR and optionally exit with a custom code.
*
* @param string $message The error message
* @param int|null $exitCode Set null to do not exit
*/
public static function error(string $message, ?int $exitCode = 1) : void
{
static::beep();
\fwrite(\STDERR, static::style($message, ForegroundColor::red) . \PHP_EOL);
if ($exitCode !== null) {
exit($exitCode);
}
}
/**
* Clear the terminal screen.
*/
public static function clear() : void
{
\fwrite(\STDOUT, "\e[H\e[2J");
}
/**
* Get user input.
*
* NOTE: It is possible pass multiple lines ending each line with a backslash.
*
* @param string $prepend Text prepended in the input. Used internally to
* allow multiple lines
*
* @return string Returns the user input
*/
public static function getInput(string $prepend = '') : string
{
$input = \fgets(\STDIN);
$input = $input === false ? '' : \trim($input);
$prepend .= $input;
$eolPos = false;
if ($prepend) {
$eolPos = \strrpos($prepend, '\\', -1);
}
if ($eolPos !== false) {
$prepend = \substr_replace($prepend, \PHP_EOL, $eolPos);
$prepend = static::getInput($prepend);
}
return $prepend;
}
/**
* Prompt a question.
*
* @param string $question The question to prompt
* @param array<int,string>|string|null $options Answer options. If an array
* is set, the default answer is the first value. If is a string, it will
* be the default.
*
* @return string The answer
*/
public static function prompt(string $question, array | string | null $options = null) : string
{
if ($options !== null) {
$options = \is_array($options)
? \array_values($options)
: [$options];
}
if ($options) {
$opt = $options;
$opt[0] = static::style($opt[0], null, null, [Format::bold]);
$optionsText = isset($opt[1])
? \implode(', ', $opt)
: $opt[0];
$question .= ' [' . $optionsText . ']';
}
$question .= ': ';
\fwrite(\STDOUT, $question);
$answer = static::getInput();
if ($answer === '' && isset($options[0])) {
$answer = $options[0];
}
return $answer;
}
/**
* Prompt a question with secret answer.
*
* @param string $question The question to prompt
*
* @see https://dev.to/mykeels/reading-passwords-from-stdin-in-php-1np9
*
* @return string The secret answer
*/
public static function secret(string $question) : string
{
$question .= ': ';
\fwrite(\STDOUT, $question);
\exec('stty -echo');
$secret = \trim((string) \fgets(\STDIN));
\exec('stty echo');
return $secret;
}
/**
* Creates a well formatted table.
*
* @param array<array<Stringable|scalar>> $tbody Table body rows
* @param array<Stringable|scalar> $thead Table head fields
*/
public static function table(array $tbody, array $thead = []) : void
{
// All the rows in the table will be here until the end
$tableRows = [];
// We need only indexes and not keys
if (!empty($thead)) {
$tableRows[] = \array_values($thead);
}
foreach ($tbody as $tr) {
// cast tr to array if is not - (objects...)
$tableRows[] = \array_values((array) $tr);
}
// Yes, it really is necessary to know this count
$totalRows = \count($tableRows);
// Store all columns lengths
// $allColsLengths[row][column] = length
$allColsLengths = [];
// Store maximum lengths by column
// $maxColsLengths[column] = length
$maxColsLengths = [];
// Read row by row and define the longest columns
for ($row = 0; $row < $totalRows; $row++) {
$column = 0; // Current column index
foreach ($tableRows[$row] as $col) {
// Sets the size of this column in the current row
$allColsLengths[$row][$column] = static::strlen((string) $col);
// If the current column does not have a value among the larger ones
// or the value of this is greater than the existing one
// then, now, this assumes the maximum length
if (!isset($maxColsLengths[$column])
|| $allColsLengths[$row][$column] > $maxColsLengths[$column]) {
$maxColsLengths[$column] = $allColsLengths[$row][$column];
}
// We can go check the size of the next column...
$column++;
}
}
// Read row by row and add spaces at the end of the columns
// to match the exact column length
for ($row = 0; $row < $totalRows; $row++) {
$column = 0;
foreach ($tableRows[$row] as $col => $value) {
$diff = $maxColsLengths[$column] - $allColsLengths[$row][$col];
if ($diff) {
$tableRows[$row][$column] .= \str_repeat(' ', $diff);
}
$column++;
}
}
$table = $line = '';
// Joins columns and append the well formatted rows to the table
foreach ($tableRows as $row => $value) {
// Set the table border-top
if ($row === 0) {
$line = '+';
foreach (\array_keys($value) as $col) {
$line .= \str_repeat('-', $maxColsLengths[$col] + 2) . '+';
}
$table .= $line . \PHP_EOL;
}
// Set the vertical borders
$table .= '| ' . \implode(' | ', $value) . ' |' . \PHP_EOL;
// Set the thead and table borders-bottom
if (($row === 0 && !empty($thead)) || $row + 1 === $totalRows) {
$table .= $line . \PHP_EOL;
}
}
\fwrite(\STDOUT, $table);
}
}