Completed
Pull Request — master (#436)
by Roberto
03:35
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
     * camcula digito de controle modulo 11
57
     * @param  string $numero
58
     * @return integer modulo11 do numero passado
59
     */
60
    protected function modulo11($numero = '')
61
    {
62
        if ($numero == '') {
63
            return '';
64
        }
65
        $numero = (string) $numero;
66
        $tamanho = strlen($numero);
67
        $soma = 0;
68
        $mult = 2;
69
        for ($i = $tamanho - 1; $i >= 0; $i--) {
70
            $digito = (int) $numero[$i];
71
            $r = $digito * $mult;
72
            $soma += $r;
73
            $mult++;
74
            if ($mult == 10) {
75
                $mult = 2;
76
            }
77
        }
78
        $resto = ($soma * 10) % 11;
79
        return ($resto == 10 || $resto == 0) ? 1 : $resto;
80
    }
81
82
    /**
83
     * Converte datas no formato YMD (ex. 2009-11-02) para o formato brasileiro 02/11/2009)
84
     * @param  string $data Parâmetro extraido da NFe
85
     * @return string Formatada para apresentação da data no padrão brasileiro
86
     */
87
    protected function ymdTodmy($data = '')
88
    {
89
        if ($data == '') {
90
            return '';
91
        }
92
        $needle = "/";
93
        if (strstr($data, "-")) {
94
            $needle = "-";
95
        }
96
        $dt = explode($needle, $data);
97
        return "$dt[2]/$dt[1]/$dt[0]";
98
    }
99
100
    /**
101
     * Converte data da NFe YYYY-mm-ddThh:mm:ss-03:00 para timestamp unix
102
     *
103
     * @param string $input
104
     *
105
     * @return integer
106
     */
107
    public function toTimestamp($input)
108
    {
109
        $regex = '^(2[0-9][0-9][0-9])[-](0?[1-9]'
110
            . '|1[0-2])[-](0?[1-9]'
111
            . '|[12][0-9]'
112
            . '|3[01])T(0[0-9]'
113
            . '|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]-(00|01|02|03|04):00$';
114
        
115
        if (!preg_match("/$regex/", $input)) {
116
            return 0;
117
        }
118
        return \DateTime::createFromFormat("Y-m-d\TH:i:sP", $input)->getTimestamp();
119
    }
120
121
    /**
122
     * Função de formatação de strings onde o cerquilha # é um coringa
123
     * que será substituido por digitos contidos em campo.
124
     * @param  string $campo   String a ser formatada
125
     * @param  string $mascara Regra de formatção da string (ex. ##.###.###/####-##)
126
     * @return string Retorna o campo formatado
127
     */
128
    protected function formatField($campo = '', $mascara = '')
129
    {
130
        if ($campo == '' || $mascara == '') {
131
            return $campo;
132
        }
133
        //remove qualquer formatação que ainda exista
134
        $sLimpo = preg_replace("(/[' '-./ t]/)", '', $campo);
135
        // pega o tamanho da string e da mascara
136
        $tCampo = strlen($sLimpo);
137
        $tMask = strlen($mascara);
138
        if ($tCampo > $tMask) {
139
            $tMaior = $tCampo;
140
        } else {
141
            $tMaior = $tMask;
142
        }
143
        //contar o numero de cerquilhas da mascara
144
        $aMask = str_split($mascara);
145
        $z = 0;
146
        $flag = false;
147
        foreach ($aMask as $letra) {
148
            if ($letra == '#') {
149
                $z++;
150
            }
151
        }
152
        if ($z > $tCampo) {
153
            //o campo é menor que esperado
154
            $flag = true;
155
        }
156
        //cria uma variável grande o suficiente para conter os dados
157
        $sRetorno = '';
158
        $sRetorno = str_pad($sRetorno, $tCampo + $tMask, " ", STR_PAD_LEFT);
159
        //pega o tamanho da string de retorno
160
        $tRetorno = strlen($sRetorno);
161
        //se houve entrada de dados
162
        if ($sLimpo != '' && $mascara != '') {
163
            //inicia com a posição do ultimo digito da mascara
164
            $x = $tMask;
165
            $y = $tCampo;
166
            $cI = 0;
167
            for ($i = $tMaior - 1; $i >= 0; $i--) {
168
                if ($cI < $z) {
169
                    // e o digito da mascara é # trocar pelo digito do campo
170
                    // se o inicio da string da mascara for atingido antes de terminar
171
                    // o campo considerar #
172
                    if ($x > 0) {
173
                        $digMask = $mascara[--$x];
174
                    } else {
175
                        $digMask = '#';
176
                    }
177
                    //se o fim do campo for atingido antes do fim da mascara
178
                    //verificar se é ( se não for não use
179
                    if ($digMask == '#') {
180
                        $cI++;
181
                        if ($y > 0) {
182
                            $sRetorno[--$tRetorno] = $sLimpo[--$y];
183
                        } else {
184
                            //$sRetorno[--$tRetorno] = '';
185
                        }
186
                    } else {
187
                        if ($y > 0) {
188
                            $sRetorno[--$tRetorno] = $mascara[$x];
189
                        } else {
190
                            if ($mascara[$x] == '(') {
191
                                $sRetorno[--$tRetorno] = $mascara[$x];
192
                            }
193
                        }
194
                        $i++;
195
                    }
196
                }
197
            }
198
            if (!$flag) {
199
                if ($mascara[0] != '#') {
200
                    $sRetorno = '(' . trim($sRetorno);
201
                }
202
            }
203
            return trim($sRetorno);
204
        } else {
205
            return '';
206
        }
207
    }
208
209
    protected function tipoPag($tPag)
210
    {
211
        switch ($tPag) {
212
            case '01':
213
                $tPagNome = 'Dinheiro';
214
                break;
215
            case '02':
216
                $tPagNome = 'Cheque';
217
                break;
218
            case '03':
219
                $tPagNome = 'Cartão de Crédito';
220
                break;
221
            case '04':
222
                $tPagNome = 'Cartão de Débito';
223
                break;
224
            case '05':
225
                $tPagNome = 'Crédito Loja';
226
                break;
227
            case '10':
228
                $tPagNome = 'Vale Alimentação';
229
                break;
230
            case '11':
231
                $tPagNome = 'Vale Refeição';
232
                break;
233
            case '12':
234
                $tPagNome = 'Vale Presente';
235
                break;
236
            case '13':
237
                $tPagNome = 'Vale Combustível';
238
                break;
239
            case '14':
240
                $tPagNome = 'Duplicata Mercantil';
241
                break;
242
            case '15':
243
                $tPagNome = 'Boleto Bancário';
244
                break;
245
            case '16':
246
                $tPagNome = 'Depósito Bancário';
247
                break;
248
            case '17':
249
                $tPagNome = 'Pagamento Instantâneo (PIX)';
250
                break;
251
            case '18':
252
                $tPagNome = 'Transferência bancária, Carteira Digital';
253
                break;
254
            case '19':
255
                $tPagNome = 'Programa de fidelidade, Cashback, Crédito Virtual';
256
                break;
257
            case '90':
258
                $tPagNome = 'Sem Pagamento';
259
                break;
260
            case '99':
261
                $tPagNome = 'Outros';
262
                break;
263
            default:
264
                $tPagNome = '';
265
                // Adicionado default para impressão de notas da 3.10
266
        }
267
        return $tPagNome;
268
    }
269
}
270