Test Failed
Push — master ( f8eb03...8feb3a )
by Francimar
06:03
created

Configuracao::fromArray()   C

Complexity

Conditions 12
Paths 129

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 27
cts 27
cp 1
rs 6.725
c 0
b 0
f 0
cc 12
nc 129
nop 1
crap 12

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
use NFe\Entity\Emitente;
31
use NFe\Database\Estatico;
32
33
/**
34
 * Fornece informações importante para a geração e envio das notas fiscais
35
 */
36
class Configuracao
0 ignored issues
show
Complexity introduced by
This class has a complexity of 55 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
37
{
38
    /**
39
     * @var \NFe\Database\Banco
40
     */
41
    private $banco;
42
    /**
43
     * @var \NFe\Entity\Emitente
44
     */
45
    private $emitente;
46
    /**
47
     * @var Evento
48
     */
49
    private $evento;
50
    /**
51
     * @var Certificado
52
     */
53
    private $certificado;
54
    /**
55
     * @var string
56
     */
57
    private $token;
58
    /**
59
     * @var string
60
     */
61
    private $csc;
62
    /**
63
     * @var string
64
     */
65
    private $token_ibpt;
66
    /**
67
     * @var int
68
     */
69
    private $tempo_limite;
70
    /**
71
     * @var string
72
     */
73
    private $sincrono;
74
    /**
75
     * @var int
76
     */
77
    private $offline;
78
79
    /**
80
     * @param mixed $configuracao array ou instância
81
     */
82 102
    public function __construct($configuracao = [])
83
    {
84 102
        $this->fromArray($configuracao);
85 102
    }
86
87
    /**
88
     * Banco que fornece informações sobre items da nota como: Códigos e Taxas
89
     * @return \NFe\Database\Banco
90
     */
91 72
    public function getBanco()
92
    {
93 72
        return $this->banco;
94
    }
95
96
    /**
97
     * Banco que fornece informações sobre items da nota como: Códigos e Taxas
98
     * @param \NFe\Database\Banco $banco
99
     * @return self
100
     */
101 102
    public function setBanco($banco)
102
    {
103 102
        $this->banco = $banco;
104 102
        return $this;
105
    }
106
107
    /**
108
     * Emitente da nota fiscal
109
     * @return \NFe\Entity\Emitente
110
     */
111 47
    public function getEmitente()
112
    {
113 47
        return $this->emitente;
114
    }
115
116
    /**
117
     * Emitente da nota fiscal
118
     * @param \NFe\Entity\Emitente $emitente
119
     * @return self
120
     */
121 102
    public function setEmitente($emitente)
122
    {
123 102
        $this->emitente = $emitente;
124 102
        return $this;
125
    }
126
127
    /**
128
     * Informa a instancia que receberá os eventos do processamento das notas
129
     * @return Evento
130
     */
131 9
    public function getEvento()
132
    {
133 9
        return $this->evento;
134
    }
135
136
    /**
137
     * Informa a instancia que receberá os eventos do processamento das notas
138
     * @param Evento $evento
139
     * @return self
140
     */
141 102
    public function setEvento($evento)
142
    {
143 102
        $this->evento = $evento;
144 102
        return $this;
145
    }
146
147
    /**
148
     * Certificado para assinar os XMLs
149
     * @return Certificado
150
     */
151 105
    public function getCertificado()
152
    {
153 105
        return $this->certificado;
154
    }
155
156
    /**
157
     * Informa o certificado para assinar os XMLs
158
     * @param Certificado $certificado
159
     * @return self
160
     */
161 102
    public function setCertificado($certificado)
162
    {
163 102
        $this->certificado = $certificado;
164 102
        return $this;
165
    }
166
167
    /**
168
     * Conteúdo da chave pública ou certificado no formato PEM
169
     * @return string
170
     * @deprecated Use getCertificado()->getChavePublica
171
     */
172 34
    public function getChavePublica()
173
    {
174 34
        return $this->getCertificado()->getChavePublica();
175
    }
176
177
    /**
178
     * Conteúdo da chave pública ou certificado no formato PEM
179
     * @param string $chave_publica
180
     * @return self
181
     * @deprecated Use getCertificado()->setChavePublica
182
     */
183 1
    public function setChavePublica($chave_publica)
184
    {
185 1
        $this->getCertificado()->setChavePublica($chave_publica);
186 1
        return $this;
187
    }
188
189
    /**
190
     * Conteúdo da chave privada do certificado no formato PEM
191
     * @return string
192
     * @deprecated Use getCertificado()->getChavePrivada
193
     */
194 34
    public function getChavePrivada()
195
    {
196 34
        return $this->getCertificado()->getChavePrivada();
197
    }
198
199
    /**
200
     * Conteúdo da chave privada do certificado no formato PEM
201
     * @param string $chave_privada
202
     * @return self
203
     * @deprecated Use getCertificado()->setChavePrivada
204
     */
205 1
    public function setChavePrivada($chave_privada)
206
    {
207 1
        $this->getCertificado()->setChavePrivada($chave_privada);
208 1
        return $this;
209
    }
210
211
    /**
212
     * Informa o caminho do arquivo da chave pública ou certificado no formato
213
     * PEM
214
     * @return string
215
     * @deprecated Use getCertificado()->getArquivoChavePublica
216
     */
217 22
    public function getArquivoChavePublica()
218
    {
219 22
        return $this->getCertificado()->getArquivoChavePublica();
220
    }
221
222
    /**
223
     * Informa o caminho do arquivo da chave pública ou certificado no formato
224
     * PEM
225
     * @param string $arquivo_chave_publica
226
     * @return self
227
     * @deprecated Use getCertificado()->setArquivoChavePublica
228
     */
229 102
    public function setArquivoChavePublica($arquivo_chave_publica)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $arquivo_chave_publica exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
230
    {
231 102
        $this->getCertificado()->setArquivoChavePublica($arquivo_chave_publica);
232 102
        return $this;
233
    }
234
235
    /**
236
     * Caminho do arquivo da chave privada do certificado no formato PEM
237
     * @return string
238
     * @deprecated Use getCertificado()->getArquivoChavePrivada
239
     */
240 22
    public function getArquivoChavePrivada()
241
    {
242 22
        return $this->getCertificado()->getArquivoChavePrivada();
243
    }
244
245
    /**
246
     * Altera o caminho do arquivo da chave privada do certificado no formato PEM
247
     * @param string $arquivo_chave_privada
248
     * @return self
249
     * @deprecated Use getCertificado()->setArquivoChavePrivada
250
     */
251 102
    public function setArquivoChavePrivada($arquivo_chave_privada)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $arquivo_chave_privada exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
252
    {
253 102
        $this->getCertificado()->setArquivoChavePrivada($arquivo_chave_privada);
254 102
        return $this;
255
    }
256
257
    /**
258
     * Data de expiração do certificado em timestamp
259
     * @return int
260
     * @deprecated Use getCertificado()->getExpiracao
261
     */
262 1
    public function getExpiracao()
263
    {
264 1
        return $this->getCertificado()->getExpiracao();
265
    }
266
267
    /**
268
     * Token do CSC
269
     * @return string
270
     */
271 31
    public function getToken()
272
    {
273 31
        return $this->token;
274
    }
275
276
    /**
277
     * Informa o token do CSC, geralmente 000001
278
     * @param string $token
279
     * @return self
280
     */
281 102
    public function setToken($token)
282
    {
283 102
        $this->token = $token;
284 102
        return $this;
285
    }
286
287
    /**
288
     * Código do contribuinte para emissão de nota fiscal
289
     * @return string
290
     */
291 31
    public function getCSC()
292
    {
293 31
        return $this->csc;
294
    }
295
296
    /**
297
     * Informa o código do contribuinte para emissão de nota fiscal
298
     * @param string $csc
299
     * @return self
300
     */
301 102
    public function setCSC($csc)
302
    {
303 102
        $this->csc = $csc;
304 102
        return $this;
305
    }
306
307
    /**
308
     * Token IBPT para consulta de impostos online
309
     */
310 37
    public function getTokenIBPT()
311
    {
312 37
        return $this->token_ibpt;
313
    }
314
315 102
    public function setTokenIBPT($token_ibpt)
316
    {
317 102
        $this->token_ibpt = $token_ibpt;
318 102
        return $this;
319
    }
320
321
    /**
322
     * Tempo limite em segundos nas conexões com os Web services, 0 para sem tempo limite
323
     */
324 24
    public function getTempoLimite()
325
    {
326 24
        return $this->tempo_limite;
327
    }
328
329 102
    public function setTempoLimite($tempo_limite)
330
    {
331 102
        $this->tempo_limite = intval($tempo_limite);
332 102
        return $this;
333
    }
334
335
    /**
336
     * Informa se o processo de autorização da nota é síncrono ou assíncrono
337
     */
338 8
    public function getSincrono($normalize = false)
339
    {
340 8
        if (!$normalize) {
341 3
            return $this->sincrono;
342
        }
343 6
        return $this->isSincrono()?'1':'0';
344
    }
345
346
    /**
347
     * Informa se o processo de autorização da nota é síncrono ou assíncrono
348
     */
349 6
    public function isSincrono()
350
    {
351 6
        return $this->sincrono == 'Y';
352
    }
353
354 102
    public function setSincrono($sincrono)
355
    {
356 102
        if (is_bool($sincrono)) {
357 1
            $sincrono = $sincrono ? 'Y': 'N';
358
        }
359 102
        $this->sincrono = $sincrono;
360 102
        return $this;
361
    }
362
363
    /**
364
     * Informa se está operando offline
365
     * @return mixed offline da Configuracao
366
     */
367 3
    public function getOffline($normalize = false)
368
    {
369 3
        if (!$normalize || is_null($this->offline)) {
370 3
            return $this->offline;
371
        }
372 1
        return Util::toDateTime($this->getOffline());
373
    }
374
375
    /**
376
     * Informa se está operando offline
377
     */
378 23
    public function isOffline()
379
    {
380 23
        return $this->offline + 180 > time();
381
    }
382
383
    /**
384
     * Entra no modo offline e sai automaticamente após 3 minutos
385
     */
386 4
    public function setOffline($offline)
387
    {
388 4
        if (!is_null($offline) && !is_numeric($offline)) {
389 1
            $offline = strtotime($offline);
390
        }
391 4
        $this->offline = $offline;
0 ignored issues
show
Documentation Bug introduced by
It seems like $offline can also be of type double or string. However, the property $offline is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
392 4
        return $this;
393
    }
394
395 2
    public function toArray($recursive = false)
396
    {
397 2
        $configuracao = [];
398 2
        $configuracao['banco'] = $this->getBanco();
399 2
        $configuracao['emitente'] = $this->getEmitente();
400 2
        $configuracao['evento'] = $this->getEvento();
401 2
        $configuracao['certificado'] = $this->getCertificado();
402 2
        $configuracao['token'] = $this->getToken();
403 2
        $configuracao['csc'] = $this->getCSC();
404 2
        $configuracao['token_ibpt'] = $this->getTokenIBPT();
405 2
        $configuracao['tempo_limite'] = $this->getTempoLimite();
406 2
        $configuracao['sincrono'] = $this->getSincrono();
407 2
        $configuracao['offline'] = $this->getOffline($recursive);
408 2
        return $configuracao;
409
    }
410
411 102
    public function fromArray($configuracao = [])
0 ignored issues
show
Complexity introduced by
This operation has 24000 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
412
    {
413 102
        if ($configuracao instanceof Configuracao) {
414 1
            $configuracao = $configuracao->toArray();
415 102
        } elseif (!is_array($configuracao)) {
416 1
            return $this;
417
        }
418 102
        $this->setBanco(new Estatico(isset($configuracao['banco']) ? $configuracao['banco'] : []));
419 102
        $this->setEmitente(new Emitente(isset($configuracao['emitente']) ? $configuracao['emitente'] : []));
420 102
        $this->setCertificado(new Certificado(isset($configuracao['certificado']) ? $configuracao['certificado'] : []));
421 102
        if (isset($configuracao['evento'])) {
422 2
            $this->setEvento($configuracao['evento']);
423
        } else {
424 102
            $this->setEvento(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<NFe\Common\Evento>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
425
        }
426 102
        if (isset($configuracao['token'])) {
427 1
            $this->setToken($configuracao['token']);
428
        } else {
429 102
            $this->setToken(null);
430
        }
431 102
        if (isset($configuracao['csc'])) {
432 1
            $this->setCSC($configuracao['csc']);
433
        } else {
434 102
            $this->setCSC(null);
435
        }
436 102
        if (isset($configuracao['token_ibpt'])) {
437 1
            $this->setTokenIBPT($configuracao['token_ibpt']);
438
        } else {
439 102
            $this->setTokenIBPT(null);
440
        }
441 102
        if (!isset($configuracao['tempo_limite'])) {
442 102
            $this->setTempoLimite(4);
443
        } else {
444 2
            $this->setTempoLimite($configuracao['tempo_limite']);
445
        }
446 102
        if (!isset($configuracao['sincrono'])) {
447 102
            $this->setSincrono('Y');
448
        } else {
449 2
            $this->setSincrono($configuracao['sincrono']);
450
        }
451 102
        return $this;
452
    }
453
454
    /**
455
     * Certifica que o certificado está informado e é válido
456
     * @throws \Exception quando o certificado estiver expirado ou não informado
457
     */
458 34
    public function verificaValidadeCertificado()
459
    {
460 34
        if (getenv('APP_ENV') != 'testing') {
461
            $this->getCertificado()->requerValido();
462
        }
463 34
    }
464
}
465