Passed
Pull Request — master (#412)
by
unknown
06:34
created

Common::modulo11()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
nc 13
nop 1
dl 0
loc 21
ccs 0
cts 21
cp 0
crap 42
rs 8.9617
c 0
b 0
f 0
1
<?php
2
3
namespace NFePHP\DA\Legacy;
4
5
class Common
6
{
7
8
    /**
9
     * Extrai o valor do node DOM
10
     * @param  object $theObj Instancia de DOMDocument ou DOMElement
11
     * @param  string $keyName identificador da TAG do xml
12
     * @param  string $extraTextBefore prefixo do retorno
13
     * @param  string extraTextAfter sufixo do retorno
14
     * @param  number itemNum numero do item a ser retornado
15
     * @return string
16
     */
17
    protected function getTagValue($theObj, $keyName, $extraTextBefore = '', $extraTextAfter = '', $itemNum = 0)
18
    {
19
        if (empty($theObj)) {
20
            return '';
21
        }
22
        $vct = $theObj->getElementsByTagName($keyName)->item($itemNum);
23
        if (isset($vct)) {
24
            $value = trim($vct->nodeValue);
25
            if (strpos($value, '&') !== false) {
26
                //existe um & na string, então deve ser uma entidade
27
                $value = html_entity_decode($value);
28
            }
29
            return $extraTextBefore . $value . $extraTextAfter;
30
        }
31
        return '';
32
    }
33
34
    /**
35
     * Recupera e reformata a data do padrão da NFe para dd/mm/aaaa
36
     * @author Marcos Diez
37
     * @param  DOM    $theObj
38
     * @param  string $keyName   identificador da TAG do xml
39
     * @param  string $extraText prefixo do retorno
40
     * @return string
41
     */
42
    protected function getTagDate($theObj, $keyName, $extraText = '')
43
    {
44
        if (!isset($theObj) || !is_object($theObj)) {
45
            return '';
46
        }
47
        $vct = $theObj->getElementsByTagName($keyName)->item(0);
48
        if (isset($vct)) {
49
            $theDate = explode("-", $vct->nodeValue);
50
            return $extraText . $theDate[2] . "/" . $theDate[1] . "/" . $theDate[0];
51
        }
52
        return '';
53
    }
54
55
    /**
56
     * Recupera e reformata a data do padrão da NFe para mm/aaaa
57
     * @author Jandelson Oliveira
58
     * @param  DOM    $theObj
59
     * @param  string $keyName   identificador da TAG do xml
60
     * @param  string $extraText prefixo do retorno
61
     * @return string
62
     */
63
    protected function getTagDateMonthYear($theObj, $keyName, $extraText = '')
64
    {
65
        if (!isset($theObj) || !is_object($theObj)) {
66
            return '';
67
        }
68
        $vct = $theObj->getElementsByTagName($keyName)->item(0);
69
        if (isset($vct)) {
70
            $theDate = explode("-", $vct->nodeValue);
71
            return $extraText . $theDate[1] . "/" . $theDate[0];
72
        }
73
        return '';
74
    }
75
76
    /**
77
     * camcula digito de controle modulo 11
78
     * @param  string $numero
79
     * @return integer modulo11 do numero passado
80
     */
81
    protected function modulo11($numero = '')
82
    {
83
        if ($numero == '') {
84
            return '';
85
        }
86
        $numero = (string) $numero;
87
        $tamanho = strlen($numero);
88
        $soma = 0;
89
        $mult = 2;
90
        for ($i = $tamanho - 1; $i >= 0; $i--) {
91
            $digito = (int) $numero[$i];
92
            $r = $digito * $mult;
93
            $soma += $r;
94
            $mult++;
95
            if ($mult == 10) {
96
                $mult = 2;
97
            }
98
        }
99
        $resto = ($soma * 10) % 11;
100
        return ($resto == 10 || $resto == 0) ? 1 : $resto;
101
    }
102
103
    /**
104
     * Converte datas no formato YMD (ex. 2009-11-02) para o formato brasileiro 02/11/2009)
105
     * @param  string $data Parâmetro extraido da NFe
106
     * @return string Formatada para apresentação da data no padrão brasileiro
107
     */
108
    protected function ymdTodmy($data = '')
109
    {
110
        if ($data == '') {
111
            return '';
112
        }
113
        $needle = "/";
114
        if (strstr($data, "-")) {
115
            $needle = "-";
116
        }
117
        $dt = explode($needle, $data);
118
        return "$dt[2]/$dt[1]/$dt[0]";
119
    }
120
121
    /**
122
     * Converte data da NFe YYYY-mm-ddThh:mm:ss-03:00 para timestamp unix
123
     *
124
     * @param string $input
125
     *
126
     * @return integer
127
     */
128
    public function toTimestamp($input)
129
    {
130
        $regex = '^(2[0-9][0-9][0-9])[-](0?[1-9]'
131
            . '|1[0-2])[-](0?[1-9]'
132
            . '|[12][0-9]'
133
            . '|3[01])T([0-9]|0[0-9]'
134
            . '|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]-(00|01|02|03|04):00$';
135
136
        if (!preg_match("/$regex/", $input)) {
137
            return '';
138
        }
139
        return \DateTime::createFromFormat("Y-m-d\TH:i:sP", $input)->getTimestamp();
140
    }
141
142
    /**
143
     * Função de formatação de strings onde o cerquilha # é um coringa
144
     * que será substituido por digitos contidos em campo.
145
     * @param  string $campo   String a ser formatada
146
     * @param  string $mascara Regra de formatção da string (ex. ##.###.###/####-##)
147
     * @return string Retorna o campo formatado
148
     */
149
    protected function formatField($campo = '', $mascara = '')
150
    {
151
        if ($campo == '' || $mascara == '') {
152
            return $campo;
153
        }
154
        //remove qualquer formatação que ainda exista
155
        $sLimpo = preg_replace("(/[' '-./ t]/)", '', $campo);
156
        // pega o tamanho da string e da mascara
157
        $tCampo = strlen($sLimpo);
158
        $tMask = strlen($mascara);
159
        if ($tCampo > $tMask) {
160
            $tMaior = $tCampo;
161
        } else {
162
            $tMaior = $tMask;
163
        }
164
        //contar o numero de cerquilhas da mascara
165
        $aMask = str_split($mascara);
166
        $z = 0;
167
        $flag = false;
168
        foreach ($aMask as $letra) {
169
            if ($letra == '#') {
170
                $z++;
171
            }
172
        }
173
        if ($z > $tCampo) {
174
            //o campo é menor que esperado
175
            $flag = true;
176
        }
177
        //cria uma variável grande o suficiente para conter os dados
178
        $sRetorno = '';
179
        $sRetorno = str_pad($sRetorno, $tCampo + $tMask, " ", STR_PAD_LEFT);
180
        //pega o tamanho da string de retorno
181
        $tRetorno = strlen($sRetorno);
182
        //se houve entrada de dados
183
        if ($sLimpo != '' && $mascara != '') {
184
            //inicia com a posição do ultimo digito da mascara
185
            $x = $tMask;
186
            $y = $tCampo;
187
            $cI = 0;
188
            for ($i = $tMaior - 1; $i >= 0; $i--) {
189
                if ($cI < $z) {
190
                    // e o digito da mascara é # trocar pelo digito do campo
191
                    // se o inicio da string da mascara for atingido antes de terminar
192
                    // o campo considerar #
193
                    if ($x > 0) {
194
                        $digMask = $mascara[--$x];
195
                    } else {
196
                        $digMask = '#';
197
                    }
198
                    //se o fim do campo for atingido antes do fim da mascara
199
                    //verificar se é ( se não for não use
200
                    if ($digMask == '#') {
201
                        $cI++;
202
                        if ($y > 0) {
203
                            $sRetorno[--$tRetorno] = $sLimpo[--$y];
204
                        } else {
205
                            //$sRetorno[--$tRetorno] = '';
206
                        }
207
                    } else {
208
                        if ($y > 0) {
209
                            $sRetorno[--$tRetorno] = $mascara[$x];
210
                        } else {
211
                            if ($mascara[$x] == '(') {
212
                                $sRetorno[--$tRetorno] = $mascara[$x];
213
                            }
214
                        }
215
                        $i++;
216
                    }
217
                }
218
            }
219
            if (!$flag) {
220
                if ($mascara[0] != '#') {
221
                    $sRetorno = '(' . trim($sRetorno);
222
                }
223
            }
224
            return trim($sRetorno);
225
        } else {
226
            return '';
227
        }
228
    }
229
230
    protected function tipoPag($tPag)
231
    {
232
        switch ($tPag) {
233
            case '01':
234
                $tPagNome = 'Dinheiro';
235
                break;
236
            case '02':
237
                $tPagNome = 'Cheque';
238
                break;
239
            case '03':
240
                $tPagNome = 'Cartão de Crédito';
241
                break;
242
            case '04':
243
                $tPagNome = 'Cartão de Débito';
244
                break;
245
            case '05':
246
                $tPagNome = 'Crédito Loja';
247
                break;
248
            case '10':
249
                $tPagNome = 'Vale Alimentação';
250
                break;
251
            case '11':
252
                $tPagNome = 'Vale Refeição';
253
                break;
254
            case '12':
255
                $tPagNome = 'Vale Presente';
256
                break;
257
            case '13':
258
                $tPagNome = 'Vale Combustível';
259
                break;
260
            case '14':
261
                $tPagNome = 'Duplicata Mercantil';
262
                break;
263
            case '15':
264
                $tPagNome = 'Boleto Bancário';
265
                break;
266
            case '90':
267
                $tPagNome = 'Sem Pagamento';
268
                break;
269
            case '99':
270
                $tPagNome = 'Outros';
271
                break;
272
            default:
273
                $tPagNome = '';
274
                // Adicionado default para impressão de notas da 3.10
275
        }
276
        return $tPagNome;
277
    }
278
}
279