ShellColoredPrinter   A
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 403
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 38
eloc 124
c 1
b 0
f 0
dl 0
loc 403
rs 9.36

13 Methods

Rating   Name   Duplication   Size   Complexity  
B getCliString() 0 35 9
A print() 0 3 1
A text() 0 3 1
A log() 0 3 1
A ask() 0 3 1
A relog() 0 3 1
A getStyles() 0 6 1
A askPassword() 0 3 1
C cmd() 0 68 13
A pad() 0 19 5
A askInt() 0 3 1
A progressBar() 0 16 2
A overwrite() 0 3 1
1
<?php
2
3
/** 
4
 *        _    _        _ _
5
 *  _ __ (_)__| |_  ___| | |
6
 * | '  \| (_-< ' \/ -_) | |
7
 * |_|_|_|_/__/_||_\___|_|_|
8
 *
9
 * This file is part of Kristuff\Mishell.
10
 * (c) Kr1s7uff For the full copyright and license information, 
11
 * please view the LICENSE file that was distributed with this 
12
 * source code.
13
 *
14
 * @version    1.6.2
15
 * @copyright  2017-2024 Kr157uff
16
 */
17
18
namespace Kristuff\Mishell;
19
20
abstract class ShellColoredPrinter extends \Kristuff\Mishell\ShellPrinter 
21
{
22
    /**
23
     * Foreground colors constants
24
     *
25
     * @access protected
26
     * @static
27
     * @var    array
28
     */
29
    protected static $foregroundColors = array(
30
        'black'        => '30', 
31
        'red'          => '31', 
32
        'green'        => '32', 
33
        'yellow'       => '33',
34
        'blue'         => '34', 
35
        'magenta'      => '35', 
36
        'cyan'         => '36', 
37
        'lightgray'    => '37', 
38
        'default'      => '39',   // your default color
39
        'darkgray'     => '90',
40
        'lightred'     => '91',
41
        'lightgreen'   => '92',
42
        'lightyellow'  => '93',
43
        'lightblue'    => '94',
44
        'lightmagenta' => '95',
45
        'lightcyan'    => '96',
46
        'white'        => '97',
47
    );
48
    
49
    /**
50
     * Background colors constants
51
     *
52
     * @access protected
53
     * @static
54
     * @var    array
55
     */
56
    protected static $backgroundColors = array(
57
        'black'        => '40',   
58
        'red'          => '41',
59
        'green'        => '42',   
60
        'yellow'       => '43',
61
        'blue'         => '44',   
62
        'magenta'      => '45',
63
        'cyan'         => '46',   
64
        'lightgray'    => '47',
65
        'default'      => '49',
66
        'darkgray'     => '100', 
67
        'lightred'     => '101', 
68
        'lightgreen'   => '102', 
69
        'lightyellow'  => '103',
70
        'lightblue'    => '104', 
71
        'lightmagenta' => '105', 
72
        'lightcyan'    => '106', 
73
        'white'        => '107',
74
    );
75
 
76
    /**
77
     * Text styles constants
78
     *
79
     * @access public
80
     * @static
81
     * @var    array
82
     */
83
    protected static $options = array(
84
        'none'         => '0',    // reset all styles
85
        'bold'         => '1',    // 
86
        'dim'          => '2',
87
        'underlined'   => '4',    
88
        'blink'        => '5', 
89
        'reverse'      => '7',    // reverse foreground/background color
90
    );
91
    
92
    /**
93
     * Get an array of all available styles
94
     *
95
     * @access public
96
     * @static
97
     *
98
     * @return array
99
     */
100
    public static function getStyles()
101
    {
102
        return [
103
            'foregrounds'   => self::$foregroundColors,
104
            'backgrounds'   => self::$backgroundColors,
105
            'options'       => self::$options
106
        ];
107
    }
108
109
    /**
110
     * Internal method dispatcher
111
     *
112
     * @access protected
113
     * @static
114
     * @param string   $command                The command name string
115
     * @param array    $args                   The command arguments
116
     *
117
     * @return mixed|void
118
     */
119
    protected static function cmd($command, array $args)
120
    {
121
        // ouptut string is always the first argument (if any)
122
        $str = !empty($args) ? $args[0] : '';
123
124
        // others (if any) are options
125
        array_shift($args);
126
127
        // 
128
        switch($command){
129
130
            // ****************************************
131
            // Get methods (return string)
132
            // ****************************************
133
134
            case'text':
135
                return self::getCliString($str, $args);             // get formatted text
136
            
137
            // ****************************************
138
            // Print methods (echo and return null)
139
            // ****************************************
140
            
141
            case'print':
142
                echo (self::getCliString($str, $args));               // print text
143
                break;
144
145
            case'log':
146
                echo (self::getCliString($str, $args) . self::$EOF );   // print text + newline
147
                break;
148
149
            case'relog':
150
                // overwrite last line (cursor stays at the beginning)
151
                echo (self::getCliString($str ."\r", $args));   
152
                break;
153
154
            case'overwrite':
155
                // Overwrite last x printed line (add trailing new lines)
156
                // text could be one line string, or array of lines
157
                $text           = is_array($str) ? implode(PHP_EOL, $str) : $str;
158
                $overwriteIndex = is_array($str) ? count($str) :  1;
159
                // https://stackoverflow.com/questions/11283625/overwrite-last-line-on-terminal
160
                echo ("\033[". $overwriteIndex ."A\033[K".self::getCliString($text, $args).self::$EOF);  
161
162
                break;
163
164
            // *****************************************
165
            // Print+Question methods (return something)
166
            // *****************************************
167
168
            case'ask':
169
                echo (self::getCliString($str, $args));     // print question
170
                return trim(fgets(STDIN));                  // reads and return one line from STDIN 
171
           
172
            case'askPassword':
173
                self::hideInput();                          // hide 
174
                echo (self::getCliString($str, $args));     // print question
175
                $line= trim(fgets(STDIN));                  // reads one line from STDIN 
176
                self::restoreInput();                       // restore 
177
                return $line;                               // return line
178
                
179
            case 'askInt':
180
                echo (self::getCliString($str, $args));     // print question
181
                fscanf(STDIN, "%d\n", $number);             // reads number from STDIN
182
                return (is_int($number) ? $number : false); // return int value or false
183
        }
184
185
        // nothing found
186
        return null;
187
    }
188
    
189
190
191
192
    
193
    public static function progressBar(
194
        $percent, 
195
        $color, 
196
        $bgcolor, 
197
        $background = 'darkgray', 
198
        $progressLenght = 40, 
199
        $pendingSign =  ' ', 
200
        $progressSign =  ' ', 
201
        $withPurcent = true
202
    ){
203
        $perc  = min(100,$percent);
204
        $start = round($progressLenght * $perc / 100);
205
206
        return  ($withPurcent ? Console::text(Console::pad($perc . '% ', 5, ' ', STR_PAD_LEFT),  $color) : '').
207
                Console::text(Console::pad('', $start, $progressSign),  'white', $bgcolor) .
208
                Console::text(Console::pad('', $progressLenght - $start, $pendingSign), 'black', $background) ;
209
    }
210
211
    /**
212
     * Get a formatted cli string to output in the console
213
     *
214
     * @access protected
215
     * @static
216
     * @param string   $str                    The text to output
217
     * @param string   $arguments              The command arguments
218
     *
219
     * @return mixed|void
220
     */
221
    protected static function getCliString(string $str, array $arguments = [])
222
    {
223
        if (empty($arguments)){
224
            return $str;
225
        }
226
227
        $coloredString = "";
228
        $hasColor = false;
229
        $hasBackColor = false;
230
        $cliArgs = [];
231
        
232
        // parse arguments
233
        foreach ($arguments as $argument) {
234
            
235
            // it's a color?
236
            if(!$hasColor && isset(self::$foregroundColors[$argument])){
237
                $cliArgs[] = self::$foregroundColors[$argument];
238
                $hasColor = true;
239
240
            // it's a backcolor?
241
            } elseif ($hasColor && !$hasBackColor && isset(self::$backgroundColors[$argument])){
242
                $cliArgs[] = self::$backgroundColors[$argument];
243
                $hasBackColor = true;
244
245
            // or it's an option?
246
            } elseif (isset(self::$options[$argument])){
247
                $cliArgs[] = self::$options[$argument];
248
            }
249
        }
250
251
        // Add string and end coloring
252
        // todo \e[0m 
253
        $coloredString .= "\033[" . implode(';',$cliArgs) .'m';
254
        $coloredString .=  $str . "\033[0m";
255
        return $coloredString;
256
    }
257
258
    /**
259
     * Get a formatted string to be returned in terminal.
260
     *
261
     * @access public
262
     * @static
263
     * @param string   [$str]                  The string to output
264
     * @param string   [$color]                The text color for the wall line
265
     * @param string   [$bgcolor]              The back color for the wall line
266
     * @param string   [$option]+...           The text styles for the wall line
267
     *
268
     * @return string
269
     */
270
    public static function text()
271
    {
272
        return self::cmd('text', func_get_args());
273
    }
274
275
    /**
276
     * Print a formatted string in terminal.
277
     *
278
     * @access public
279
     * @static
280
     * @param string   [$str]                  The string to print
281
     * @param string   [$color]                The text color for the wall line
282
     * @param string   [$bgcolor]              The back color for the wall line
283
     * @param string   [$option]+...           The text styles for the wall line
284
     *
285
     * @return void
286
     */
287
    public static function print()
288
    {
289
        return self::cmd('print', func_get_args());
0 ignored issues
show
Bug introduced by
Are you sure the usage of self::cmd('print', func_get_args()) targeting Kristuff\Mishell\ShellColoredPrinter::cmd() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
290
    }
291
292
    /**
293
     * Prints a formatted string in the console then waits for a user input.
294
     *
295
     * @access public
296
     * @static
297
     * @param string   [$str]                  The string to print
298
     * @param string   [$color]                The text color for the wall line
299
     * @param string   [$bgcolor]              The back color for the wall line
300
     * @param string   [$option]+...           The text styles for the wall line
301
     *
302
     * @return string|null
303
     */
304
    public static function ask()
305
    {
306
        return self::cmd('ask', func_get_args());
307
    }
308
309
    /**
310
     * Print a formatted string in the console and wait for an integer input.
311
     *
312
     * @access public
313
     * @static
314
     * @param string   [$str]                  The string to print
315
     * @param string   [$color]                The text color for the wall line
316
     * @param string   [$bgcolor]              The back color for the wall line
317
     * @param string   [$option]+...           The text styles for the wall line
318
     *
319
     * @return int|bool 
320
     */
321
    public static function askInt()
322
    {
323
        return self::cmd('askInt', func_get_args());
324
    }
325
326
    /**
327
     * Prints a formatted string in the console then waits for a user input (returns but does not displays that user's input).
328
     *
329
     * @param string   [$str]                  The string to print
330
     * @param string   [$color]                The text color for the wall line
331
     * @param string   [$bgcolor]              The back color for the wall line
332
     * @param string   [$option]+...           The text styles for the wall line
333
     *
334
     * @return string|null
335
     */
336
    public static function askPassword()
337
    {
338
        return self::cmd('askPassword',func_get_args());
339
    }
340
341
    /**
342
     * Print a string to console and go to new line
343
     *
344
     * @access public
345
     * @static
346
     * @param string   [$str]                  The string to print
347
     * @param string   [$color]                The text color for the wall line
348
     * @param string   [$bgcolor]              The back color for the wall line
349
     * @param string   [$option]+...           The text styles for the wall line
350
     *
351
     * @return void
352
     */
353
    public static function log()
354
    {
355
        self::cmd('log',func_get_args());
356
    }
357
358
    /**
359
     * Overwrite the current line in terminal. (cursor stays at the beginning)
360
     *
361
     * @access public
362
     * @static
363
     * @param string   [$str]                  The string to print
364
     * @param string   [$color]                The text color for the wall line
365
     * @param string   [$bgcolor]              The back color for the wall line
366
     * @param string   [$option]+...           The text styles for the wall line
367
     *
368
     * @return void
369
     */
370
    public static function relog()
371
    {
372
        self::cmd('relog',func_get_args());
373
    }  
374
375
    /**
376
     * Overwrite the current line in terminal.
377
     *
378
     * @access public
379
     * @static
380
     * @param string|array   [$str]            The string to print|array of lines
381
     * @param string   [$color]                The text color for the wall line
382
     * @param string   [$bgcolor]              The back color for the wall line
383
     * @param string   [$option]+...           The text styles for the wall line
384
     *
385
     * @return void
386
     */
387
    public static function overwrite()
388
    {
389
        self::cmd('overwrite',func_get_args());
390
    }  
391
    
392
    /**
393
     * A cli version of str_pad() that takes care of not printable ANSI chars
394
     *
395
     * @access protected
396
     * @static
397
     * @param string   $input                  The input text
398
     * @param int      $padLenght              The pad length. Default is 0 (no pad)
399
     * @param string   $padString              The pad string. Default is blank char.
400
     * @param int      $padType                The pad type (STR_PAD_LEFT, STR_PAD_RIGHT or STR_PAD_BOTH). Default is STR_PAD_RIGHT.
401
     *
402
     * @return mixed|void
403
     */    
404
    public static function pad($input, $padLength, $padString = ' ', $padType = STR_PAD_RIGHT)
405
    {
406
        $diff = $padLength - mb_strlen(preg_replace('#\\033\[[[0-9;*]{1,}m#', '', $input));
407
        
408
        if ($diff > 0){
409
            switch ($padType){
410
                
411
                case STR_PAD_RIGHT:
412
                    return $input . str_repeat($padString, $diff);
413
                
414
                case STR_PAD_LEFT:
415
                    return str_repeat($padString, $diff ) . $input;
416
                
417
                case STR_PAD_BOTH:
418
                    $padLeft = round(($diff)/2);
419
                    return str_repeat($padString, $padLeft) . $input . str_repeat($padString, $diff - $padLeft);
0 ignored issues
show
Bug introduced by
$padLeft of type double is incompatible with the type integer expected by parameter $times 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

419
                    return str_repeat($padString, /** @scrutinizer ignore-type */ $padLeft) . $input . str_repeat($padString, $diff - $padLeft);
Loading history...
420
            }
421
        }
422
        return $input;
423
    }
424
    
425
}