Passed
Branch dev (82d5bf)
by Kris
02:06
created

ShellUtils   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 312
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 94
dl 0
loc 312
rs 9.92
c 1
b 0
f 0
wmc 31

13 Methods

Rating   Name   Duplication   Size   Complexity  
A printResult() 0 11 3
A printVersion() 0 11 1
A printLogo() 0 11 1
A printBanner() 0 7 1
A getNumericParameter() 0 13 3
B printErrors() 0 38 10
A getScoreBadge() 0 16 3
A printFooter() 0 18 2
A clearTempMessage() 0 4 1
A printTempMessage() 0 3 1
A printTitle() 0 5 1
A error() 0 11 1
A validate() 0 9 3
1
<?php
2
3
/**
4
 *     _    _                    ___ ____  ____  ____
5
 *    / \  | |__  _   _ ___  ___|_ _|  _ \|  _ \| __ )
6
 *   / _ \ | '_ \| | | / __|/ _ \| || |_) | | | |  _ \
7
 *  / ___ \| |_) | |_| \__ \  __/| ||  __/| |_| | |_) |
8
 * /_/   \_\_.__/ \__,_|___/\___|___|_|   |____/|____/
9
 *
10
 * This file is part of Kristuff\AbsuseIPDB.
11
 *
12
 * (c) Kristuff <[email protected]>
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 *
17
 * @version    0.9.9
18
 * @copyright  2020-2021 Kristuff
19
 */
20
namespace Kristuff\AbuseIPDB;
21
22
use Kristuff\Mishell\Console;
23
use Kristuff\AbuseIPDB\ApiHandler;
24
25
/**
26
 * Class ShellUtils
27
 * 
28
 * Absract base class for main cli program
29
 */
30
abstract class ShellUtils
31
{
32
    /**
33
     * helper functions
34
     */
35
    use UtilsTrait;
36
    
37
    /**
38
     * Prints title action banner 
39
     * 
40
     * @access protected
41
     * @static
42
     * @param array $arguments
43
     * 
44
     * @return void
45
     */
46
    protected static function printTitle(string $title)
47
    {
48
        Console::log();
49
        Console::log($title);
50
        Console::log();
51
    }
52
  
53
    /**
54
     * Print temp message during api request 
55
     * 
56
     * @access protected
57
     * @static
58
     * @param array $arguments
59
     * 
60
     * @return void
61
     */
62
    protected static function printTempMessage()
63
    {
64
        Console::reLog(Console::text('   ? ', 'green') . Console::text('waiting for api response', 'white') . Console::text(' ... ', 'green'));
65
    }
66
67
    /**
68
     * Clear the temp message set during api request 
69
     * 
70
     * @access protected
71
     * @static
72
     * @param array $arguments
73
     * 
74
     * @return void
75
     */
76
    protected static function clearTempMessage()
77
    {
78
        // long blank string to overwrite previous message
79
        Console::reLog('                                                     ');
80
    }
81
82
    /**
83
     * Print to banner 
84
     * 
85
     * @access protected
86
     * @static
87
     * @param array $arguments
88
     * 
89
     * @return void
90
     */
91
    protected static function printLogo()
92
    {
93
        //Console::log("   _       _    _         __  __                   ", "darkgray");
94
        //Console::log("  | |___ _(_)__| |_ _  _ / _|/ _|                  ", "darkgray");
95
        //Console::log("  | / / '_| (_-<  _| || |  _|  _|                  ", "darkgray");
96
        //Console::log("  |_\_\_| |_/__/\__|\_,_|_| |_|                    ", "darkgray");
97
        
98
        Console::log("         _                 ___ ___ ___  ___        ", "darkgray");
99
        Console::log("    __ _| |__ _  _ ___ ___|_ _| _ \   \| _ )       ", "darkgray");
100
        Console::log("   / _` | '_ \ || (_-</ -_)| ||  _/ |) | _ \       ", "darkgray");
101
        Console::log("   \__,_|_.__/\_,_/__/\___|___|_| |___/|___/       ", "darkgray");
102
    }
103
104
    /**
105
     * Print version 
106
     * 
107
     * @access protected
108
     * @static
109
     * @param array $arguments
110
     * 
111
     * @return void
112
     */
113
    protected static function printVersion()
114
    {
115
        Console::log();
116
        Console::log(Console::text('  Kristuff/AbuseIPDB Client version: ', 'darkgray') . Console::text(AbuseIPDBClient::VERSION, 'lightgray'));
117
        Console::log(Console::text('  Kristuff/AbuseIPDB Core version:   ', 'darkgray') . Console::text(ApiHandler::VERSION, 'lightgray')); 
118
        Console::log(Console::text('  --------------------------------------------------', 'darkgray'));    
119
        Console::log(Console::text('  Licence: ', 'darkgray') . Console::text('MIT', 'lightgray'));
120
        Console::log(Console::text('  Made with ', 'darkgray') . Console::text('♥', 'red') . Console::text(' in France ', 'darkgray'));
121
        Console::log(Console::text('  © 2020-2021 Kristuff (https://github.com/kristuff)', 'darkgray'));
122
        Console::log(Console::text('  --------------------------------------------------', 'darkgray'));    
123
        Console::log();
124
    }
125
126
127
    /**
128
     * Print app banner
129
     * 
130
     * @access protected
131
     * @static
132
     * 
133
     * @return void
134
     */
135
    protected static function printBanner()
136
    {
137
        Console::log();    
138
        Console::log( Console::text(' Kristuff\AbuseIPDB ', 'darkgray') . Console::text(' ' . AbuseIPDBClient::VERSION . ' ', 'white', 'blue')); 
139
        Console::log(Console::text(' Made with ', 'darkgray') . Console::text('♥', 'red') . Console::text(' in France', 'darkgray')); 
140
        Console::log(' © 2020-2021 Kristuff', 'darkgray'); 
141
        Console::log();    
142
    }
143
144
    /**
145
     * Print footer
146
     * 
147
     * @access protected
148
     * @static
149
     * 
150
     * @return void
151
     */
152
    protected static function printFooter(string $requestTime = '')
153
    {
154
        if (!empty($requestTime)){
155
            $date_utc = new \DateTime("now", new \DateTimeZone("UTC"));
156
            Console::log(
157
                Console::text('  Request time: ', 'darkgray') . Console::text($requestTime . 's', 'lightgray'). 
158
                Console::text(' | UTC time: ', 'darkgray') . Console::text($date_utc->format('Y-m-d H:i:s'), 'lightgray')
159
            );
160
        }
161
        Console::log(Console::text('  ------------------------------------------------------------------------------------------------------', 'darkgray')); 
162
        Console::log(
163
            Console::text('  Kristuff\AbuseIPDB ', 'darkgray') . 
164
            Console::text(AbuseIPDBClient::VERSION, 'lightgray') . 
165
            Console::text(' | Made with ', 'darkgray') . 
166
            Console::text('♥', 'red') .
167
            Console::text(' in France | © 2020-2021 Kristuff (https://github.com/kristuff)', 'darkgray')
168
        ); 
169
        Console::log();    
170
    }
171
172
    /**
173
     * Prints/gets a result value 
174
     * 
175
     * @access protected
176
     * @static
177
     * 
178
     * @return string
179
     */
180
    protected static function printResult($text, $value, string $foregroundColor = 'lightred', string $backgroundColor = '', bool $print = true)
181
    {
182
        // do not print null/blank values
183
        if (isset($value)){
184
            $line = Console::text($text, 'white') . Console::text($value, $foregroundColor, $backgroundColor); 
185
            if ($print){
186
                Console::log($line);
187
            }
188
            return $line;
189
        }
190
        return '';
191
    }
192
 
193
    /**
194
     * Prints score badge 
195
     * 
196
     * @access protected
197
     * @static
198
     * @param string    $text       
199
     * @param int       $score     
200
     * @param string    $textColor
201
     * 
202
     * @return string
203
     */
204
    protected static function getScoreBadge(int $score, string $padding = ' ')
205
    {
206
        $scoreforegroundColor = 'white';
207
        $scoreBackgroundColor = 'green';
208
209
        if (intval($score) > 0 ){
210
            $scoreforegroundColor = 'black';
211
            $scoreBackgroundColor = 'yellow';
212
        } 
213
        if (intval($score) > 50 ){
214
            $scoreforegroundColor = 'white';
215
            $scoreBackgroundColor = 'red';
216
        } 
217
  
218
        $badge = str_pad($score, 3, ' ',STR_PAD_LEFT); 
219
        return Console::text($padding.$badge.$padding, $scoreforegroundColor, $scoreBackgroundColor);
220
    }
221
222
    /**
223
     * Check and print errors in API response
224
     * 
225
     * @access protected
226
     * @static
227
     * @param object     $response       
228
     * @param bool       $checkForEmpty     
229
     * 
230
     * @return bool     
231
     */
232
    protected static function printErrors($response, bool $checkForEmpty = true)
233
    {
234
        if (isset($response) && isset($response->errors)){
235
236
            // top error badge    
237
            Console::log('  ' .   Console::text(' ERROR ','white', 'red'));
238
239
            $num = 0;
240
            // errors is an array, could have more than one error..
241
            foreach ($response->errors as $err){
242
                $num++;
243
244
                Console::log(Console::text('   ✗', 'red') .  self::printResult(' Number:    ', $num, 'lightyellow','', false));
245
                self::printResult('     Status:    ', $err->status ?? null, 'lightyellow','');    
246
                
247
                if (!empty($err->source) && !empty($err->source->parameter)){
248
                    self::printResult('     Parameter: ', $err->source->parameter, 'lightyellow');    
249
                }
250
                self::printResult('     Title:     ', $err->title ?? null, 'lightyellow');    
251
                self::printResult('     Detail:    ', $err->detail ?? null, 'lightyellow');    
252
253
                // separate errors
254
                if (count($response->errors) > 1){
255
                    Console::log('   ---');
256
                }
257
258
            }
259
            Console::log();
260
            return true;
261
        }
262
263
        // check for empty response ?
264
        if ( $checkForEmpty && ( empty($response) || empty($response->data)) ){
265
            self::error('An unexpected error occurred.');
266
            return true;
267
        }
268
269
        return false;    
270
    }
271
272
    /**
273
     * Print a single error
274
     * 
275
     * @access protected
276
     * @static
277
     * @param string    $error      The error message
278
     * 
279
     * @return void
280
     */
281
    protected static function error($error)
282
    {
283
        // ✗
284
        Console::log('  ' .   Console::text(' ERROR ','white', 'red'));
285
        Console::log(
286
            Console::text('   ✗', 'red') . 
287
            Console::text(' Detail:    ', 'white') . 
288
            Console::text($error, 'lightyellow') . 
289
            Console::text('', 'white')
290
        );    
291
        Console::log();    
292
    }
293
    
294
    /**
295
     * helper to validate a condition or exit with an error
296
     * 
297
     * @access protected
298
     * @static
299
     * @param bool      $condition      The condition to evaluate
300
     * @param string    $message        Error message
301
     * @param bool      $print          True to print error. Default is true
302
     * 
303
     * @return bool
304
     */
305
    protected static function validate(bool $condition, string $message, bool $print = true)
306
    {
307
        if ( !$condition ){
308
            if ($print) {
309
                Console::log();
310
                self::error($message);
311
                self::printFooter();
312
            }
313
            exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
314
        }
315
    }
316
317
        /**
318
     * Get numeric parameter and exit on error
319
     * 
320
     * @access protected
321
     * @static
322
     * @param array     $arguments
323
     * @param string    $shortArg           The short argument name
324
     * @param string    $longArg            The long argument name
325
     * @param int       $defaultValue
326
     * 
327
     * @return int
328
     */
329
    protected static function getNumericParameter(array $arguments, string $shortArg, string $longArg, int $defaultValue)
330
    {
331
         if (self::inArguments($arguments,$shortArg, $longArg)){
332
            $val = self::getArgumentValue($arguments,$shortArg, $longArg);
333
334
            if (!is_numeric($val)){
335
                self::error("Invalid parameter: $longArg must be a numeric value.");
336
                self::printFooter();
337
                exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
338
            }
339
            return intval($val);
340
        }
341
        return $defaultValue;
342
    }
343
344
}