Passed
Pull Request — master (#446)
by
unknown
02:49
created

Common   C

Complexity

Total Complexity 57

Size/Duplication

Total Lines 281
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 281
ccs 0
cts 205
cp 0
rs 5.04
c 0
b 0
f 0
wmc 57
lcom 0
cbo 1

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getTagValue() 0 16 4
B modulo11() 0 21 6
A ymdTodmy() 0 12 3
A getTagDate() 0 12 4
A toTimestamp() 0 13 2
A toDateTime() 0 8 2
F formatField() 0 80 18
D tipoPag() 0 60 18

How to fix   Complexity   

Complex Class

Complex classes like Common 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 Common, and based on these observations, apply Extract Interface, too.

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]-(01|02|03|04|05):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
     * Converte data da NFe YYYY-mm-ddThh:mm:ss-03:00 para \DateTime
123
     *
124
     * @param string $input
125
     *
126
     * @return \DateTime
127
     */
128
    public function toDateTime($input)
129
    {
130
        try {
131
            return \DateTime::createFromFormat("Y-m-d\TH:i:sP", $input);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \DateTime::createFromFor...m-d\\TH:i:sP', $input); of type DateTime|false adds false to the return on line 131 which is incompatible with the return type documented by NFePHP\DA\Legacy\Common::toDateTime of type DateTime|null. It seems like you forgot to handle an error condition.
Loading history...
132
        } catch (\Exception $e) {
133
            return null;
134
        }
135
    }
136
137
    /**
138
     * Função de formatação de strings onde o cerquilha # é um coringa
139
     * que será substituido por digitos contidos em campo.
140
     * @param  string $campo   String a ser formatada
141
     * @param  string $mascara Regra de formatção da string (ex. ##.###.###/####-##)
142
     * @return string Retorna o campo formatado
143
     */
144
    protected function formatField($campo = '', $mascara = '')
145
    {
146
        if ($campo == '' || $mascara == '') {
147
            return $campo;
148
        }
149
        //remove qualquer formatação que ainda exista
150
        $sLimpo = preg_replace("(/[' '-./ t]/)", '', $campo);
151
        // pega o tamanho da string e da mascara
152
        $tCampo = strlen($sLimpo);
153
        $tMask = strlen($mascara);
154
        if ($tCampo > $tMask) {
155
            $tMaior = $tCampo;
156
        } else {
157
            $tMaior = $tMask;
158
        }
159
        //contar o numero de cerquilhas da mascara
160
        $aMask = str_split($mascara);
161
        $z = 0;
162
        $flag = false;
163
        foreach ($aMask as $letra) {
164
            if ($letra == '#') {
165
                $z++;
166
            }
167
        }
168
        if ($z > $tCampo) {
169
            //o campo é menor que esperado
170
            $flag = true;
171
        }
172
        //cria uma variável grande o suficiente para conter os dados
173
        $sRetorno = '';
174
        $sRetorno = str_pad($sRetorno, $tCampo + $tMask, " ", STR_PAD_LEFT);
175
        //pega o tamanho da string de retorno
176
        $tRetorno = strlen($sRetorno);
177
        //se houve entrada de dados
178
        if ($sLimpo != '' && $mascara != '') {
179
            //inicia com a posição do ultimo digito da mascara
180
            $x = $tMask;
181
            $y = $tCampo;
182
            $cI = 0;
183
            for ($i = $tMaior - 1; $i >= 0; $i--) {
184
                if ($cI < $z) {
185
                    // e o digito da mascara é # trocar pelo digito do campo
186
                    // se o inicio da string da mascara for atingido antes de terminar
187
                    // o campo considerar #
188
                    if ($x > 0) {
189
                        $digMask = $mascara[--$x];
190
                    } else {
191
                        $digMask = '#';
192
                    }
193
                    //se o fim do campo for atingido antes do fim da mascara
194
                    //verificar se é ( se não for não use
195
                    if ($digMask == '#') {
196
                        $cI++;
197
                        if ($y > 0) {
198
                            $sRetorno[--$tRetorno] = $sLimpo[--$y];
199
                        } else {
200
                            //$sRetorno[--$tRetorno] = '';
201
                        }
202
                    } else {
203
                        if ($y > 0) {
204
                            $sRetorno[--$tRetorno] = $mascara[$x];
205
                        } else {
206
                            if ($mascara[$x] == '(') {
207
                                $sRetorno[--$tRetorno] = $mascara[$x];
208
                            }
209
                        }
210
                        $i++;
211
                    }
212
                }
213
            }
214
            if (!$flag) {
215
                if ($mascara[0] != '#') {
216
                    $sRetorno = '(' . trim($sRetorno);
217
                }
218
            }
219
            return trim($sRetorno);
220
        } else {
221
            return '';
222
        }
223
    }
224
225
    protected function tipoPag($tPag)
226
    {
227
        switch ($tPag) {
228
            case '01':
229
                $tPagNome = 'Dinheiro';
230
                break;
231
            case '02':
232
                $tPagNome = 'Cheque';
233
                break;
234
            case '03':
235
                $tPagNome = 'Cartão de Crédito';
236
                break;
237
            case '04':
238
                $tPagNome = 'Cartão de Débito';
239
                break;
240
            case '05':
241
                $tPagNome = 'Crédito Loja';
242
                break;
243
            case '10':
244
                $tPagNome = 'Vale Alimentação';
245
                break;
246
            case '11':
247
                $tPagNome = 'Vale Refeição';
248
                break;
249
            case '12':
250
                $tPagNome = 'Vale Presente';
251
                break;
252
            case '13':
253
                $tPagNome = 'Vale Combustível';
254
                break;
255
            case '14':
256
                $tPagNome = 'Duplicata Mercantil';
257
                break;
258
            case '15':
259
                $tPagNome = 'Boleto Bancário';
260
                break;
261
            case '16':
262
                $tPagNome = 'Depósito Bancário';
263
                break;
264
            case '17':
265
                $tPagNome = 'Pagamento Instantâneo (PIX)';
266
                break;
267
            case '18':
268
                $tPagNome = 'Transferência bancária, Carteira Digital';
269
                break;
270
            case '19':
271
                $tPagNome = 'Programa de fidelidade, Cashback, Crédito Virtual';
272
                break;
273
            case '90':
274
                $tPagNome = 'Sem Pagamento';
275
                break;
276
            case '99':
277
                $tPagNome = 'Outros';
278
                break;
279
            default:
280
                $tPagNome = '';
281
                // Adicionado default para impressão de notas da 3.10
282
        }
283
        return $tPagNome;
284
    }
285
}
286