Passed
Push — master ( c1d1cf...f48ccd )
by Francimar
03:58
created

Util::nodeExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
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 103
    public static function toCurrency($value, $places = 2)
48
    {
49 103
        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 85
    public static function toFloat($value, $places = 4)
60
    {
61 85
        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 26
    public static function toDateTime($time)
70
    {
71 26
        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 23
    public static function toHex($string)
80
    {
81 23
        $hexstr = unpack('H*', $string);
82 23
        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 25
    public static function padDigit($text, $len, $digit = '0')
93
    {
94 25
        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 16
    public static function padText($str, $len, $txt = '0')
106
    {
107 16
        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 27
    public static function isGreater($value, $compare, $delta = 0.005)
130
    {
131 27
        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
    public static function isLess($value, $compare, $delta = 0.005)
142
    {
143
        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 27
    public static function toMoney($value)
152
    {
153 27
        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 9
    public static function binarySearch($elem, $array, $cmp_fn)
165
    {
166 9
        $bot = 0;
167 9
        $top = count($array) -1;
168 9
        while ($top >= $bot) {
169 9
            $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 9
            $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 9
            $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 9
            if ($r < 0) {
173 9
                $bot = $p + 1;
174 9
            } elseif ($r > 0) {
175 9
                $top = $p - 1;
176 9
            } else {
177 9
                return $o;
178
            }
179 9
        }
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 9
    public static function removeAccent($str)
189
    {
190 9
        return strtr(
191 9
            utf8_decode($str),
192 9
            utf8_decode(self::ACCENT_CHARS),
193
            self::NORMAL_CHARS
194 9
        );
195
    }
196
197
    /**
198
     * Retorna o módulo dos dígitos por 11
199
     * @param string $digitos dígitos para o cálculo
200
     * @return int            dígito do módulo 11
201
     */
202 25
    public static function getModulo11($digitos)
203
    {
204 25
        $sum = 0;
205 25
        $mul = 1;
206 25
        $len = strlen($digitos);
207 25
        for ($i = $len - 1; $i >= 0; $i--) {
208 25
            $mul++;
209 25
            $dig = $digitos[$i];
210 25
            $sum += $dig * $mul;
211 25
            if ($mul == 9) {
212 25
                $mul = 1; // reset
213 25
            }
214 25
        }
215 25
        return $sum % 11;
216
    }
217
218
    /**
219
     * Retorna o módulo dos dígitos por 10
220
     * @param string $digitos dígitos para o cálculo
221
     * @return int            dígito do módulo 10
222
     */
223
    public static function getModulo10($digitos)
224
    {
225
        $sum = 0;
226
        $mul = 1;
227
        $len = strlen($digitos);
228
        for ($i = $len - 1; $i >= 0; $i--) {
229
            $mul++;
230
            $dig = $digitos[$i];
231
            $term = $dig * $mul;
232
            $sum += ($dig == 9)?$dig:($term % 9);
233
            if ($mul == 2) {
234
                $mul = 0; // reset
235
            }
236
        }
237
        return $sum % 10;
238
    }
239
240
    /**
241
     * Retorna o Dígito de Auto-Conferência dos dígitos
242
     *
243
     * @param string $digitos
244
     * @param int $div Número divisor que determinará o resto da divisão
245
     * @param int $presente Informa o número padrão para substituição do excesso
246
     * @return int dígito verificador calculado
247
     */
248 25
    public static function getDAC($digitos, $div, $presente = 0)
249
    {
250 25
        $ext = $div % 10;
251 25
        if ($div == 10) {
252
            $ret = self::getModulo10($digitos);
253
        } else {
254 25
            $ret = self::getModulo11($digitos);
255
        }
256 25
        return ($ret <= $ext)? $presente: ($div - $ret);
257
    }
258
259 146
    public static function appendNode($element, $name, $text, $before = null)
260
    {
261 146
        $dom = $element->ownerDocument;
262 146
        if (is_null($before)) {
263 146
            $node = $element->appendChild($dom->createElement($name));
264 146
        } else {
265 5
            $node = $element->insertBefore($dom->createElement($name), $before);
266
        }
267 146
        $node->appendChild($dom->createTextNode($text));
268 146
        return $node;
269
    }
270
271 86
    public static function loadNode($element, $name, $exception = null)
272
    {
273 86
        $value = null;
274 86
        $list = $element->getElementsByTagName($name);
275 86
        if ($list->length > 0) {
276 85
            $value = $list->item(0)->nodeValue;
277 86
        } elseif (!is_null($exception)) {
278 1
            throw new \Exception($exception, 404);
279
        }
280 85
        return $value;
281
    }
282
283 25
    public static function nodeExists($element, $name)
284
    {
285 25
        $list = $element->getElementsByTagName($name);
286 25
        return $list->length > 0;
287
    }
288
289 6
    public static function findNode($element, $name, $exception = null)
290
    {
291 6
        $list = $element->getElementsByTagName($name);
292 6
        if ($list->length == 0) {
293
            if (is_null($exception)) {
294
                $exception = 'Node "'.$name.'" not found on element "'.$element->nodeName.'"';
295
            }
296
            throw new \Exception($exception, 404);
297
        }
298 6
        return $list->item(0);
299
    }
300
}
301