Completed
Push — master ( 138995...8cf48b )
by Kris
14s queued 11s
created

ShellUtils   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 318
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 98
c 2
b 0
f 0
dl 0
loc 318
rs 9.92
wmc 31

13 Methods

Rating   Name   Duplication   Size   Complexity  
A clearTempMessage() 0 4 1
A printTempMessage() 0 3 1
A printTitle() 0 5 1
A printResult() 0 11 3
A printVersion() 0 19 1
A printLogo() 0 10 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 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
        Console::log("        _                 ___ ___ ___  ___        ", "darkgray");
98
        Console::log("   __ _| |__ _  _ ___ ___|_ _| _ \   \| _ )       ", "darkgray");
99
        Console::log("  / _` | '_ \ || (_-</ -_)| ||  _/ |) | _ \       ", "darkgray");
100
        Console::log("  \__,_|_.__/\_,_/__/\___|___|_| |___/|___/       ", "darkgray");
101
    }
102
103
    /**
104
     * Print version 
105
     * 
106
     * @access protected
107
     * @static
108
     * @param array $arguments
109
     * 
110
     * @return void
111
     */
112
    protected static function printVersion()
113
    {
114
        self::printLogo();
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('  __________________________________________________', 'darkgray'));    
120
        //Console::log();
121
        //Console::log(Console::text('  --------------------------------------------------', 'darkgray'));    
122
        Console::log(Console::text('  Released under the MIT licence', 'darkgray'));
123
        Console::log(Console::text('  Made with ', 'darkgray') . Console::text('♥', 'red') . Console::text(' in France', 'darkgray'));
124
        Console::log(
125
            Console::text('  © 2020-2021 Kristuff (', 'darkgray').
126
            Console::text('https://github.com/kristuff', 'darkgray', 'underlined').
127
            Console::text(')', 'darkgray')
128
        );
129
        Console::log(Console::text('  --------------------------------------------------', 'darkgray'));    
130
        Console::log();
131
    }
132
133
    /**
134
     * Print app banner
135
     * 
136
     * @access protected
137
     * @static
138
     * 
139
     * @return void
140
     */
141
    protected static function printBanner()
142
    {
143
        Console::log();    
144
        Console::log( Console::text(' Kristuff\AbuseIPDB ', 'darkgray') . Console::text(' ' . AbuseIPDBClient::VERSION . ' ', 'white', 'blue')); 
145
        Console::log(Console::text(' Made with ', 'darkgray') . Console::text('♥', 'red') . Console::text(' in France', 'darkgray')); 
146
        Console::log(' © 2020-2021 Kristuff', 'darkgray'); 
147
        Console::log();    
148
    }
149
150
    /**
151
     * Print footer
152
     * 
153
     * @access protected
154
     * @static
155
     * 
156
     * @return void
157
     */
158
    protected static function printFooter(string $requestTime = '')
159
    {
160
        if (!empty($requestTime)){
161
            $date_utc = new \DateTime("now", new \DateTimeZone("UTC"));
162
            Console::log(
163
                Console::text('  Request time: ', 'darkgray') . Console::text($requestTime . 's', 'lightgray'). 
164
                Console::text(' | UTC time: ', 'darkgray') . Console::text($date_utc->format('Y-m-d H:i:s'), 'lightgray')
165
            );
166
        }
167
        Console::log(Console::text('  ------------------------------------------------------------------------------------------------------', 'darkgray')); 
168
        Console::log(
169
            Console::text('  Kristuff\AbuseIPDB ', 'darkgray') . 
170
            Console::text(AbuseIPDBClient::VERSION, 'lightgray') . 
171
            Console::text(' | Made with ', 'darkgray') . 
172
            Console::text('♥', 'red') .
173
            Console::text(' in France | © 2020-2021 Kristuff (https://github.com/kristuff)', 'darkgray')
174
        ); 
175
        Console::log();    
176
    }
177
178
    /**
179
     * Prints/gets a result value 
180
     * 
181
     * @access protected
182
     * @static
183
     * 
184
     * @return string
185
     */
186
    protected static function printResult($text, $value, string $foregroundColor = 'lightred', string $backgroundColor = '', bool $print = true)
187
    {
188
        // do not print null/blank values
189
        if (isset($value)){
190
            $line = Console::text($text, 'white') . Console::text($value, $foregroundColor, $backgroundColor); 
191
            if ($print){
192
                Console::log($line);
193
            }
194
            return $line;
195
        }
196
        return '';
197
    }
198
 
199
    /**
200
     * Prints score badge 
201
     * 
202
     * @access protected
203
     * @static
204
     * @param string    $text       
205
     * @param int       $score     
206
     * @param string    $textColor
207
     * 
208
     * @return string
209
     */
210
    protected static function getScoreBadge(int $score, string $padding = ' ')
211
    {
212
        $scoreforegroundColor = 'white';
213
        $scoreBackgroundColor = 'green';
214
215
        if (intval($score) > 0 ){
216
            $scoreforegroundColor = 'black';
217
            $scoreBackgroundColor = 'yellow';
218
        } 
219
        if (intval($score) > 50 ){
220
            $scoreforegroundColor = 'white';
221
            $scoreBackgroundColor = 'red';
222
        } 
223
  
224
        $badge = str_pad($score, 3, ' ',STR_PAD_LEFT); 
225
        return Console::text($padding.$badge.$padding, $scoreforegroundColor, $scoreBackgroundColor);
226
    }
227
228
    /**
229
     * Check and print errors in API response
230
     * 
231
     * @access protected
232
     * @static
233
     * @param object     $response       
234
     * @param bool       $checkForEmpty     
235
     * 
236
     * @return bool     
237
     */
238
    protected static function printErrors($response, bool $checkForEmpty = true)
239
    {
240
        if (isset($response) && isset($response->errors)){
241
242
            // top error badge    
243
            Console::log('  ' .   Console::text(' ERROR ','white', 'red'));
244
245
            $num = 0;
246
            // errors is an array, could have more than one error..
247
            foreach ($response->errors as $err){
248
                $num++;
249
250
                Console::log(Console::text('   ✗', 'red') .  self::printResult(' Number:    ', $num, 'lightyellow','', false));
251
                self::printResult('     Status:    ', $err->status ?? null, 'lightyellow','');    
252
                
253
                if (!empty($err->source) && !empty($err->source->parameter)){
254
                    self::printResult('     Parameter: ', $err->source->parameter, 'lightyellow');    
255
                }
256
                self::printResult('     Title:     ', $err->title ?? null, 'lightyellow');    
257
                self::printResult('     Detail:    ', $err->detail ?? null, 'lightyellow');    
258
259
                // separate errors
260
                if (count($response->errors) > 1){
261
                    Console::log('   ---');
262
                }
263
264
            }
265
            Console::log();
266
            return true;
267
        }
268
269
        // check for empty response ?
270
        if ( $checkForEmpty && ( empty($response) || empty($response->data)) ){
271
            self::error('An unexpected error occurred.');
272
            return true;
273
        }
274
275
        return false;    
276
    }
277
278
    /**
279
     * Print a single error
280
     * 
281
     * @access protected
282
     * @static
283
     * @param string    $error      The error message
284
     * 
285
     * @return void
286
     */
287
    protected static function error($error)
288
    {
289
        // ✗
290
        Console::log('  ' .   Console::text(' ERROR ','white', 'red'));
291
        Console::log(
292
            Console::text('   ✗', 'red') . 
293
            Console::text(' Detail:    ', 'white') . 
294
            Console::text($error, 'lightyellow') . 
295
            Console::text('', 'white')
296
        );    
297
        Console::log();    
298
    }
299
    
300
    /**
301
     * helper to validate a condition or exit with an error
302
     * 
303
     * @access protected
304
     * @static
305
     * @param bool      $condition      The condition to evaluate
306
     * @param string    $message        Error message
307
     * @param bool      $print          True to print error. Default is true
308
     * 
309
     * @return bool
310
     */
311
    protected static function validate(bool $condition, string $message, bool $print = true)
312
    {
313
        if ( !$condition ){
314
            if ($print) {
315
                Console::log();
316
                self::error($message);
317
                self::printFooter();
318
            }
319
            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...
320
        }
321
    }
322
323
        /**
324
     * Get numeric parameter and exit on error
325
     * 
326
     * @access protected
327
     * @static
328
     * @param array     $arguments
329
     * @param string    $shortArg           The short argument name
330
     * @param string    $longArg            The long argument name
331
     * @param int       $defaultValue
332
     * 
333
     * @return int
334
     */
335
    protected static function getNumericParameter(array $arguments, string $shortArg, string $longArg, int $defaultValue)
336
    {
337
         if (self::inArguments($arguments,$shortArg, $longArg)){
338
            $val = self::getArgumentValue($arguments,$shortArg, $longArg);
339
340
            if (!is_numeric($val)){
341
                self::error("Invalid parameter: $longArg must be a numeric value.");
342
                self::printFooter();
343
                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...
344
            }
345
            return intval($val);
346
        }
347
        return $defaultValue;
348
    }
349
350
}