Completed
Pull Request — master (#274)
by Roberto
06:36
created

Common::toTimestamp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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