TShellWriter   F
last analyzed

Complexity

Total Complexity 89

Size/Duplication

Total Lines 590
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 195
c 3
b 1
f 0
dl 0
loc 590
rs 2
wmc 89

35 Methods

Rating   Name   Duplication   Size   Complexity  
B pad() 0 22 8
A format() 0 9 3
A unformat() 0 3 1
B tableWidget() 0 42 11
A clearScreenAfterCursor() 0 3 1
A hideCursor() 0 3 1
A setWriter() 0 3 1
A clearScreenBeforeCursor() 0 3 1
A scrollDown() 0 3 1
A setColorSupported() 0 3 1
A moveCursorUp() 0 3 1
A saveCursorPosition() 0 3 1
A writeError() 0 11 2
A writeLine() 0 13 6
A wrapText() 0 18 5
A __construct() 0 5 1
A clearLineAfterCursor() 0 3 1
B isColorSupported() 0 23 8
A getWriter() 0 3 1
C getScreenSize() 0 42 13
A moveCursorNextLine() 0 3 1
A clearScreen() 0 3 1
A moveCursorPrevLine() 0 3 1
A flush() 0 3 1
A moveCursorForward() 0 3 1
A write() 0 11 6
A clearLineBeforeCursor() 0 3 1
A getColorSupported() 0 3 1
A showCursor() 0 3 1
A moveCursorDown() 0 3 1
A moveCursorTo() 0 6 2
A moveCursorBackward() 0 3 1
A restoreCursorPosition() 0 3 1
A scrollUp() 0 3 1
A clearLine() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like TShellWriter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TShellWriter, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * TShellWriter class file
5
 *
6
 * @author Brad Anderson <[email protected]>
7
 * @link https://github.com/pradosoft/prado
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 */
10
11
namespace Prado\Shell;
12
13
use Prado\IO\TStdOutWriter;
14
use Prado\TPropertyValue;
15
use Prado\Util\Helpers\TProcessHelper;
16
17
/**
18
 * TShellWriter class.
19
 *
20
 * Similar to the {@see \Prado\Web\UI\THtmlWriter}, the TShellWriter writes and formats text
21
 * with color, and processes other commands to the terminal to another ITextWriter.
22
 *
23
 * @author Brad Anderson <[email protected]>
24
 * @since 4.2.0
25
 */
26
class TShellWriter extends \Prado\TComponent implements \Prado\IO\ITextWriter
27
{
28
	public const BOLD = 1;
29
	public const DARK = 2;
30
	public const ITALIC = 3;
31
	public const UNDERLINE = 4;
32
	public const BLINK = 5;
33
	public const REVERSE = 7;
34
	public const CONCEALED = 8;
35
	public const CROSSED = 9;
36
	public const FRAMED = 51;
37
	public const ENCIRCLED = 52;
38
	public const OVERLINED = 53;
39
40
	public const BLACK = 30;
41
	public const RED = 31;
42
	public const GREEN = 32;
43
	public const YELLOW = 33;
44
	public const BLUE = 34;
45
	public const MAGENTA = 35;
46
	public const CYAN = 36;
47
	public const LIGHT_GRAY = 37;
48
	// '256' => '38', //  38:2:<red>:<green>:<blue> or 38:5:<256-color>
49
	public const DEFAULT = 39;
50
51
	public const DARK_GRAY = 90;
52
	public const LIGHT_RED = 91;
53
	public const LIGHT_GREEN = 92;
54
	public const LIGHT_YELLOW = 93;
55
	public const LIGHT_BLUE = 94;
56
	public const LIGHT_MAGENTA = 95;
57
	public const LIGHT_CYAN = 96;
58
	public const WHITE = 97;
59
60
	public const BG_BLACK = 40;
61
	public const BG_RED = 41;
62
	public const BG_GREEN = 42;
63
	public const BG_YELLOW = 43;
64
	public const BG_BLUE = 44;
65
	public const BG_MAGENTA = 45;
66
	public const BG_CYAN = 46;
67
	public const BG_LIGHT_GRAY = 47;
68
	//'256' => '48', // 48:2:<red>:<green>:<blue>   48:5:<256-color>
69
	public const BG_DEFAULT = 49;
70
71
	public const BG_DARK_GRAY = 100;
72
	public const BG_LIGHT_RED = 101;
73
	public const BG_LIGHT_GREEN = 102;
74
	public const BG_LIGHT_YELLOW = 103;
75
	public const BG_LIGHT_BLUE = 104;
76
	public const BG_LIGHT_MAGENTA = 105;
77
	public const BG_LIGHT_CYAN = 106;
78
	public const BG_WHITE = 107;
79
80
	/**
81
	 * @var \Prado\IO\ITextWriter writer
82
	 */
83
	protected $_writer;
84
85
	/** @var bool is color supported on tty */
86
	protected $_color;
87
88
	/**
89
	 * Constructor.
90
	 * @param \Prado\IO\ITextWriter $writer a writer that THtmlWriter will pass its rendering result to
91
	 */
92
	public function __construct($writer)
93
	{
94
		$this->_writer = $writer;
95
		$this->_color = $this->isColorSupported();
96
		parent::__construct();
97
	}
98
99
	/**
100
	 * @return bool is color supported
101
	 */
102
	public function getColorSupported()
103
	{
104
		return $this->_color;
105
	}
106
107
	/**
108
	 * @param bool $color is color supported
109
	 */
110
	public function setColorSupported($color)
111
	{
112
		$this->_color = TPropertyValue::ensureBoolean($color);
113
	}
114
115
	/**
116
	 * @return \Prado\IO\ITextWriter the writer output to this class
117
	 */
118
	public function getWriter()
119
	{
120
		return $this->_writer;
121
	}
122
123
	/**
124
	 * @param \Prado\IO\ITextWriter $writer the writer output to this class
125
	 */
126
	public function setWriter($writer)
127
	{
128
		$this->_writer = $writer;
129
	}
130
131
	/**
132
	 * Flushes the rendering result.
133
	 * This will invoke the underlying writer's flush method.
134
	 * @return string the content being flushed
135
	 */
136
	public function flush()
137
	{
138
		return $this->_writer->flush();
139
	}
140
141
	/**
142
	 * Renders a string.
143
	 * @param string $str string to be rendered
144
	 * @param null|mixed $attr
145
	 */
146
	public function write($str, $attr = null)
147
	{
148
		if ($this->_color && $attr) {
149
			if (!is_array($attr)) {
150
				$attr = [$attr];
151
			}
152
			$this->_writer->write("\033[" . implode(';', $attr) . 'm');
153
		}
154
		$this->_writer->write($str);
155
		if ($this->_color && $attr) {
156
			$this->_writer->write("\033[0m");
157
		}
158
	}
159
160
	/**
161
	 * Renders a string and appends a newline to it.
162
	 * @param string $str string to be rendered
163
	 * @param null|mixed $attr
164
	 */
165
	public function writeLine($str = '', $attr = null)
166
	{
167
		if ($this->_color && $attr) {
168
			if (!is_array($attr)) {
169
				$attr = [$attr];
170
			}
171
			$this->_writer->write("\033[" . implode(';', $attr) . 'm');
172
		}
173
		$this->_writer->write($str);
174
		if ($this->_color && $attr) {
175
			$this->_writer->write("\033[0m");
176
		}
177
		$this->_writer->write("\n");
178
	}
179
180
	/**
181
	 * Writes an error block to the writer with color
182
	 * @param string $text
183
	 */
184
	public function writeError($text)
185
	{
186
		$len = 78;
187
		$lines = explode("\n", wordwrap($text, $len - 4, "\n"));
188
		$this->writeLine();
189
		$this->writeLine("*" . str_pad(' Error ', $len, '-', STR_PAD_BOTH) . "*", [self::BG_RED, self::WHITE, self::BOLD]);
190
		foreach ($lines as $i => $line) {
191
			$this->writeLine('*  ' . str_pad($line, $len - 4, ' ', STR_PAD_BOTH) . '  *', [self::BG_RED, self::WHITE, self::BOLD]);
192
		}
193
		$this->writeLine('*' . str_repeat('-', $len) . "*", [self::BG_RED, self::WHITE, self::BOLD]);
194
		$this->writeLine();
195
	}
196
197
	/**
198
	 * @param string $str the string to ANSI format.
199
	 * @param mixed $len
200
	 * @param mixed $pad
201
	 * @param mixed $place
202
	 * @return string $str in the format of $attr.
203
	 */
204
	public function pad($str, $len, $pad = ' ', $place = STR_PAD_RIGHT)
205
	{
206
		$len -= strlen($this->unformat($str));
207
		$pad = $pad[0];
208
		if ($place === STR_PAD_RIGHT) {
209
			while ($len-- > 0) {
210
				$str .= $pad;
211
			}
212
		} elseif ($place === STR_PAD_LEFT) {
213
			while ($len-- > 0) {
214
				$str = $pad . $str;
215
			}
216
		} elseif ($place === STR_PAD_BOTH) {
217
			while ($len-- > 0) {
218
				if ($len % 2) {
219
					$str .= $pad;
220
				} else {
221
					$str = $pad . $str;
222
				}
223
			}
224
		}
225
		return $str;
226
	}
227
228
	/**
229
	 * renders a table widget.
230
	 * ```php
231
	 *  $writer->tableWidget(
232
	 *		'headers' => ['title 1', 'title 2', 'count'],
233
	 *		'rows' => [['a', 'b', 1], ['s', 't', 2], ['c', 'd', 3], ['e', 'f', 10],
234
	 *			['span' => 'text spanning all columns']]
235
	 * );
236
	 * ```
237
	 *
238
	 * @param array $table
239
	 */
240
	public function tableWidget($table)
241
	{
242
		$lengths = [];
243
244
		foreach ($table['headers'] ?? $table['rows'][0] as $i => $header) {
245
			$lengths[$i] = strlen($this->unformat($header)) + 1;
246
			foreach ($table['rows'] as $row => $data) {
247
				if (isset($data['span'])) {
248
					continue;
249
				}
250
				$len = strlen($this->unformat($data[$i])) + 1;
251
				if ($lengths[$i] < $len) {
252
					$lengths[$i] = $len;
253
				}
254
			}
255
		}
256
		$str = '';
257
258
		if (isset($table['headers'])) {
259
			foreach ($table['headers'] as $i => $header) {
260
				$str .= $this->pad($this->format($header, [TShellWriter::UNDERLINE]), $lengths[$i], ' ', STR_PAD_RIGHT);
261
			}
262
			$str .= PHP_EOL;
263
		}
264
		$last = count($table['headers'] ?? $table['rows'][0]) - 1;
265
		foreach ($table['rows'] as $row => $data) {
266
			$lastcolumn = 0;
267
			if (isset($data['span'])) {
268
				$str .= $data['span'];
269
			} else {
270
				foreach ($data as $i => $value) {
271
					if ($last == $i) {
272
						$str .= $this->wrapText($value, $lastcolumn);
273
					} else {
274
						$lastcolumn += $lengths[$i];
275
						$str .= $this->pad($value, $lengths[$i]);
276
					}
277
				}
278
			}
279
			$str .= PHP_EOL;
280
		}
281
		return $str;
282
	}
283
	/**
284
	 * @param string $str the string to ANSI format.
285
	 * @param string|string[] $attr the attributes to format.
286
	 * @return string $str in the format of $attr.
287
	 */
288
	public function format($str, $attr)
289
	{
290
		if (!$this->_color) {
291
			return $str;
292
		}
293
		if (!is_array($attr)) {
294
			$attr = [$attr];
295
		}
296
		return "\033[" . implode(';', $attr) . 'm' . $str . "\033[0m";
297
	}
298
299
	/**
300
	 * removes ANSI formatting
301
	 * @param mixed $str
302
	 */
303
	public function unformat($str)
304
	{
305
		return preg_replace("/\033\[[\?\d;:]*[usmA-HJKSTlh]/", '', $str ?? '');
306
	}
307
308
	/**
309
	 * is color TTY supported
310
	 * @return bool color is supported
311
	 */
312
	protected function isColorSupported()
313
	{
314
		static $hasColor = null;
315
316
		if ($hasColor === null) {
317
			if (TProcessHelper::isSystemWindows()) {
318
				return getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON';
319
			}
320
321
			if ($hasStdOut = !defined('STDOUT')) {
322
				$stdOut = fopen(TStdOutWriter::STDOUT_URI, 'wb');
323
			} else {
324
				$stdOut = STDOUT;
325
			}
326
327
			$hasColor = function_exists('posix_isatty') && @posix_isatty($stdOut) && strpos(getenv('TERM'), '256color') !== false;
328
329
			if ($hasStdOut) {
330
				fclose($stdOut);
331
			}
332
		}
333
334
		return $hasColor;
335
	}
336
337
	/**
338
	 * Moves the terminal cursor up by sending ANSI control code CUU to the terminal.
339
	 * If the cursor is already at the edge of the screen, this has no effect.
340
	 * @param int $rows number of rows the cursor should be moved up
341
	 */
342
	public function moveCursorUp($rows = 1)
343
	{
344
		$this->_writer->write("\033[" . (int) $rows . 'A');
345
	}
346
347
	/**
348
	 * Moves the terminal cursor down by sending ANSI control code CUD to the terminal.
349
	 * If the cursor is already at the edge of the screen, this has no effect.
350
	 * @param int $rows number of rows the cursor should be moved down
351
	 */
352
	public function moveCursorDown($rows = 1)
353
	{
354
		$this->_writer->write("\033[" . (int) $rows . 'B');
355
	}
356
357
	/**
358
	 * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal.
359
	 * If the cursor is already at the edge of the screen, this has no effect.
360
	 * @param int $steps number of steps the cursor should be moved forward
361
	 */
362
	public function moveCursorForward($steps = 1)
363
	{
364
		$this->_writer->write("\033[" . (int) $steps . 'C');
365
	}
366
367
	/**
368
	 * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal.
369
	 * If the cursor is already at the edge of the screen, this has no effect.
370
	 * @param int $steps number of steps the cursor should be moved backward
371
	 */
372
	public function moveCursorBackward($steps = 1)
373
	{
374
		$this->_writer->write("\033[" . (int) $steps . 'D');
375
	}
376
377
	/**
378
	 * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.
379
	 * @param int $lines number of lines the cursor should be moved down
380
	 */
381
	public function moveCursorNextLine($lines = 1)
382
	{
383
		$this->_writer->write("\033[" . (int) $lines . 'E');
384
	}
385
386
	/**
387
	 * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.
388
	 * @param int $lines number of lines the cursor should be moved up
389
	 */
390
	public function moveCursorPrevLine($lines = 1)
391
	{
392
		$this->_writer->write("\033[" . (int) $lines . 'F');
393
	}
394
395
	/**
396
	 * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.
397
	 * @param int $column 1-based column number, 1 is the left edge of the screen.
398
	 * @param null|int $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.
399
	 */
400
	public function moveCursorTo($column, $row = null)
401
	{
402
		if ($row === null) {
403
			$this->_writer->write("\033[" . (int) $column . 'G');
404
		} else {
405
			$this->_writer->write("\033[" . (int) $row . ';' . (int) $column . 'H');
406
		}
407
	}
408
409
	/**
410
	 * Scrolls whole page up by sending ANSI control code SU to the terminal.
411
	 * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
412
	 * @param int $lines number of lines to scroll up
413
	 */
414
	public function scrollUp($lines = 1)
415
	{
416
		$this->_writer->write("\033[" . (int) $lines . 'S');
417
	}
418
419
	/**
420
	 * Scrolls whole page down by sending ANSI control code SD to the terminal.
421
	 * New lines are added at the top. This is not supported by ANSI.SYS used in windows.
422
	 * @param int $lines number of lines to scroll down
423
	 */
424
	public function scrollDown($lines = 1)
425
	{
426
		$this->_writer->write("\033[" . (int) $lines . 'T');
427
	}
428
429
	/**
430
	 * Saves the current cursor position by sending ANSI control code SCP to the terminal.
431
	 * Position can then be restored with {@see restoreCursorPosition}.
432
	 */
433
	public function saveCursorPosition()
434
	{
435
		$this->_writer->write("\033[s");
436
	}
437
438
	/**
439
	 * Restores the cursor position saved with {@see saveCursorPosition} by sending ANSI control code RCP to the terminal.
440
	 */
441
	public function restoreCursorPosition()
442
	{
443
		$this->_writer->write("\033[u");
444
	}
445
446
	/**
447
	 * Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.
448
	 * Use {@see showCursor} to bring it back.
449
	 * Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.
450
	 */
451
	public function hideCursor()
452
	{
453
		$this->_writer->write("\033[?25l");
454
	}
455
456
	/**
457
	 * Will show a cursor again when it has been hidden by {@see hideCursor}  by sending ANSI DECTCEM code ?25h to the terminal.
458
	 */
459
	public function showCursor()
460
	{
461
		$this->_writer->write("\033[?25h");
462
	}
463
464
	/**
465
	 * Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal.
466
	 * Cursor position will not be changed.
467
	 * **Note:** ANSI.SYS implementation used in windows will reset cursor position to upper left corner of the screen.
468
	 */
469
	public function clearScreen()
470
	{
471
		$this->_writer->write("\033[2J");
472
	}
473
474
	/**
475
	 * Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.
476
	 * Cursor position will not be changed.
477
	 */
478
	public function clearScreenBeforeCursor()
479
	{
480
		$this->_writer->write("\033[1J");
481
	}
482
483
	/**
484
	 * Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.
485
	 * Cursor position will not be changed.
486
	 */
487
	public function clearScreenAfterCursor()
488
	{
489
		$this->_writer->write("\033[0J");
490
	}
491
492
	/**
493
	 * Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.
494
	 * Cursor position will not be changed.
495
	 */
496
	public function clearLine()
497
	{
498
		$this->_writer->write("\033[2K");
499
	}
500
501
	/**
502
	 * Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.
503
	 * Cursor position will not be changed.
504
	 */
505
	public function clearLineBeforeCursor()
506
	{
507
		$this->_writer->write("\033[1K");
508
	}
509
510
	/**
511
	 * Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.
512
	 * Cursor position will not be changed.
513
	 */
514
	public function clearLineAfterCursor()
515
	{
516
		$this->_writer->write("\033[0K");
517
	}
518
519
520
	/**
521
	 * Returns terminal screen size.
522
	 *
523
	 * Usage:
524
	 *
525
	 * ```php
526
	 * [$width, $height] = TShellWriter::getScreenSize();
527
	 * ```
528
	 *
529
	 * @param bool $refresh whether to force checking and not re-use cached size value.
530
	 * This is useful to detect changing window size while the application is running but may
531
	 * not get up to date values on every terminal.
532
	 * @return array|bool An array of ($width, $height) or false when it was not able to determine size.
533
	 */
534
	public static function getScreenSize($refresh = false)
535
	{
536
		static $size;
537
		if ($size !== null && !$refresh) {
538
			return $size;
539
		}
540
541
		if (TProcessHelper::isSystemWindows()) {
542
			$output = [];
543
			exec('mode con', $output);
544
			if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
545
				return $size = [(int) preg_replace('~\D~', '', $output[4]), (int) preg_replace('~\D~', '', $output[3])];
546
			}
547
		} else {
548
			// try stty if available
549
			$stty = [];
550
			if (exec('stty -a 2>&1', $stty)) {
551
				$stty = implode(' ', $stty);
552
553
				// Linux stty output
554
				if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) {
555
					return $size = [(int) $matches[2], (int) $matches[1]];
556
				}
557
558
				// MacOS stty output
559
				if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) {
560
					return $size = [(int) $matches[2], (int) $matches[1]];
561
				}
562
			}
563
564
			// fallback to tput, which may not be updated on terminal resize
565
			if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
566
				return $size = [$width, $height];
567
			}
568
569
			// fallback to ENV variables, which may not be updated on terminal resize
570
			if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
571
				return $size = [$width, $height];
572
			}
573
		}
574
575
		return $size = false;
576
	}
577
578
	/**
579
	 * Word wrap text with indentation to fit the screen size.
580
	 *
581
	 * If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.
582
	 *
583
	 * The first line will **not** be indented, so `TShellWriter::wrapText("Lorem ipsum dolor sit amet.", 4)` will result in the
584
	 * following output, given the screen width is 16 characters:
585
	 *
586
	 * ```
587
	 * Lorem ipsum
588
	 *     dolor sit
589
	 *     amet.
590
	 * ```
591
	 *
592
	 * @param string $text the text to be wrapped
593
	 * @param int $indent number of spaces to use for indentation.
594
	 * @param bool $refresh whether to force refresh of screen size.
595
	 * This will be passed to {@see getScreenSize}.
596
	 * @return string the wrapped text.
597
	 */
598
	public function wrapText($text, $indent = 0, $refresh = false)
599
	{
600
		$size = static::getScreenSize($refresh);
601
		if ($size === false || $size[0] <= $indent) {
602
			return $text;
603
		}
604
		$pad = str_repeat(' ', $indent);
605
		$lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n"));
606
		$first = true;
607
		foreach ($lines as $i => $line) {
608
			if ($first) {
609
				$first = false;
610
				continue;
611
			}
612
			$lines[$i] = $pad . $line;
613
		}
614
615
		return implode("\n", $lines);
616
	}
617
}
618