Utils   B
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 258
Duplicated Lines 27.52 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 37
c 2
b 1
f 0
lcom 1
cbo 2
dl 71
loc 258
rs 8.6

15 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 8 2
A detect_mobile() 0 8 3
A is_email() 0 8 2
A stripSlashes() 0 4 2
A textLimit() 0 6 2
A active() 0 4 2
A value() 0 8 4
A formatDate() 0 8 1
A formatMoney() 0 4 1
B encrypt() 35 35 5
A setDebug() 0 11 2
A getDebug() 0 4 1
A generateToken() 0 20 4
B decrypt() 36 36 5
A getIv() 0 7 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Core\Helpers;
4
5
use Carbon\Carbon;
6
use Core\Lib\Controller;
7
8
class Utils extends Controller
9
{
10
    private static $instance;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
11
    public $debug;
12
13
    /**
14
     * @return Utils
15
     */
16
    public static function getInstance()
17
    {
18
        if (!isset(self::$instance)) {
19
            self::$instance = new self();
20
        }
21
22
        return self::$instance;
23
    }
24
25
    /**
26
     * @param $useragent
27
     *
28
     * @return bool
29
     */
30
    public static function detect_mobile($useragent)
31
    {
32
        if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($useragent, 0, 4))) {
33
            return true;
34
        } else {
35
            return false;
36
        }
37
    }
38
39
    /**
40
     * @param $email
41
     *
42
     * @return bool
43
     */
44
    public static function is_email($email)
45
    {
46
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
47
            return true;
48
        } else {
49
            return false;
50
        }
51
    }
52
53
    /**
54
     * @param $rawData
55
     *
56
     * @return mixed
57
     */
58
    public static function stripSlashes($rawData)
59
    {
60
        return is_array($rawData) ? array_map(['self', 'stripSlashes'], $rawData) : stripslashes($rawData);
61
    }
62
63
    /**
64
     * @param $string
65
     * @param $size
66
     *
67
     * @return string
68
     */
69
    public static function textLimit($string, $size)
70
    {
71
        $string = (strlen($string) <= $size) ? $string : substr($string, 0, $size).'...';
72
73
        return $string;
74
    }
75
76
    /**
77
     * @param $uri
78
     */
79
    public function active($uri)
0 ignored issues
show
Coding Style introduced by
active uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
80
    {
81
        echo (str_replace('/', '.', substr($_SERVER['REQUEST_URI'], 1)) == $uri) ? "class='active'" : '';
82
    }
83
84
    /**
85
     * @return bool
86
     */
87
    public static function value($key = null)
0 ignored issues
show
Coding Style introduced by
value uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
88
    {
89
        if (isset($key) && $key !== null) {
90
            return (isset($_REQUEST[$key])) ? ' value='.$_REQUEST[$key].'' : false;
91
        }
92
93
        return true;
94
    }
95
96
    /**
97
     * @param $key
98
     *
99
     * @return string|static
100
     */
101
    public static function formatDate($key)
102
    {
103
        $now = Carbon::now();
0 ignored issues
show
Unused Code introduced by
$now is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
104
        $createdAt = Carbon::parse($key);
105
        $now = $createdAt->format('d/m/Y');
106
107
        return $now;
108
    }
109
110
    /**
111
     * @param $value
112
     *
113
     * @return mixed
114
     */
115
    public static function formatMoney($value)
116
    {
117
        return number_format($value, 2, ',', '.');
118
    }
119
120
    /**
121
     * @param       $data
122
     * @param       $key
123
     * @param       $iv
124
     * @param array $settings
125
     *
126
     * @return mixed
127
     */
128 View Code Duplication
    public static function encrypt($data, $key, $iv, $settings = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
    {
130
        if ($data === '' || !extension_loaded('mcrypt')) {
131
            return $data;
132
        }
133
134
        //Merge settings with defaults
135
        $defaults = [
136
            'algorithm' => MCRYPT_RIJNDAEL_256,
137
            'mode'      => MCRYPT_MODE_CBC,
138
        ];
139
        $settings = array_merge($defaults, $settings);
140
141
        //Get module
142
        $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], '');
143
144
        //Validate IV
145
        $ivSize = mcrypt_enc_get_iv_size($module);
146
        if (strlen($iv) > $ivSize) {
147
            $iv = substr($iv, 0, $ivSize);
148
        }
149
150
        //Validate key
151
        $keySize = mcrypt_enc_get_key_size($module);
152
        if (strlen($key) > $keySize) {
153
            $key = substr($key, 0, $keySize);
154
        }
155
156
        //Encrypt value
157
        mcrypt_generic_init($module, $key, $iv);
158
        $res = @mcrypt_generic($module, $data);
159
        mcrypt_generic_deinit($module);
160
161
        return $res;
162
    }
163
164
    public static function setDebug($exceptionCode)
165
    {
166
        $exception = null;
167
        switch ($exceptionCode) {
168
            case 23000: $exception = 'Erro ao inserir os dados!'; break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
169
        }
170
        $print = "<div class='debug'>";
171
        $print .= $exception;
172
        $print .= '</div>';
173
        self::getInstance()->debug = $print;
174
    }
175
176
    public static function getDebug()
177
    {
178
        echo self::getInstance()->debug;
179
    }
180
181
    /**
182
     * @param int $length
183
     *
184
     * @return string
185
     */
186
    public static function generateToken($length = 20)
187
    {
188
        if (function_exists('openssl_random_pseudo_bytes')) {
189
            $token = base64_encode(openssl_random_pseudo_bytes($length, $strong));
190
            if ($strong == true) {
191
                return strtr(substr($token, 0, $length), '+/=', '-_,');
192
            }
193
        }
194
195
        $characters = '0123456789';
196
        $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
197
        $charactersLength = strlen($characters) - 1;
198
        $token = '';
199
200
        for ($i = 0; $i < $length; $i++) {
201
            $token .= $characters[mt_rand(0, $charactersLength)];
202
        }
203
204
        return $token;
205
    }
206
207
    /**
208
     * @param       $data
209
     * @param       $key
210
     * @param       $iv
211
     * @param array $settings
212
     *
213
     * @return mixed
214
     */
215 View Code Duplication
    public static function decrypt($data, $key, $iv, $settings = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
216
    {
217
        if ($data === '' || !extension_loaded('mcrypt')) {
218
            return $data;
219
        }
220
221
        //Merge settings with defaults
222
        $defaults = [
223
            'algorithm' => MCRYPT_RIJNDAEL_256,
224
            'mode'      => MCRYPT_MODE_CBC,
225
        ];
226
        $settings = array_merge($defaults, $settings);
227
228
        //Get module
229
        $module = mcrypt_module_open($settings['algorithm'], '', $settings['mode'], '');
230
231
        //Validate IV
232
        $ivSize = mcrypt_enc_get_iv_size($module);
233
        if (strlen($iv) > $ivSize) {
234
            $iv = substr($iv, 0, $ivSize);
235
        }
236
237
        //Validate key
238
        $keySize = mcrypt_enc_get_key_size($module);
239
        if (strlen($key) > $keySize) {
240
            $key = substr($key, 0, $keySize);
241
        }
242
243
        //Decrypt value
244
        mcrypt_generic_init($module, $key, $iv);
245
        $decryptedData = @mdecrypt_generic($module, $data);
246
        $res = rtrim($decryptedData, "\0");
247
        mcrypt_generic_deinit($module);
248
249
        return $res;
250
    }
251
252
    /**
253
     * @param $expires
254
     * @param $secret
255
     *
256
     * @return mixed
257
     */
258
    private static function getIv($expires, $secret)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
259
    {
260
        $data1 = hash_hmac('sha1', 'a'.$expires.'b', $secret);
261
        $data2 = hash_hmac('sha1', 'z'.$expires.'y', $secret);
262
263
        return pack('h*', $data1.$data2);
264
    }
265
}
266