Passed
Push — master ( 5c3ee6...2b9323 )
by Alexander
130:11 queued 126:34
created

BaseConsole::ansiStrwidth()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\helpers;
9
10
use Yii;
11
use yii\console\Markdown as ConsoleMarkdown;
12
use yii\base\Model;
13
14
/**
15
 * BaseConsole provides concrete implementation for [[Console]].
16
 *
17
 * Do not use BaseConsole. Use [[Console]] instead.
18
 *
19
 * @author Carsten Brandt <[email protected]>
20
 * @since 2.0
21
 */
22
class BaseConsole
23
{
24
    // foreground color control codes
25
    const FG_BLACK = 30;
26
    const FG_RED = 31;
27
    const FG_GREEN = 32;
28
    const FG_YELLOW = 33;
29
    const FG_BLUE = 34;
30
    const FG_PURPLE = 35;
31
    const FG_CYAN = 36;
32
    const FG_GREY = 37;
33
    // background color control codes
34
    const BG_BLACK = 40;
35
    const BG_RED = 41;
36
    const BG_GREEN = 42;
37
    const BG_YELLOW = 43;
38
    const BG_BLUE = 44;
39
    const BG_PURPLE = 45;
40
    const BG_CYAN = 46;
41
    const BG_GREY = 47;
42
    // fonts style control codes
43
    const RESET = 0;
44
    const NORMAL = 0;
45
    const BOLD = 1;
46
    const ITALIC = 3;
47
    const UNDERLINE = 4;
48
    const BLINK = 5;
49
    const NEGATIVE = 7;
50
    const CONCEALED = 8;
51
    const CROSSED_OUT = 9;
52
    const FRAMED = 51;
53
    const ENCIRCLED = 52;
54
    const OVERLINED = 53;
55
56
57
    /**
58
     * Moves the terminal cursor up by sending ANSI control code CUU to the terminal.
59
     * If the cursor is already at the edge of the screen, this has no effect.
60
     * @param int $rows number of rows the cursor should be moved up
61
     */
62 1
    public static function moveCursorUp($rows = 1)
63
    {
64 1
        echo "\033[" . (int) $rows . 'A';
65 1
    }
66
67
    /**
68
     * Moves the terminal cursor down by sending ANSI control code CUD to the terminal.
69
     * If the cursor is already at the edge of the screen, this has no effect.
70
     * @param int $rows number of rows the cursor should be moved down
71
     */
72 1
    public static function moveCursorDown($rows = 1)
73
    {
74 1
        echo "\033[" . (int) $rows . 'B';
75 1
    }
76
77
    /**
78
     * Moves the terminal cursor forward by sending ANSI control code CUF to the terminal.
79
     * If the cursor is already at the edge of the screen, this has no effect.
80
     * @param int $steps number of steps the cursor should be moved forward
81
     */
82 1
    public static function moveCursorForward($steps = 1)
83
    {
84 1
        echo "\033[" . (int) $steps . 'C';
85 1
    }
86
87
    /**
88
     * Moves the terminal cursor backward by sending ANSI control code CUB to the terminal.
89
     * If the cursor is already at the edge of the screen, this has no effect.
90
     * @param int $steps number of steps the cursor should be moved backward
91
     */
92 1
    public static function moveCursorBackward($steps = 1)
93
    {
94 1
        echo "\033[" . (int) $steps . 'D';
95 1
    }
96
97
    /**
98
     * Moves the terminal cursor to the beginning of the next line by sending ANSI control code CNL to the terminal.
99
     * @param int $lines number of lines the cursor should be moved down
100
     */
101 1
    public static function moveCursorNextLine($lines = 1)
102
    {
103 1
        echo "\033[" . (int) $lines . 'E';
104 1
    }
105
106
    /**
107
     * Moves the terminal cursor to the beginning of the previous line by sending ANSI control code CPL to the terminal.
108
     * @param int $lines number of lines the cursor should be moved up
109
     */
110 1
    public static function moveCursorPrevLine($lines = 1)
111
    {
112 1
        echo "\033[" . (int) $lines . 'F';
113 1
    }
114
115
    /**
116
     * Moves the cursor to an absolute position given as column and row by sending ANSI control code CUP or CHA to the terminal.
117
     * @param int $column 1-based column number, 1 is the left edge of the screen.
118
     * @param int|null $row 1-based row number, 1 is the top edge of the screen. if not set, will move cursor only in current line.
119
     */
120 1
    public static function moveCursorTo($column, $row = null)
121
    {
122 1
        if ($row === null) {
123 1
            echo "\033[" . (int) $column . 'G';
124
        } else {
125 1
            echo "\033[" . (int) $row . ';' . (int) $column . 'H';
126
        }
127 1
    }
128
129
    /**
130
     * Scrolls whole page up by sending ANSI control code SU to the terminal.
131
     * New lines are added at the bottom. This is not supported by ANSI.SYS used in windows.
132
     * @param int $lines number of lines to scroll up
133
     */
134 1
    public static function scrollUp($lines = 1)
135
    {
136 1
        echo "\033[" . (int) $lines . 'S';
137 1
    }
138
139
    /**
140
     * Scrolls whole page down by sending ANSI control code SD to the terminal.
141
     * New lines are added at the top. This is not supported by ANSI.SYS used in windows.
142
     * @param int $lines number of lines to scroll down
143
     */
144 1
    public static function scrollDown($lines = 1)
145
    {
146 1
        echo "\033[" . (int) $lines . 'T';
147 1
    }
148
149
    /**
150
     * Saves the current cursor position by sending ANSI control code SCP to the terminal.
151
     * Position can then be restored with [[restoreCursorPosition()]].
152
     */
153 1
    public static function saveCursorPosition()
154
    {
155 1
        echo "\033[s";
156 1
    }
157
158
    /**
159
     * Restores the cursor position saved with [[saveCursorPosition()]] by sending ANSI control code RCP to the terminal.
160
     */
161 1
    public static function restoreCursorPosition()
162
    {
163 1
        echo "\033[u";
164 1
    }
165
166
    /**
167
     * Hides the cursor by sending ANSI DECTCEM code ?25l to the terminal.
168
     * Use [[showCursor()]] to bring it back.
169
     * Do not forget to show cursor when your application exits. Cursor might stay hidden in terminal after exit.
170
     */
171 1
    public static function hideCursor()
172
    {
173 1
        echo "\033[?25l";
174 1
    }
175
176
    /**
177
     * Will show a cursor again when it has been hidden by [[hideCursor()]]  by sending ANSI DECTCEM code ?25h to the terminal.
178
     */
179 1
    public static function showCursor()
180
    {
181 1
        echo "\033[?25h";
182 1
    }
183
184
    /**
185
     * Clears entire screen content by sending ANSI control code ED with argument 2 to the terminal.
186
     * Cursor position will not be changed.
187
     * **Note:** ANSI.SYS implementation used in windows will reset cursor position to upper left corner of the screen.
188
     */
189 1
    public static function clearScreen()
190
    {
191 1
        echo "\033[2J";
192 1
    }
193
194
    /**
195
     * Clears text from cursor to the beginning of the screen by sending ANSI control code ED with argument 1 to the terminal.
196
     * Cursor position will not be changed.
197
     */
198 1
    public static function clearScreenBeforeCursor()
199
    {
200 1
        echo "\033[1J";
201 1
    }
202
203
    /**
204
     * Clears text from cursor to the end of the screen by sending ANSI control code ED with argument 0 to the terminal.
205
     * Cursor position will not be changed.
206
     */
207 1
    public static function clearScreenAfterCursor()
208
    {
209 1
        echo "\033[0J";
210 1
    }
211
212
    /**
213
     * Clears the line, the cursor is currently on by sending ANSI control code EL with argument 2 to the terminal.
214
     * Cursor position will not be changed.
215
     */
216 1
    public static function clearLine()
217
    {
218 1
        echo "\033[2K";
219 1
    }
220
221
    /**
222
     * Clears text from cursor position to the beginning of the line by sending ANSI control code EL with argument 1 to the terminal.
223
     * Cursor position will not be changed.
224
     */
225 1
    public static function clearLineBeforeCursor()
226
    {
227 1
        echo "\033[1K";
228 1
    }
229
230
    /**
231
     * Clears text from cursor position to the end of the line by sending ANSI control code EL with argument 0 to the terminal.
232
     * Cursor position will not be changed.
233
     */
234 1
    public static function clearLineAfterCursor()
235
    {
236 1
        echo "\033[0K";
237 1
    }
238
239
    /**
240
     * Returns the ANSI format code.
241
     *
242
     * @param array $format An array containing formatting values.
243
     * You can pass any of the `FG_*`, `BG_*` and `TEXT_*` constants
244
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
245
     * @return string The ANSI format code according to the given formatting constants.
246
     */
247 5
    public static function ansiFormatCode($format)
248
    {
249 5
        return "\033[" . implode(';', $format) . 'm';
250
    }
251
252
    /**
253
     * Echoes an ANSI format code that affects the formatting of any text that is printed afterwards.
254
     *
255
     * @param array $format An array containing formatting values.
256
     * You can pass any of the `FG_*`, `BG_*` and `TEXT_*` constants
257
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
258
     * @see ansiFormatCode()
259
     * @see endAnsiFormat()
260
     */
261 1
    public static function beginAnsiFormat($format)
262
    {
263 1
        echo "\033[" . implode(';', $format) . 'm';
264 1
    }
265
266
    /**
267
     * Resets any ANSI format set by previous method [[beginAnsiFormat()]]
268
     * Any output after this will have default text format.
269
     * This is equal to calling.
270
     *
271
     * ```php
272
     * echo Console::ansiFormatCode([Console::RESET])
273
     * ```
274
     */
275 1
    public static function endAnsiFormat()
276
    {
277 1
        echo "\033[0m";
278 1
    }
279
280
    /**
281
     * Will return a string formatted with the given ANSI style.
282
     *
283
     * @param string $string the string to be formatted
284
     * @param array $format An array containing formatting values.
285
     * You can pass any of the `FG_*`, `BG_*` and `TEXT_*` constants
286
     * and also [[xtermFgColor]] and [[xtermBgColor]] to specify a format.
287
     * @return string
288
     */
289 24
    public static function ansiFormat($string, $format = [])
290
    {
291 24
        $code = implode(';', $format);
292
293 24
        return "\033[0m" . ($code !== '' ? "\033[" . $code . 'm' : '') . $string . "\033[0m";
294
    }
295
296
    /**
297
     * Returns the ansi format code for xterm foreground color.
298
     *
299
     * You can pass the return value of this to one of the formatting methods:
300
     * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]].
301
     *
302
     * @param int $colorCode xterm color code
303
     * @return string
304
     * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
305
     */
306 1
    public static function xtermFgColor($colorCode)
307
    {
308 1
        return '38;5;' . $colorCode;
309
    }
310
311
    /**
312
     * Returns the ansi format code for xterm background color.
313
     *
314
     * You can pass the return value of this to one of the formatting methods:
315
     * [[ansiFormat]], [[ansiFormatCode]], [[beginAnsiFormat]].
316
     *
317
     * @param int $colorCode xterm color code
318
     * @return string
319
     * @see http://en.wikipedia.org/wiki/Talk:ANSI_escape_code#xterm-256colors
320
     */
321 1
    public static function xtermBgColor($colorCode)
322
    {
323 1
        return '48;5;' . $colorCode;
324
    }
325
326
    /**
327
     * Strips ANSI control codes from a string.
328
     *
329
     * @param string $string String to strip
330
     * @return string
331
     */
332 25
    public static function stripAnsiFormat($string)
333
    {
334 25
        return preg_replace('/\033\[[\d;?]*\w/', '', $string);
335
    }
336
337
    /**
338
     * Returns the length of the string without ANSI color codes.
339
     * @param string $string the string to measure
340
     * @return int the length of the string not counting ANSI format characters
341
     */
342
    public static function ansiStrlen($string)
343
    {
344
        return mb_strlen(static::stripAnsiFormat($string));
345
    }
346
347
    /**
348
     * Returns the width of the string without ANSI color codes.
349
     * @param string $string the string to measure
350
     * @return int the width of the string not counting ANSI format characters
351
     * @since 2.0.36
352
     */
353 15
    public static function ansiStrwidth($string)
354
    {
355 15
        return mb_strwidth(static::stripAnsiFormat($string), Yii::$app->charset);
356
    }
357
358
    /**
359
     * Converts an ANSI formatted string to HTML.
360
     *
361
     * Note: xTerm 256 bit colors are currently not supported.
362
     *
363
     * @param string $string the string to convert.
364
     * @param array $styleMap an optional mapping of ANSI control codes such as
365
     * FG\_*COLOR* or [[BOLD]] to a set of css style definitions.
366
     * The CSS style definitions are represented as an array where the array keys correspond
367
     * to the css style attribute names and the values are the css values.
368
     * values may be arrays that will be merged and imploded with `' '` when rendered.
369
     * @return string HTML representation of the ANSI formatted string
370
     */
371 15
    public static function ansiToHtml($string, $styleMap = [])
372
    {
373
        $styleMap = [
374
            // http://www.w3.org/TR/CSS2/syndata.html#value-def-color
375 15
            self::FG_BLACK => ['color' => 'black'],
376 15
            self::FG_BLUE => ['color' => 'blue'],
377 15
            self::FG_CYAN => ['color' => 'aqua'],
378 15
            self::FG_GREEN => ['color' => 'lime'],
379 15
            self::FG_GREY => ['color' => 'silver'],
380
            // http://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/
381
            // http://dev.w3.org/csswg/css-color/#valuedef-rebeccapurple
382 15
            self::FG_PURPLE => ['color' => 'rebeccapurple'],
383 15
            self::FG_RED => ['color' => 'red'],
384 15
            self::FG_YELLOW => ['color' => 'yellow'],
385 15
            self::BG_BLACK => ['background-color' => 'black'],
386 15
            self::BG_BLUE => ['background-color' => 'blue'],
387 15
            self::BG_CYAN => ['background-color' => 'aqua'],
388 15
            self::BG_GREEN => ['background-color' => 'lime'],
389 15
            self::BG_GREY => ['background-color' => 'silver'],
390 15
            self::BG_PURPLE => ['background-color' => 'rebeccapurple'],
391 15
            self::BG_RED => ['background-color' => 'red'],
392 15
            self::BG_YELLOW => ['background-color' => 'yellow'],
393 15
            self::BOLD => ['font-weight' => 'bold'],
394 15
            self::ITALIC => ['font-style' => 'italic'],
395 15
            self::UNDERLINE => ['text-decoration' => ['underline']],
396 15
            self::OVERLINED => ['text-decoration' => ['overline']],
397 15
            self::CROSSED_OUT => ['text-decoration' => ['line-through']],
398 15
            self::BLINK => ['text-decoration' => ['blink']],
399 15
            self::CONCEALED => ['visibility' => 'hidden'],
400 15
        ] + $styleMap;
401
402 15
        $tags = 0;
403 15
        $result = preg_replace_callback(
404 15
            '/\033\[([\d;]+)m/',
405 15
            function ($ansi) use (&$tags, $styleMap) {
406 14
                $style = [];
407 14
                $reset = false;
408 14
                $negative = false;
409 14
                foreach (explode(';', $ansi[1]) as $controlCode) {
410 14
                    if ($controlCode == 0) {
411 14
                        $style = [];
412 14
                        $reset = true;
413 11
                    } elseif ($controlCode == self::NEGATIVE) {
414 2
                        $negative = true;
415 10
                    } elseif (isset($styleMap[$controlCode])) {
416 14
                        $style[] = $styleMap[$controlCode];
417
                    }
418
                }
419
420 14
                $return = '';
421 14
                while ($reset && $tags > 0) {
422 10
                    $return .= '</span>';
423 10
                    $tags--;
424
                }
425 14
                if (empty($style)) {
426 14
                    return $return;
427
                }
428
429 10
                $currentStyle = [];
430 10
                foreach ($style as $content) {
431 10
                    $currentStyle = ArrayHelper::merge($currentStyle, $content);
432
                }
433
434
                // if negative is set, invert background and foreground
435 10
                if ($negative) {
436 1
                    if (isset($currentStyle['color'])) {
437 1
                        $fgColor = $currentStyle['color'];
438 1
                        unset($currentStyle['color']);
439
                    }
440 1
                    if (isset($currentStyle['background-color'])) {
441 1
                        $bgColor = $currentStyle['background-color'];
442 1
                        unset($currentStyle['background-color']);
443
                    }
444 1
                    if (isset($fgColor)) {
445 1
                        $currentStyle['background-color'] = $fgColor;
446
                    }
447 1
                    if (isset($bgColor)) {
448 1
                        $currentStyle['color'] = $bgColor;
449
                    }
450
                }
451
452 10
                $styleString = '';
453 10
                foreach ($currentStyle as $name => $value) {
454 10
                    if (is_array($value)) {
455 1
                        $value = implode(' ', $value);
456
                    }
457 10
                    $styleString .= "$name: $value;";
458
                }
459 10
                $tags++;
460 10
                return "$return<span style=\"$styleString\">";
461 15
            },
462 15
            $string
463
        );
464 15
        while ($tags > 0) {
465
            $result .= '</span>';
466
            $tags--;
467
        }
468
469 15
        return $result;
470
    }
471
472
    /**
473
     * Converts Markdown to be better readable in console environments by applying some ANSI format.
474
     * @param string $markdown the markdown string.
475
     * @return string the parsed result as ANSI formatted string.
476
     */
477 2
    public static function markdownToAnsi($markdown)
478
    {
479 2
        $parser = new ConsoleMarkdown();
480 2
        return $parser->parse($markdown);
481
    }
482
483
    /**
484
     * Converts a string to ansi formatted by replacing patterns like %y (for yellow) with ansi control codes.
485
     *
486
     * Uses almost the same syntax as https://github.com/pear/Console_Color2/blob/master/Console/Color2.php
487
     * The conversion table is: ('bold' meaning 'light' on some
488
     * terminals). It's almost the same conversion table irssi uses.
489
     * <pre>
490
     *                  text      text            background
491
     *      ------------------------------------------------
492
     *      %k %K %0    black     dark grey       black
493
     *      %r %R %1    red       bold red        red
494
     *      %g %G %2    green     bold green      green
495
     *      %y %Y %3    yellow    bold yellow     yellow
496
     *      %b %B %4    blue      bold blue       blue
497
     *      %m %M %5    magenta   bold magenta    magenta
498
     *      %p %P       magenta (think: purple)
499
     *      %c %C %6    cyan      bold cyan       cyan
500
     *      %w %W %7    white     bold white      white
501
     *
502
     *      %F     Blinking, Flashing
503
     *      %U     Underline
504
     *      %8     Reverse
505
     *      %_,%9  Bold
506
     *
507
     *      %n     Resets the color
508
     *      %%     A single %
509
     * </pre>
510
     * First param is the string to convert, second is an optional flag if
511
     * colors should be used. It defaults to true, if set to false, the
512
     * color codes will just be removed (And %% will be transformed into %)
513
     *
514
     * @param string $string String to convert
515
     * @param bool $colored Should the string be colored?
516
     * @return string
517
     */
518 5
    public static function renderColoredString($string, $colored = true)
519
    {
520
        // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
521 5
        static $conversions = [
522
            '%y' => [self::FG_YELLOW],
523
            '%g' => [self::FG_GREEN],
524
            '%b' => [self::FG_BLUE],
525
            '%r' => [self::FG_RED],
526
            '%p' => [self::FG_PURPLE],
527
            '%m' => [self::FG_PURPLE],
528
            '%c' => [self::FG_CYAN],
529
            '%w' => [self::FG_GREY],
530
            '%k' => [self::FG_BLACK],
531
            '%n' => [0], // reset
532
            '%Y' => [self::FG_YELLOW, self::BOLD],
533
            '%G' => [self::FG_GREEN, self::BOLD],
534
            '%B' => [self::FG_BLUE, self::BOLD],
535
            '%R' => [self::FG_RED, self::BOLD],
536
            '%P' => [self::FG_PURPLE, self::BOLD],
537
            '%M' => [self::FG_PURPLE, self::BOLD],
538
            '%C' => [self::FG_CYAN, self::BOLD],
539
            '%W' => [self::FG_GREY, self::BOLD],
540
            '%K' => [self::FG_BLACK, self::BOLD],
541
            '%N' => [0, self::BOLD],
542
            '%3' => [self::BG_YELLOW],
543
            '%2' => [self::BG_GREEN],
544
            '%4' => [self::BG_BLUE],
545
            '%1' => [self::BG_RED],
546
            '%5' => [self::BG_PURPLE],
547
            '%6' => [self::BG_CYAN],
548
            '%7' => [self::BG_GREY],
549
            '%0' => [self::BG_BLACK],
550
            '%F' => [self::BLINK],
551
            '%U' => [self::UNDERLINE],
552
            '%8' => [self::NEGATIVE],
553
            '%9' => [self::BOLD],
554
            '%_' => [self::BOLD],
555
        ];
556
557 5
        if ($colored) {
558 5
            $string = str_replace('%%', '% ', $string);
559 5
            foreach ($conversions as $key => $value) {
560 5
                $string = str_replace(
561 5
                    $key,
562 5
                    static::ansiFormatCode($value),
563 5
                    $string
564
                );
565
            }
566 5
            $string = str_replace('% ', '%', $string);
567
        } else {
568 1
            $string = preg_replace('/%((%)|.)/', '$2', $string);
569
        }
570
571 5
        return $string;
572
    }
573
574
    /**
575
     * Escapes % so they don't get interpreted as color codes when
576
     * the string is parsed by [[renderColoredString]].
577
     *
578
     * @param string $string String to escape
579
     *
580
     * @return string
581
     */
582
    public static function escape($string)
583
    {
584
        // TODO rework/refactor according to https://github.com/yiisoft/yii2/issues/746
585
        return str_replace('%', '%%', $string);
586
    }
587
588
    /**
589
     * Returns true if the stream supports colorization. ANSI colors are disabled if not supported by the stream.
590
     *
591
     * - windows without ansicon
592
     * - not tty consoles
593
     *
594
     * @param mixed $stream
595
     * @return bool true if the stream supports ANSI colors, otherwise false.
596
     */
597 6
    public static function streamSupportsAnsiColors($stream)
598
    {
599 6
        return DIRECTORY_SEPARATOR === '\\'
600
            ? getenv('ANSICON') !== false || getenv('ConEmuANSI') === 'ON'
601 6
            : function_exists('posix_isatty') && @posix_isatty($stream);
602
    }
603
604
    /**
605
     * Returns true if the console is running on windows.
606
     * @return bool
607
     */
608 1
    public static function isRunningOnWindows()
609
    {
610 1
        return DIRECTORY_SEPARATOR === '\\';
611
    }
612
613
    /**
614
     * Returns terminal screen size.
615
     *
616
     * Usage:
617
     *
618
     * ```php
619
     * list($width, $height) = ConsoleHelper::getScreenSize();
620
     * ```
621
     *
622
     * @param bool $refresh whether to force checking and not re-use cached size value.
623
     * This is useful to detect changing window size while the application is running but may
624
     * not get up to date values on every terminal.
625
     * @return array|bool An array of ($width, $height) or false when it was not able to determine size.
626
     */
627 4
    public static function getScreenSize($refresh = false)
628
    {
629 4
        static $size;
630 4
        if ($size !== null && !$refresh) {
631 4
            return $size;
632
        }
633
634 1
        if (static::isRunningOnWindows()) {
635
            $output = [];
636
            exec('mode con', $output);
637
            if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
638
                return $size = [(int) preg_replace('~\D~', '', $output[4]), (int) preg_replace('~\D~', '', $output[3])];
639
            }
640
        } else {
641
            // try stty if available
642 1
            $stty = [];
643 1
            if (exec('stty -a 2>&1', $stty)) {
644 1
                $stty = implode(' ', $stty);
645
646
                // Linux stty output
647 1
                if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) {
648
                    return $size = [(int) $matches[2], (int) $matches[1]];
649
                }
650
651
                // MacOS stty output
652 1
                if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) {
653
                    return $size = [(int) $matches[2], (int) $matches[1]];
654
                }
655
            }
656
657
            // fallback to tput, which may not be updated on terminal resize
658 1
            if (($width = (int) exec('tput cols 2>&1')) > 0 && ($height = (int) exec('tput lines 2>&1')) > 0) {
659
                return $size = [$width, $height];
660
            }
661
662
            // fallback to ENV variables, which may not be updated on terminal resize
663 1
            if (($width = (int) getenv('COLUMNS')) > 0 && ($height = (int) getenv('LINES')) > 0) {
664
                return $size = [$width, $height];
665
            }
666
        }
667
668 1
        return $size = false;
669
    }
670
671
    /**
672
     * Word wrap text with indentation to fit the screen size.
673
     *
674
     * If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.
675
     *
676
     * The first line will **not** be indented, so `Console::wrapText("Lorem ipsum dolor sit amet.", 4)` will result in the
677
     * following output, given the screen width is 16 characters:
678
     *
679
     * ```
680
     * Lorem ipsum
681
     *     dolor sit
682
     *     amet.
683
     * ```
684
     *
685
     * @param string $text the text to be wrapped
686
     * @param int $indent number of spaces to use for indentation.
687
     * @param bool $refresh whether to force refresh of screen size.
688
     * This will be passed to [[getScreenSize()]].
689
     * @return string the wrapped text.
690
     * @since 2.0.4
691
     */
692 2
    public static function wrapText($text, $indent = 0, $refresh = false)
693
    {
694 2
        $size = static::getScreenSize($refresh);
695 2
        if ($size === false || $size[0] <= $indent) {
696 2
            return $text;
697
        }
698
        $pad = str_repeat(' ', $indent);
699
        $lines = explode("\n", wordwrap($text, $size[0] - $indent, "\n"));
700
        $first = true;
701
        foreach ($lines as $i => $line) {
702
            if ($first) {
703
                $first = false;
704
                continue;
705
            }
706
            $lines[$i] = $pad . $line;
707
        }
708
709
        return implode("\n", $lines);
710
    }
711
712
    /**
713
     * Gets input from STDIN and returns a string right-trimmed for EOLs.
714
     *
715
     * @param bool $raw If set to true, returns the raw string without trimming
716
     * @return string the string read from stdin
717
     */
718
    public static function stdin($raw = false)
719
    {
720
        return $raw ? fgets(\STDIN) : rtrim(fgets(\STDIN), PHP_EOL);
721
    }
722
723
    /**
724
     * Prints a string to STDOUT.
725
     *
726
     * @param string $string the string to print
727
     * @return int|bool Number of bytes printed or false on error
728
     */
729
    public static function stdout($string)
730
    {
731
        return fwrite(\STDOUT, $string);
732
    }
733
734
    /**
735
     * Prints a string to STDERR.
736
     *
737
     * @param string $string the string to print
738
     * @return int|bool Number of bytes printed or false on error
739
     */
740
    public static function stderr($string)
741
    {
742
        return fwrite(\STDERR, $string);
743
    }
744
745
    /**
746
     * Asks the user for input. Ends when the user types a carriage return (PHP_EOL). Optionally, It also provides a
747
     * prompt.
748
     *
749
     * @param string $prompt the prompt to display before waiting for input (optional)
750
     * @return string the user's input
751
     */
752
    public static function input($prompt = null)
753
    {
754
        if (isset($prompt)) {
755
            static::stdout($prompt);
756
        }
757
758
        return static::stdin();
759
    }
760
761
    /**
762
     * Prints text to STDOUT appended with a carriage return (PHP_EOL).
763
     *
764
     * @param string $string the text to print
765
     * @return int|bool number of bytes printed or false on error.
766
     */
767
    public static function output($string = null)
768
    {
769
        return static::stdout($string . PHP_EOL);
770
    }
771
772
    /**
773
     * Prints text to STDERR appended with a carriage return (PHP_EOL).
774
     *
775
     * @param string $string the text to print
776
     * @return int|bool number of bytes printed or false on error.
777
     */
778
    public static function error($string = null)
779
    {
780
        return static::stderr($string . PHP_EOL);
781
    }
782
783
    /**
784
     * Prompts the user for input and validates it.
785
     *
786
     * @param string $text prompt string
787
     * @param array $options the options to validate the input:
788
     *
789
     * - `required`: whether it is required or not
790
     * - `default`: default value if no input is inserted by the user
791
     * - `pattern`: regular expression pattern to validate user input
792
     * - `validator`: a callable function to validate input. The function must accept two parameters:
793
     * - `input`: the user input to validate
794
     * - `error`: the error value passed by reference if validation failed.
795
     *
796
     * @return string the user input
797
     */
798
    public static function prompt($text, $options = [])
799
    {
800
        $options = ArrayHelper::merge(
801
            [
802
                'required' => false,
803
                'default' => null,
804
                'pattern' => null,
805
                'validator' => null,
806
                'error' => 'Invalid input.',
807
            ],
808
            $options
809
        );
810
        $error = null;
811
812
        top:
813
        $input = $options['default']
814
            ? static::input("$text [" . $options['default'] . '] ')
815
            : static::input("$text ");
816
817
        if ($input === '') {
818
            if (isset($options['default'])) {
819
                $input = $options['default'];
820
            } elseif ($options['required']) {
821
                static::output($options['error']);
822
                goto top;
823
            }
824
        } elseif ($options['pattern'] && !preg_match($options['pattern'], $input)) {
825
            static::output($options['error']);
826
            goto top;
827
        } elseif ($options['validator'] &&
828
            !call_user_func_array($options['validator'], [$input, &$error])
829
        ) {
830
            static::output(isset($error) ? $error : $options['error']);
831
            goto top;
832
        }
833
834
        return $input;
835
    }
836
837
    /**
838
     * Asks user to confirm by typing y or n.
839
     *
840
     * A typical usage looks like the following:
841
     *
842
     * ```php
843
     * if (Console::confirm("Are you sure?")) {
844
     *     echo "user typed yes\n";
845
     * } else {
846
     *     echo "user typed no\n";
847
     * }
848
     * ```
849
     *
850
     * @param string $message to print out before waiting for user input
851
     * @param bool $default this value is returned if no selection is made.
852
     * @return bool whether user confirmed
853
     */
854
    public static function confirm($message, $default = false)
855
    {
856
        while (true) {
857
            static::stdout($message . ' (yes|no) [' . ($default ? 'yes' : 'no') . ']:');
858
            $input = trim(static::stdin());
859
860
            if (empty($input)) {
861
                return $default;
862
            }
863
864
            if (!strcasecmp($input, 'y') || !strcasecmp($input, 'yes')) {
865
                return true;
866
            }
867
868
            if (!strcasecmp($input, 'n') || !strcasecmp($input, 'no')) {
869
                return false;
870
            }
871
        }
872
    }
873
874
    /**
875
     * Gives the user an option to choose from. Giving '?' as an input will show
876
     * a list of options to choose from and their explanations.
877
     *
878
     * @param string $prompt the prompt message
879
     * @param array $options Key-value array of options to choose from. Key is what is inputed and used, value is
880
     * what's displayed to end user by help command.
881
     *
882
     * @return string An option character the user chose
883
     */
884
    public static function select($prompt, $options = [])
885
    {
886
        top:
887
        static::stdout("$prompt [" . implode(',', array_keys($options)) . ',?]: ');
888
        $input = static::stdin();
889
        if ($input === '?') {
890
            foreach ($options as $key => $value) {
891
                static::output(" $key - $value");
892
            }
893
            static::output(' ? - Show help');
894
            goto top;
895
        } elseif (!array_key_exists($input, $options)) {
896
            goto top;
897
        }
898
899
        return $input;
900
    }
901
902
    private static $_progressStart;
903
    private static $_progressWidth;
904
    private static $_progressPrefix;
905
    private static $_progressEta;
906
    private static $_progressEtaLastDone = 0;
907
    private static $_progressEtaLastUpdate;
908
909
    /**
910
     * Starts display of a progress bar on screen.
911
     *
912
     * This bar will be updated by [[updateProgress()]] and may be ended by [[endProgress()]].
913
     *
914
     * The following example shows a simple usage of a progress bar:
915
     *
916
     * ```php
917
     * Console::startProgress(0, 1000);
918
     * for ($n = 1; $n <= 1000; $n++) {
919
     *     usleep(1000);
920
     *     Console::updateProgress($n, 1000);
921
     * }
922
     * Console::endProgress();
923
     * ```
924
     *
925
     * Git clone like progress (showing only status information):
926
     *
927
     * ```php
928
     * Console::startProgress(0, 1000, 'Counting objects: ', false);
929
     * for ($n = 1; $n <= 1000; $n++) {
930
     *     usleep(1000);
931
     *     Console::updateProgress($n, 1000);
932
     * }
933
     * Console::endProgress("done." . PHP_EOL);
934
     * ```
935
     *
936
     * @param int $done the number of items that are completed.
937
     * @param int $total the total value of items that are to be done.
938
     * @param string $prefix an optional string to display before the progress bar.
939
     * Default to empty string which results in no prefix to be displayed.
940
     * @param int|bool $width optional width of the progressbar. This can be an integer representing
941
     * the number of characters to display for the progress bar or a float between 0 and 1 representing the
942
     * percentage of screen with the progress bar may take. It can also be set to false to disable the
943
     * bar and only show progress information like percent, number of items and ETA.
944
     * If not set, the bar will be as wide as the screen. Screen size will be detected using [[getScreenSize()]].
945
     * @see startProgress
946
     * @see updateProgress
947
     * @see endProgress
948
     */
949
    public static function startProgress($done, $total, $prefix = '', $width = null)
950
    {
951
        self::$_progressStart = time();
952
        self::$_progressWidth = $width;
953
        self::$_progressPrefix = $prefix;
954
        self::$_progressEta = null;
955
        self::$_progressEtaLastDone = 0;
956
        self::$_progressEtaLastUpdate = time();
957
958
        static::updateProgress($done, $total);
959
    }
960
961
    /**
962
     * Updates a progress bar that has been started by [[startProgress()]].
963
     *
964
     * @param int $done the number of items that are completed.
965
     * @param int $total the total value of items that are to be done.
966
     * @param string $prefix an optional string to display before the progress bar.
967
     * Defaults to null meaning the prefix specified by [[startProgress()]] will be used.
968
     * If prefix is specified it will update the prefix that will be used by later calls.
969
     * @see startProgress
970
     * @see endProgress
971
     */
972
    public static function updateProgress($done, $total, $prefix = null)
973
    {
974
        if ($prefix === null) {
975
            $prefix = self::$_progressPrefix;
976
        } else {
977
            self::$_progressPrefix = $prefix;
978
        }
979
        $width = static::getProgressbarWidth($prefix);
980
        $percent = ($total == 0) ? 1 : $done / $total;
981
        $info = sprintf('%d%% (%d/%d)', $percent * 100, $done, $total);
982
        self::setETA($done, $total);
983
        $info .= self::$_progressEta === null ? ' ETA: n/a' : sprintf(' ETA: %d sec.', self::$_progressEta);
984
985
        // Number extra characters outputted. These are opening [, closing ], and space before info
986
        // Since Windows uses \r\n\ for line endings, there's one more in the case
987
        $extraChars = static::isRunningOnWindows() ? 4 : 3;
988
        $width -= $extraChars + static::ansiStrlen($info);
989
        // skipping progress bar on very small display or if forced to skip
990
        if ($width < 5) {
991
            static::stdout("\r$prefix$info   ");
992
        } else {
993
            if ($percent < 0) {
994
                $percent = 0;
995
            } elseif ($percent > 1) {
996
                $percent = 1;
997
            }
998
            $bar = floor($percent * $width);
999
            $status = str_repeat('=', $bar);
0 ignored issues
show
Bug introduced by
$bar of type double is incompatible with the type integer expected by parameter $multiplier of str_repeat(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

999
            $status = str_repeat('=', /** @scrutinizer ignore-type */ $bar);
Loading history...
1000
            if ($bar < $width) {
1001
                $status .= '>';
1002
                $status .= str_repeat(' ', $width - $bar - 1);
1003
            }
1004
            static::stdout("\r$prefix" . "[$status] $info");
1005
        }
1006
        flush();
1007
    }
1008
1009
    /**
1010
     * Return width of the progressbar
1011
     * @param string $prefix an optional string to display before the progress bar.
1012
     * @see updateProgress
1013
     * @return int screen width
1014
     * @since 2.0.14
1015
     */
1016
    private static function getProgressbarWidth($prefix)
1017
    {
1018
        $width = self::$_progressWidth;
1019
1020
        if ($width === false) {
1021
            return 0;
1022
        }
1023
1024
        $screenSize = static::getScreenSize(true);
1025
        if ($screenSize === false && $width < 1) {
0 ignored issues
show
introduced by
The condition $screenSize === false is always false.
Loading history...
1026
            return 0;
1027
        }
1028
1029
        if ($width === null) {
1030
            $width = $screenSize[0];
1031
        } elseif ($width > 0 && $width < 1) {
1032
            $width = floor($screenSize[0] * $width);
1033
        }
1034
1035
        $width -= static::ansiStrlen($prefix);
1036
1037
        return $width;
1038
    }
1039
1040
    /**
1041
     * Calculate $_progressEta, $_progressEtaLastUpdate and $_progressEtaLastDone
1042
     * @param int $done the number of items that are completed.
1043
     * @param int $total the total value of items that are to be done.
1044
     * @see updateProgress
1045
     * @since 2.0.14
1046
     */
1047
    private static function setETA($done, $total)
1048
    {
1049
        if ($done > $total || $done == 0) {
1050
            self::$_progressEta = null;
1051
            self::$_progressEtaLastUpdate = time();
1052
            return;
1053
        }
1054
1055
        if ($done < $total && (time() - self::$_progressEtaLastUpdate > 1 && $done > self::$_progressEtaLastDone)) {
1056
            $rate = (time() - (self::$_progressEtaLastUpdate ?: self::$_progressStart)) / ($done - self::$_progressEtaLastDone);
1057
            self::$_progressEta = $rate * ($total - $done);
1058
            self::$_progressEtaLastUpdate = time();
1059
            self::$_progressEtaLastDone = $done;
1060
        }
1061
    }
1062
1063
    /**
1064
     * Ends a progress bar that has been started by [[startProgress()]].
1065
     *
1066
     * @param string|bool $remove This can be `false` to leave the progress bar on screen and just print a newline.
1067
     * If set to `true`, the line of the progress bar will be cleared. This may also be a string to be displayed instead
1068
     * of the progress bar.
1069
     * @param bool $keepPrefix whether to keep the prefix that has been specified for the progressbar when progressbar
1070
     * gets removed. Defaults to true.
1071
     * @see startProgress
1072
     * @see updateProgress
1073
     */
1074
    public static function endProgress($remove = false, $keepPrefix = true)
1075
    {
1076
        if ($remove === false) {
1077
            static::stdout(PHP_EOL);
1078
        } else {
1079
            if (static::streamSupportsAnsiColors(STDOUT)) {
1080
                static::clearLine();
1081
            }
1082
            static::stdout("\r" . ($keepPrefix ? self::$_progressPrefix : '') . (is_string($remove) ? $remove : ''));
1083
        }
1084
        flush();
1085
1086
        self::$_progressStart = null;
1087
        self::$_progressWidth = null;
1088
        self::$_progressPrefix = '';
1089
        self::$_progressEta = null;
1090
        self::$_progressEtaLastDone = 0;
1091
        self::$_progressEtaLastUpdate = null;
1092
    }
1093
1094
    /**
1095
     * Generates a summary of the validation errors.
1096
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1097
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1098
     *
1099
     * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
1100
     *   only the first error message for each attribute will be shown. Defaults to `false`.
1101
     *
1102
     * @return string the generated error summary
1103
     * @since 2.0.14
1104
     */
1105 1
    public static function errorSummary($models, $options = [])
1106
    {
1107 1
        $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
1108 1
        $lines = self::collectErrors($models, $showAllErrors);
1109
1110 1
        return implode(PHP_EOL, $lines);
1111
    }
1112
1113
    /**
1114
     * Return array of the validation errors
1115
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1116
     * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
1117
     * only the first error message for each attribute will be shown.
1118
     * @return array of the validation errors
1119
     * @since 2.0.14
1120
     */
1121 1
    private static function collectErrors($models, $showAllErrors)
1122
    {
1123 1
        $lines = [];
1124 1
        if (!is_array($models)) {
1125 1
            $models = [$models];
1126
        }
1127
1128 1
        foreach ($models as $model) {
1129 1
            $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
1130
        }
1131
1132 1
        return $lines;
1133
    }
1134
}
1135