Test Failed
Push — master ( f8eb03...8feb3a )
by Francimar
06:03
created

Util   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 308
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 43
lcom 0
cbo 0
dl 0
loc 308
ccs 115
cts 115
cp 1
rs 8.96
c 0
b 0
f 0

22 Methods

Rating   Name   Duplication   Size   Complexity  
A toCurrency() 0 4 1
A toFloat() 0 4 1
A toDateTime() 0 4 1
A toHex() 0 5 1
A padDigit() 0 4 1
A padText() 0 4 1
A isEqual() 0 4 2
A isGreater() 0 4 1
A isLess() 0 4 1
A toMoney() 0 4 1
A binarySearch() 0 18 4
A removeAccent() 0 8 1
A createDirectory() 0 8 2
A getModulo11() 0 15 3
A getModulo10() 0 16 4
A getDAC() 0 10 3
A appendNode() 0 11 2
A addAttribute() 0 7 1
A loadNode() 0 11 3
A nodeExists() 0 5 2
A findNode() 0 14 4
A mergeNodes() 0 14 3

How to fix   Complexity   

Complex Class

Complex classes like Util often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Util, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * MIT License
4
 *
5
 * Copyright (c) 2016 MZ Desenvolvimento de Sistemas LTDA
6
 *
7
 * @author Francimar Alves <[email protected]>
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
namespace NFe\Common;
29
30
/**
31
 * Utilitário para conversões de moeda, datas, verificação de dígitos, etc.
32
 */
33
class Util
34
{
35
    const ACCENT_CHARS =
36
        'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ';
37
    const NORMAL_CHARS =
38
        'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY';
39
    
40
    /**
41
     * Converte float para string informando a quantidade de
42
     * casas decimais e usando ponto como separador
43
     * @param  float   $value  valor para ser convertido
44
     * @param  integer $places quantidade de casas decimais, padrão 2 casas
45
     * @return string          valor formatado
46
     */
47 119
    public static function toCurrency($value, $places = 2)
48
    {
49 119
        return number_format($value, $places, '.', '');
50
    }
51
52
    /**
53
     * Converte float para string informando a quantidade de
54
     * casas decimais e usando ponto como separador
55
     * @param  float   $value  valor para ser convertido
56
     * @param  integer $places quantidade de casas decimais, padrão 4 casas
57
     * @return string          valor formatado
58
     */
59 103
    public static function toFloat($value, $places = 4)
60
    {
61 103
        return number_format($value, $places, '.', '');
62
    }
63
64
    /**
65
     * Converte timestamp para data GMT
66
     * @param  integer $time data para ser convertida
67
     * @return string        data no formato GMT
68
     */
69 36
    public static function toDateTime($time)
70
    {
71 36
        return date('Y-m-d\TH:i:sP', $time);
72
    }
73
74
    /**
75
     * Converte uma cadeira de bytes para hexadecimal
76
     * @param  string $string cadeira de bytes ou de caracteres
77
     * @return string         representação em hexadecimal
78
     */
79 1
    public static function toHex($string)
80
    {
81 1
        $hexstr = unpack('H*', $string);
82 1
        return array_shift($hexstr);
83
    }
84
85
    /**
86
     * Adiciona zeros à esquerda para completar o comprimento
87
     * @param  string  $text  texto ou número a ser adicionados os zeros
88
     * @param  integer $len  quantidade de caracteres mínimo que deve ter
89
     * @param  string  $digit permite alterar o caractere a ser concatenado
90
     * @return string        texto com os zeros à esquerda
91
     */
92 32
    public static function padDigit($text, $len, $digit = '0')
93
    {
94 32
        return str_pad($text, $len, $digit, STR_PAD_LEFT);
95
    }
96
97
    /**
98
     * Adiciona zeros à direita para completar o comprimento
99
     * @param  stringt $str texto ou número a ser adicionado os zeros
100
     * @param  integer $len quantidade de caracteres mínimo
101
     * @param  string  $txt caractere a ser adicionado quando não atingir
102
     * a quantidade len
103
     * @return string       texto com os zeros à direita
104
     */
105 21
    public static function padText($str, $len, $txt = '0')
106
    {
107 21
        return str_pad($str, $len, $txt, STR_PAD_RIGHT);
108
    }
109
110
    /**
111
     * Compara se dois valores flutuantes são iguais usando um delta como erro
112
     * @param  float  $value   valor a ser comparado
113
     * @param  float  $compare valor a ser comparado
114
     * @param  float   $delta   margem de erro para igualdade
115
     * @return boolean          true se for igual ou false caso contrário
116
     */
117 4
    public static function isEqual($value, $compare, $delta = 0.005)
118
    {
119 4
        return $compare < ($value + $delta) && ($value - $delta) < $compare;
120
    }
121
122
    /**
123
     * Compara se um valor é maior que outro usando um delta como erro
124
     * @param  float  $value   valor para testar se é maior
125
     * @param  float  $compare valor com que será comparado
126
     * @param  float   $delta   margem de erro para informar se é maior
127
     * @return boolean          true se o valor for maior ou false caso contrário
128
     */
129 34
    public static function isGreater($value, $compare, $delta = 0.005)
130
    {
131 34
        return $value > ($compare + $delta);
132
    }
133
134
    /**
135
     * Compara se um valor é menor que outro usando um delta como erro
136
     * @param  float  $value   valor a testar se é menor
137
     * @param  float  $compare valor com que comparar
138
     * @param  float   $delta   margem de erro para dizer se é menor
139
     * @return boolean          true se o valor for menor ou false caso contrário
140
     */
141 1
    public static function isLess($value, $compare, $delta = 0.005)
142
    {
143 1
        return ($value + $delta) < $compare;
144
    }
145
    
146
    /**
147
     * Converte um valor para a moeda Real já incluindo o símbolo
148
     * @param  float $value valor a ser formatado
149
     * @return string        valor já formatado e com o símbolo
150
     */
151 34
    public static function toMoney($value)
152
    {
153 34
        return 'R$ '.number_format($value, 2, ',', '.');
154
    }
155
156
    /**
157
     * Realiza uma busca binária num array ordenado usando uma função customizada
158
     * para comparação
159
     * @param  mixed $elem   elemento a ser procurado
160
     * @param  array $array  array contendo todos os elementos
161
     * @param  function $cmp_fn função que irá comparar dois elementos
162
     * @return mixed         retorna o valor do array referente a chave ou false caso não encontre
163
     */
164 13
    public static function binarySearch($elem, $array, $cmp_fn)
165
    {
166 13
        $bot = 0;
167 13
        $top = count($array) -1;
168 13
        while ($top >= $bot) {
169 13
            $p = floor(($top + $bot) / 2);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $p. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
170 13
            $o = $array[$p];
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $o. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
171 13
            $r = $cmp_fn($o, $elem);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $r. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
172 13
            if ($r < 0) {
173 13
                $bot = $p + 1;
174 13
            } elseif ($r > 0) {
175 13
                $top = $p - 1;
176
            } else {
177 13
                return $o;
178
            }
179
        }
180 1
        return false;
181
    }
182
183
    /**
184
     * Remove acentos e caracteres especiais do texto
185
     * @param  string $str string com caracteres especiais
186
     * @return string      texto no formato ANSI sem caracteres especiais
187
     */
188 13
    public static function removeAccent($str)
189
    {
190 13
        return strtr(
191 13
            utf8_decode($str),
192 13
            utf8_decode(self::ACCENT_CHARS),
193 13
            self::NORMAL_CHARS
194
        );
195
    }
196
197
    /**
198
     * Cria diretório com permissões
199
     * @param string $dir caminho da pasta a ser criada
200
     * @param int $access permissões da pasta
201
     */
202 5
    public static function createDirectory($dir, $access = 0711)
203
    {
204 5
        $oldUmask = umask(0);
0 ignored issues
show
Coding Style introduced by
$oldUmask does not seem to conform to the naming convention (^[a-z_][a-z0-9_]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
205 5
        if (!file_exists($dir)) {
206 5
            mkdir($dir, $access, true);
207
        }
208 5
        umask($oldUmask);
0 ignored issues
show
Coding Style introduced by
$oldUmask does not seem to conform to the naming convention (^[a-z_][a-z0-9_]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
209 5
    }
210
211
    /**
212
     * Retorna o módulo dos dígitos por 11
213
     * @param string $digitos dígitos para o cálculo
214
     * @return int            dígito do módulo 11
215
     */
216 33
    public static function getModulo11($digitos)
217
    {
218 33
        $sum = 0;
219 33
        $mul = 1;
220 33
        $len = strlen($digitos);
221 33
        for ($i = $len - 1; $i >= 0; $i--) {
222 33
            $mul++;
223 33
            $dig = $digitos[$i];
224 33
            $sum += $dig * $mul;
225 33
            if ($mul == 9) {
226 33
                $mul = 1; // reset
227
            }
228
        }
229 33
        return $sum % 11;
230
    }
231
232
    /**
233
     * Retorna o módulo dos dígitos por 10
234
     * @param string $digitos dígitos para o cálculo
235
     * @return int            dígito do módulo 10
236
     */
237 2
    public static function getModulo10($digitos)
238
    {
239 2
        $sum = 0;
240 2
        $mul = 1;
241 2
        $len = strlen($digitos);
242 2
        for ($i = $len - 1; $i >= 0; $i--) {
243 2
            $mul++;
244 2
            $dig = $digitos[$i];
245 2
            $term = $dig * $mul;
246 2
            $sum += ($dig == 9)?$dig:($term % 9);
247 2
            if ($mul == 2) {
248 2
                $mul = 0; // reset
249
            }
250
        }
251 2
        return $sum % 10;
252
    }
253
254
    /**
255
     * Retorna o Dígito de Auto-Conferência dos dígitos
256
     *
257
     * @param string $digitos
258
     * @param int $div Número divisor que determinará o resto da divisão
259
     * @param int $presente Informa o número padrão para substituição do excesso
260
     * @return int dígito verificador calculado
261
     */
262 33
    public static function getDAC($digitos, $div, $presente = 0)
263
    {
264 33
        $ext = $div % 10;
265 33
        if ($div == 10) {
266 1
            $ret = self::getModulo10($digitos);
267
        } else {
268 33
            $ret = self::getModulo11($digitos);
269
        }
270 33
        return ($ret <= $ext)? $presente: ($div - $ret);
271
    }
272
273 160
    public static function appendNode($element, $name, $text, $before = null)
274
    {
275 160
        $dom = $element->ownerDocument;
276 160
        if (is_null($before)) {
277 160
            $node = $element->appendChild($dom->createElement($name));
278
        } else {
279 9
            $node = $element->insertBefore($dom->createElement($name), $before);
280
        }
281 160
        $node->appendChild($dom->createTextNode($text));
282 160
        return $node;
283
    }
284
285 32
    public static function addAttribute($element, $name, $text)
286
    {
287 32
        $dom = $element->ownerDocument;
288 32
        $node = $element->appendChild($dom->createAttribute($name));
289 32
        $node->appendChild($dom->createTextNode($text));
290 32
        return $node;
291
    }
292
293 97
    public static function loadNode($element, $name, $exception = null)
294
    {
295 97
        $value = null;
296 97
        $list = $element->getElementsByTagName($name);
297 97
        if ($list->length > 0) {
298 96
            $value = $list->item(0)->nodeValue;
299 51
        } elseif (!is_null($exception)) {
300 1
            throw new \Exception($exception, 404);
301
        }
302 96
        return $value;
303
    }
304
305 48
    public static function nodeExists($element, $name)
306
    {
307 48
        $list = $element->getElementsByTagName($name);
308 48
        return ($list->length > 0) || ($element->nodeName == $name);
309
    }
310
311 31
    public static function findNode($element, $name, $exception = null)
312
    {
313 31
        if ($element->nodeName == $name) {
314 1
            return $element;
315
        }
316 31
        $list = $element->getElementsByTagName($name);
317 31
        if ($list->length == 0) {
318 1
            if (is_null($exception)) {
319 1
                $exception = 'Node "'.$name.'" not found on element "'.$element->nodeName.'"';
320
            }
321 1
            throw new \Exception($exception, 404);
322
        }
323 31
        return $list->item(0);
324
    }
325
326 16
    public static function mergeNodes($element, $other)
327
    {
328 16
        $dom = $element->ownerDocument;
329 16
        foreach ($other->childNodes as $node) {
330 16
            $node = $dom->importNode($node, true);
331 16
            $list = $element->getElementsByTagName($node->nodeName);
332 16
            if ($list->length == 1) {
333 10
                $element->replaceChild($node, $list->item(0));
334
            } else {
335 16
                $element->appendChild($node);
336
            }
337
        }
338 16
        return $element;
339
    }
340
}
341