Completed
Push — master ( 318379...7c23c1 )
by Kris
23s queued 10s
created

lib/ShellColoredPrinter.php (1 issue)

Labels
Severity
1
<?php
2
3
/* 
4
 *   __  __  _       _            _  _
5
 *  |  \/  |(_) ___ | |__    ___ | || |
6
 *  | |\/| || |/ __|| '_ \  / _ \| || |
7
 *  | |  | || |\__ \| | | ||  __/| || |
8
 *  |_|  |_||_||___/|_| |_| \___||_||_|
9
 *
10
 * This file is part of Kristuff\Mishell.
11
 * (c) Kristuff <[email protected]>
12
 *
13
 * For the full copyright and license information, please view the LICENSE
14
 * file that was distributed with this source code.
15
 *
16
 * @version    1.5.0
17
 * @copyright  2017-2021 Kristuff
18
 */
19
20
namespace Kristuff\Mishell;
21
22
abstract class ShellColoredPrinter extends \Kristuff\Mishell\ShellPrinter 
23
{
24
    /**
25
     * Foreground colors constants
26
     *
27
     * @access protected
28
     * @static
29
     * @var    array
30
     */
31
    protected static $foregroundColors = array(
32
        'black'        => '30', 
33
        'red'          => '31', 
34
        'green'        => '32', 
35
        'yellow'       => '33',
36
        'blue'         => '34', 
37
        'magenta'      => '35', 
38
        'cyan'         => '36', 
39
        'lightgray'    => '37', 
40
        'default'      => '39',   // your default color
41
        'darkgray'     => '90',
42
        'lightred'     => '91',
43
        'lightgreen'   => '92',
44
        'lightyellow'  => '93',
45
        'lightblue'    => '94',
46
        'lightmagenta' => '95',
47
        'lightcyan'    => '96',
48
        'white'        => '97',
49
    );
50
    
51
    /**
52
     * Background colors constants
53
     *
54
     * @access protected
55
     * @static
56
     * @var    array
57
     */
58
    protected static $backgroundColors = array(
59
        'black'        => '40',   
60
        'red'          => '41',
61
        'green'        => '42',   
62
        'yellow'       => '43',
63
        'blue'         => '44',   
64
        'magenta'      => '45',
65
        'cyan'         => '46',   
66
        'lightgray'    => '47',
67
        'default'      => '49',
68
        'darkgray'     => '100', 
69
        'lightred'     => '101', 
70
        'lightgreen'   => '102', 
71
        'lightyellow'  => '103',
72
        'lightblue'    => '104', 
73
        'lightmagenta' => '105', 
74
        'lightcyan'    => '106', 
75
        'white'        => '107',
76
    );
77
 
78
    /**
79
     * Text styles constants
80
     *
81
     * @access public
82
     * @static
83
     * @var    array
84
     */
85
    protected static $options = array(
86
        'none'         => '0',    // reset all styles
87
        'bold'         => '1',    // 
88
        'dim'          => '2',
89
        'underlined'   => '4',    
90
        'blink'        => '5', 
91
        'reverse'      => '7',    // reverse foreground/background color
92
93
        //formats=(["bold"]=1 ["bright"]=1 ["dim"]=2 ["underlined"]=4 ["blink"]=5 ["reverse"]=7 ["hidden"]=8)
94
        //resets=(["all"]=0 ["bold"]=21 ["bright"]=21 ["dim"]=22 ["underlined"]=24 ["blink"]=25 ["reverse"]=27 ["hidden"]=28)
95
    );
96
    
97
    /**
98
     * Get an array of all available styles
99
     *
100
     * @access public
101
     * @static
102
     *
103
     * @return array
104
     */
105
    public static function getStyles()
106
    {
107
        return [
108
            'foregrounds'   => self::$foregroundColors,
109
            'backgrounds'   => self::$backgroundColors,
110
            'options'       => self::$options
111
        ];
112
    }
113
114
    /**
115
     * Internal method dispatcher
116
     *
117
     * @access protected
118
     * @static
119
     * @param  string   $command                The command name string
120
     * @param  string   $args                   The command arguments
121
     *
122
     * @return mixed|void
123
     */
124
    protected static function cmd($command, array $args)
125
    {
126
        // ouptut string is always the first argument (in any)
127
        $str = !empty($args) ? $args[0] : '';
128
129
        // others (if any) are options
130
        array_shift($args);
131
132
        // 
133
        switch($command){
134
135
            // ****************************************
136
            // Get methods (return string)
137
            // ****************************************
138
139
            case'text':
140
                return self::getCliString($str, $args);             // get formatted text
141
            
142
            // ****************************************
143
            // Print methods (echo and return null)
144
            // ****************************************
145
            
146
            case'print':
147
                echo (self::getCliString($str, $args));               // print text
148
                break;
149
            case'log':
150
                echo (self::getCliString($str, $args) . self::$EOF );   // print text + newline
151
                break;
152
            case'relog':
153
                echo (self::getCliString($str ."\r", $args));         // overwrite current line 
154
                break;
155
156
            // *****************************************
157
            // Print+Question methods (return something)
158
            // *****************************************
159
160
            case'ask':
161
                echo (self::getCliString($str, $args));     // print question
162
                return trim(fgets(STDIN));                  // reads and return one line from STDIN 
163
           
164
            case'askPassword':
165
                self::hideInput();                          // hide 
166
                echo (self::getCliString($str, $args));     // print question
167
                $line= trim(fgets(STDIN));                  // reads one line from STDIN 
168
                self::restoreInput();                       // restore 
169
                return $line;                               // return line
170
                
171
            case 'askInt':
172
                echo (self::getCliString($str, $args));     // print question
173
                fscanf(STDIN, "%d\n", $number);             // reads number from STDIN
174
                return (is_int($number) ? $number : false); // return int value or false
175
        }
176
177
        // nothing found
178
        return null;
179
    }
180
      
181
    /**
182
     * Get a formatted cli string to output in the console
183
     *
184
     * @access protected
185
     * @static
186
     * @param  string   $str                    The text to output
187
     * @param  string   $arguments              The command arguments
188
     *
189
     * @return mixed|void
190
     */
191
    protected static function getCliString(string $str, array $arguments = [])
192
    {
193
        if (empty($arguments)){
194
            return $str;
195
        }
196
197
        $coloredString = "";
198
        $hasColor = false;
199
        $hasBackColor = false;
200
        $cliArgs = [];
201
        
202
        // parse arguments
203
        foreach ($arguments as $argument) {
204
            
205
            // it's a color?
206
            if(!$hasColor && isset(self::$foregroundColors[$argument])){
207
                $cliArgs[] = self::$foregroundColors[$argument];
208
                $hasColor = true;
209
210
            // it's a backcolor?
211
            } elseif ($hasColor && !$hasBackColor && isset(self::$backgroundColors[$argument])){
212
                $cliArgs[] = self::$backgroundColors[$argument];
213
                $hasBackColor = true;
214
215
            // or it's an option?
216
            } elseif (isset(self::$options[$argument])){
217
                $cliArgs[] = self::$options[$argument];
218
            }
219
        }
220
221
        // Add string and end coloring
222
        // todo \e[0m 
223
        $coloredString .= "\033[" . implode(';',$cliArgs) .'m';
224
        $coloredString .=  $str . "\033[0m";
225
        return $coloredString;
226
    }
227
228
    /**
229
     * Get a formatted string to be returned in console.
230
     *
231
     * @access public
232
     * @static
233
     * @param  string   [$str]                  The string to output
234
     * @param  string   [$color]                The text color for the wall line
235
     * @param  string   [$bgcolor]              The back color for the wall line
236
     * @param  string   [$option]+...           The text styles for the wall line
237
     *
238
     * @return string
239
     */
240
    public static function text()
241
    {
242
        return self::cmd('text', func_get_args());
243
    }
244
245
    /**
246
     * Print a formatted string in console.
247
     *
248
     * @access public
249
     * @static
250
     * @param  string   [$str]                  The string to print
251
     * @param  string   [$color]                The text color for the wall line
252
     * @param  string   [$bgcolor]              The back color for the wall line
253
     * @param  string   [$option]+...           The text styles for the wall line
254
     *
255
     * @return void
256
     */
257
    public static function print()
258
    {
259
        return self::cmd('write', func_get_args());
260
    }
261
262
    /**
263
     * Prints a formatted string in the console then waits for a user input.
264
     *
265
     * @access public
266
     * @static
267
     * @param  string   [$str]                  The string to print
268
     * @param  string   [$color]                The text color for the wall line
269
     * @param  string   [$bgcolor]              The back color for the wall line
270
     * @param  string   [$option]+...           The text styles for the wall line
271
     *
272
     * @return string|null
273
     */
274
    public static function ask()
275
    {
276
        return self::cmd('ask', func_get_args());
277
    }
278
279
    /**
280
     * Print a formatted string in the console and wait for an integer input.
281
     *
282
     * @access public
283
     * @static
284
     * @param  string   [$str]                  The string to print
285
     * @param  string   [$color]                The text color for the wall line
286
     * @param  string   [$bgcolor]              The back color for the wall line
287
     * @param  string   [$option]+...           The text styles for the wall line
288
     *
289
     * @return int|bool 
290
     */
291
    public static function askInt()
292
    {
293
        return self::cmd('askInt', func_get_args());
294
    }
295
296
    /**
297
     * Prints a formatted string in the console then waits for a user input (returns but does not displays that user's input).
298
     *
299
     * @param  string   [$str]                  The string to print
300
     * @param  string   [$color]                The text color for the wall line
301
     * @param  string   [$bgcolor]              The back color for the wall line
302
     * @param  string   [$option]+...           The text styles for the wall line
303
     *
304
     * @return string|null
305
     */
306
    public static function askPassword()
307
    {
308
        return self::cmd('askPassword',func_get_args());
309
    }
310
311
    /**
312
     * Print a string to console and go to new line
313
     *
314
     * @access public
315
     * @static
316
     * @param  string   [$str]                  The string to print
317
     * @param  string   [$color]                The text color for the wall line
318
     * @param  string   [$bgcolor]              The back color for the wall line
319
     * @param  string   [$option]+...           The text styles for the wall line
320
     *
321
     * @return void
322
     */
323
    public static function log()
324
    {
325
        self::cmd('log',func_get_args());
326
    }
327
328
    /**
329
     * Overwrite the current line in console.
330
     *
331
     * @access public
332
     * @static
333
     * @param  string   [$str]                  The string to print
334
     * @param  string   [$color]                The text color for the wall line
335
     * @param  string   [$bgcolor]              The back color for the wall line
336
     * @param  string   [$option]+...           The text styles for the wall line
337
     *
338
     * @return void
339
     */
340
    public static function relog()
341
    {
342
        self::cmd('relog',func_get_args());
343
    }  
344
       
345
    /**
346
     * A cli version of str_pad() that takes care of not printable ANSI chars
347
     *
348
     * @access protected
349
     * @static
350
     * @param  string   $input                  The input text
351
     * @param  int      $padLenght              The pad length. Default is 0 (no pad)
352
     * @param  string   $padString              The pad string. Default is blank char.
353
     * @param  int      $padType                The pad type (STR_PAD_LEFT, STR_PAD_RIGHT or STR_PAD_BOTH). Default is STR_PAD_RIGHT.
354
     *
355
     * @return mixed|void
356
     */    
357
    public static function pad($input, $padLength, $padString = ' ', $padType = STR_PAD_RIGHT)
358
    {
359
        $diff = $padLength - mb_strlen(preg_replace('#\\033\[[[0-9;*]{1,}m#', '', $input));
360
        
361
        if ($diff > 0){
362
            switch ($padType){
363
                
364
                case STR_PAD_RIGHT:
365
                    return $input . str_repeat($padString, $diff);
366
                
367
                case STR_PAD_LEFT:
368
                    return str_repeat($padString, $diff ) . $input;
369
                
370
                case STR_PAD_BOTH:
371
                    $padLeft = round(($diff)/2);
372
                    return str_repeat($padString, $padLeft) . $input . str_repeat($padString, $diff - $padLeft);
0 ignored issues
show
$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

372
                    return str_repeat($padString, /** @scrutinizer ignore-type */ $padLeft) . $input . str_repeat($padString, $diff - $padLeft);
Loading history...
373
            }
374
        }
375
        return $input;
376
    }
377
    
378
}