Completed
Push — master ( f6da78...86bb06 )
by Francimar
03:45
created

Produto::getNode()   F

Complexity

Conditions 13
Paths 1152

Size

Total Lines 77
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 66
CRAP Score 13.0042

Importance

Changes 0
Metric Value
dl 0
loc 77
ccs 66
cts 68
cp 0.9706
rs 2.15
c 0
b 0
f 0
cc 13
eloc 57
nc 1152
nop 1
crap 13.0042

How to fix   Long Method    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\Entity;
29
30
use NFe\Core\SEFAZ;
31
use NFe\Common\Node;
32
use NFe\Common\Util;
33
34
/**
35
 * Produto ou serviço que está sendo vendido ou prestado e será adicionado
36
 * na nota fiscal
37
 */
38
class Produto implements Node
0 ignored issues
show
Complexity introduced by
This class has 54 public methods and attributes which exceeds the configured maximum of 45.

The number of this metric differs depending on the chosen design (inheritance vs. composition). For inheritance, the number should generally be a bit lower.

A high number indicates a reusable class. It might also make the class harder to change without breaking other classes though.

Loading history...
Complexity introduced by
This class has 21 fields which exceeds the configured maximum of 15.

Too many fields generally indicate a class which does too much and does not follow the single responsibility principle.

We suggest taking a look at the “Code” section for further suggestions on how to fix this.

Loading history...
Complexity introduced by
This class has a complexity of 156 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...
39
{
40
41
    /**
42
     * Unidade do produto, Não informar a grandeza
43
     */
44
    const UNIDADE_UNIDADE = 'unidade';
45
    const UNIDADE_PECA = 'peca';
46
    const UNIDADE_METRO = 'metro';
47
    const UNIDADE_GRAMA = 'grama';
48
    const UNIDADE_LITRO = 'litro';
49
50
    private $item;
51
    private $pedido;
52
    private $codigo;
53
    private $codigo_tributario;
54
    private $codigo_barras;
55
    private $descricao;
56
    private $unidade;
57
    private $multiplicador;
58
    private $preco;
59
    private $quantidade;
60
    private $tributada;
61
    private $peso;
62
    private $desconto;
63
    private $seguro;
64
    private $frete;
65
    private $despesas;
66
    private $excecao;
67
    private $cfop;
68
    private $ncm;
69
    private $cest;
70
    private $impostos;
71
72 8
    public function __construct($produto = array())
73
    {
74 8
        $this->fromArray($produto);
75 8
    }
76
77
    /**
78
     * Número do Item do Pedido de Compra - Identificação do número do item do
79
     * pedido de Compra
80
     */
81 7
    public function getItem($normalize = false)
82
    {
83 7
        if (!$normalize) {
84 6
            return $this->item;
85
        }
86 7
        return $this->item;
87
    }
88
89 8
    public function setItem($item)
90
    {
91 8
        if (trim($item) != '') {
92 7
            $item = intval($item);
93 7
        }
94 8
        $this->item = $item;
95 8
        return $this;
96
    }
97
98
    /**
99
     * informar o número do pedido de compra, o campo é de livre uso do emissor
100
     */
101 7
    public function getPedido($normalize = false)
102
    {
103 7
        if (!$normalize) {
104 7
            return $this->pedido;
105
        }
106 2
        return $this->pedido;
107
    }
108
109 8
    public function setPedido($pedido)
110
    {
111 8
        $this->pedido = $pedido;
112 8
        return $this;
113
    }
114
115
    /**
116
     * Código do produto ou serviço. Preencher com CFOP caso se trate de itens
117
     * não relacionados com mercadorias/produto e que o contribuinte não possua
118
     * codificação própria
119
     * Formato ”CFOP9999”.
120
     */
121 7
    public function getCodigo($normalize = false)
122
    {
123 7
        if (!$normalize) {
124 3
            return $this->codigo;
125
        }
126 7
        return $this->codigo;
127
    }
128
129 8
    public function setCodigo($codigo)
130
    {
131 8
        $this->codigo = $codigo;
132 8
        return $this;
133
    }
134
135
    /**
136
     * Código do produto ou serviço. Preencher com CFOP caso se trate de itens
137
     * não relacionados com mercadorias/produto e que o contribuinte não possua
138
     * codificação própria
139
     * Formato ”CFOP9999”.
140
     */
141 7
    public function getCodigoTributario($normalize = false)
142
    {
143 7
        if (!$normalize) {
144 3
            return $this->codigo_tributario;
145
        }
146 7
        return $this->codigo_tributario;
147
    }
148
149 8
    public function setCodigoTributario($codigo_tributario)
150
    {
151 8
        $this->codigo_tributario = $codigo_tributario;
152 8
        return $this;
153
    }
154
155
    /**
156
     * GTIN (Global Trade Item Number) do produto, antigo código EAN ou código
157
     * de barras
158
     */
159 7
    public function getCodigoBarras($normalize = false)
160
    {
161 7
        if (!$normalize) {
162 3
            return $this->codigo_barras;
163
        }
164 7
        return $this->codigo_barras;
165
    }
166
167 8
    public function setCodigoBarras($codigo_barras)
168
    {
169 8
        $this->codigo_barras = $codigo_barras;
170 8
        return $this;
171
    }
172
173
    /**
174
     * Descrição do produto ou serviço
175
     */
176 7
    public function getDescricao($normalize = false)
177
    {
178 7
        if (!$normalize) {
179 3
            return $this->descricao;
180
        }
181 7
        return $this->descricao;
182
    }
183
184 8
    public function setDescricao($descricao)
185
    {
186 8
        $this->descricao = $descricao;
187 8
        return $this;
188
    }
189
190
    /**
191
     * Unidade do produto, Não informar a grandeza
192
     */
193 7
    public function getUnidade($normalize = false)
194
    {
195 7
        if (!$normalize) {
196 3
            return $this->unidade;
197
        }
198 7
        switch ($this->unidade) {
199 7
            case self::UNIDADE_UNIDADE:
200 7
                return 'UN';
201
            case self::UNIDADE_PECA:
202
                return 'PC';
203
            case self::UNIDADE_METRO:
204
                return 'm';
205
            case self::UNIDADE_GRAMA:
206
                return 'g';
207
            case self::UNIDADE_LITRO:
208
                return 'L';
209
        }
210
        return $this->unidade;
211
    }
212
213 8
    public function setUnidade($unidade)
214
    {
215
        switch ($unidade) {
216 8
            case 'UN':
217 4
                $unidade = self::UNIDADE_UNIDADE;
218 4
                break;
219 8
            case 'PC':
220
                $unidade = self::UNIDADE_PECA;
221
                break;
222 8
            case 'm':
223
                $unidade = self::UNIDADE_METRO;
224
                break;
225 8
            case 'g':
226
                $unidade = self::UNIDADE_GRAMA;
227
                break;
228 8
            case 'L':
229
                $unidade = self::UNIDADE_LITRO;
230
                break;
231
        }
232 8
        $this->unidade = $unidade;
233 8
        return $this;
234
    }
235
236 7
    public function getMultiplicador($normalize = false)
237
    {
238 7
        if (!$normalize) {
239 6
            return $this->multiplicador;
240
        }
241 7
        return $this->multiplicador;
242
    }
243
244 8
    public function setMultiplicador($multiplicador)
245
    {
246 8
        if (trim($multiplicador) != '') {
247 8
            $multiplicador = intval($multiplicador);
248 8
        }
249 8
        $this->multiplicador = $multiplicador;
250 8
        return $this;
251
    }
252
253
    /**
254
     * Valor unitário de comercialização  - alterado para aceitar 0 a 10 casas
255
     * decimais e 11 inteiros
256
     */
257 7
    public function getPreco($normalize = false)
258
    {
259 7
        if (!$normalize) {
260 7
            return $this->preco;
261
        }
262 7
        return Util::toCurrency($this->preco);
263
    }
264
265 8
    public function setPreco($preco)
266
    {
267 8
        if (trim($preco) != '') {
268 7
            $preco = floatval($preco);
269 7
        }
270 8
        $this->preco = $preco;
271 8
        return $this;
272
    }
273
274
    /**
275
     * Quantidade Comercial  do produto, alterado para aceitar de 0 a 4 casas
276
     * decimais e 11 inteiros.
277
     */
278 7
    public function getQuantidade($normalize = false)
279
    {
280 7
        if (!$normalize) {
281 7
            return $this->quantidade;
282
        }
283 7
        return Util::toFloat($this->quantidade);
284
    }
285
286 8
    public function setQuantidade($quantidade)
287
    {
288 8
        if (trim($quantidade) != '') {
289 7
            $quantidade = floatval($quantidade);
290 7
        }
291 8
        $this->quantidade = $quantidade;
292 8
        return $this;
293
    }
294
295
    /**
296
     * Informa a quantidade tributada
297
     */
298 7
    public function getTributada($normalize = false)
299
    {
300 7
        if (!$normalize) {
301 7
            return is_null($this->tributada)?$this->getQuantidade():$this->tributada;
302
        }
303 7
        return Util::toFloat($this->getTributada());
304
    }
305
306 8
    public function setTributada($tributada)
307
    {
308 8
        if (trim($tributada) != '') {
309 7
            $tributada = floatval($tributada);
310 7
        }
311 8
        $this->tributada = $tributada;
312 8
        return $this;
313
    }
314
315 3
    public function getPeso()
316
    {
317 3
        return $this->peso;
318
    }
319
320 8
    public function setPeso($peso)
321
    {
322 8
        $this->peso = $peso;
323 8
        return $this;
324
    }
325
326
    /**
327
     * Valor do Desconto
328
     */
329 7
    public function getDesconto($normalize = false)
330
    {
331 7
        if (!$normalize) {
332 7
            return $this->desconto;
333
        }
334 7
        return Util::toCurrency($this->desconto);
335
    }
336
337 8
    public function setDesconto($desconto)
338
    {
339 8
        if (trim($desconto) != '') {
340 7
            $desconto = floatval($desconto);
341 7
        }
342 8
        $this->desconto = $desconto;
343 8
        return $this;
344
    }
345
346
    /**
347
     * informar o valor do Seguro, o Seguro deve ser rateado entre os itens de
348
     * produto
349
     */
350 7
    public function getSeguro($normalize = false)
351
    {
352 7
        if (!$normalize) {
353 7
            return $this->seguro;
354
        }
355 2
        return Util::toCurrency($this->seguro);
356
    }
357
358 8
    public function setSeguro($seguro)
359
    {
360 8
        if (trim($seguro) != '') {
361 2
            $seguro = floatval($seguro);
362 2
        }
363 8
        $this->seguro = $seguro;
364 8
        return $this;
365
    }
366
367
    /**
368
     * informar o valor do Frete, o Frete deve ser rateado entre os itens de
369
     * produto.
370
     */
371 7
    public function getFrete($normalize = false)
372
    {
373 7
        if (!$normalize) {
374 7
            return $this->frete;
375
        }
376 2
        return Util::toCurrency($this->frete);
377
    }
378
379 8
    public function setFrete($frete)
380
    {
381 8
        if (trim($frete) != '') {
382 2
            $frete = floatval($frete);
383 2
        }
384 8
        $this->frete = $frete;
385 8
        return $this;
386
    }
387
388
    /**
389
     * informar o valor de outras despesas acessórias do item de produto ou
390
     * serviço
391
     */
392 7
    public function getDespesas($normalize = false)
393
    {
394 7
        if (!$normalize) {
395 7
            return $this->despesas;
396
        }
397 2
        return Util::toCurrency($this->despesas);
398
    }
399
400 8
    public function setDespesas($despesas)
401
    {
402 8
        if (trim($despesas) != '') {
403 2
            $despesas = floatval($despesas);
404 2
        }
405 8
        $this->despesas = $despesas;
406 8
        return $this;
407
    }
408
409
    /**
410
     * Código EX TIPI
411
     */
412 7
    public function getExcecao($normalize = false)
413
    {
414 7
        if (!$normalize) {
415 7
            return $this->excecao;
416
        }
417
        return Util::padDigit($this->excecao, 2);
418
    }
419
420 8
    public function setExcecao($excecao)
421
    {
422 8
        $this->excecao = $excecao;
423 8
        return $this;
424
    }
425
426 7
    public function getCFOP($normalize = false)
427
    {
428 7
        if (!$normalize) {
429 3
            return $this->cfop;
430
        }
431 7
        return $this->cfop;
432
    }
433
434 8
    public function setCFOP($cfop)
435
    {
436 8
        if (trim($cfop) != '') {
437 7
            $cfop = intval($cfop);
438 7
        }
439 8
        $this->cfop = $cfop;
440 8
        return $this;
441
    }
442
443
    /**
444
     * Código NCM (8 posições), será permitida a informação do gênero (posição
445
     * do capítulo do NCM) quando a operação não for de comércio exterior
446
     * (importação/exportação) ou o produto não seja tributado pelo IPI. Em
447
     * caso de item de serviço ou item que não tenham produto (Ex.
448
     * transferência de crédito, crédito do ativo imobilizado, etc.), informar
449
     * o código 00 (zeros) (v2.0)
450
     */
451 7
    public function getNCM($normalize = false)
452
    {
453 7
        if (!$normalize) {
454 7
            return $this->ncm;
455
        }
456 7
        return $this->ncm;
457
    }
458
459 8
    public function setNCM($ncm)
460
    {
461 8
        $this->ncm = $ncm;
462 8
        return $this;
463
    }
464
465 7
    public function getCEST($normalize = false)
466
    {
467 7
        if (!$normalize) {
468 7
            return $this->cest;
469
        }
470 7
        return $this->cest;
471
    }
472
473 8
    public function setCEST($cest)
474
    {
475 8
        $this->cest = $cest;
476 8
        return $this;
477
    }
478
479 7
    public function getImpostos()
480
    {
481 7
        return $this->impostos;
482
    }
483
484 8
    public function setImpostos($impostos)
485
    {
486 8
        $this->impostos = $impostos;
487 8
        return $this;
488
    }
489
490 3
    public function addImposto($imposto)
491
    {
492 3
        $this->impostos[] = $imposto;
493 3
        return $this;
494
    }
495
496
    /**
497
     * Valor unitário
498
     */
499 7
    public function getPrecoUnitario($normalize = false)
500
    {
501 7
        if (!$normalize) {
502 7
            return $this->getPreco() / $this->getQuantidade();
503
        }
504 7
        return Util::toCurrency($this->getPrecoUnitario());
505
    }
506
507
    /**
508
     * Valor tributável
509
     */
510 7
    public function getPrecoTributavel($normalize = false)
511
    {
512 7
        if (!$normalize) {
513 7
            return $this->getPreco() / $this->getTributada();
514
        }
515 7
        return Util::toCurrency($this->getPrecoTributavel());
516
    }
517
518 7
    public function getBase($normalize = false)
519
    {
520 7
        if (!$normalize) {
521 7
            return $this->getPreco() - $this->getDesconto();
522
        }
523
        return Util::toCurrency($this->getBase());
524
    }
525
526 5
    public function getContabilizado($normalize = false)
527
    {
528 5
        if (!$normalize) {
529 5
            return $this->getBase() * $this->getMultiplicador();
530
        }
531
        return Util::toCurrency($this->getContabilizado());
532
    }
533
534 7
    public function getImpostoInfo()
535
    {
536 7
        $config = SEFAZ::getInstance()->getConfiguracao();
537 7
        $db = $config->getBanco();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $db. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
538 7
        $endereco = $config->getEmitente()->getEndereco();
539 7
        $info = array('total' => 0.00);
540
        $tipos = array(
541
            // Imposto::TIPO_IMPORTADO, // TODO: determinar quando usar
542 7
            Imposto::TIPO_NACIONAL,
543 7
            Imposto::TIPO_ESTADUAL,
544
            Imposto::TIPO_MUNICIPAL
545 7
        );
546 7
        $imposto = new \NFe\Entity\Imposto\Total();
547 7
        $imposto->setBase($this->getBase());
548 7
        $aliquota = $db->getImpostoAliquota(
549 7
            $this->getNCM(),
550 7
            $endereco->getMunicipio()->getEstado()->getUF(),
551 7
            $this->getExcecao(),
552 7
            $config->getEmitente()->getCNPJ(),
553 7
            $config->getTokenIBPT()
554 7
        );
555 7
        if ($aliquota === false) {
556
            throw new \Exception('Não foi possível obter o tributo aproximado do produto "'.
557
                $this->getDescricao().'" e item '.$this->getItem(), 404);
558
        }
559 7
        foreach ($tipos as $tipo) {
560 7
            $imposto->setAliquota($aliquota[$tipo]);
561 7
            $tributo = round($imposto->getTotal(), 2);
562 7
            $info[$tipo] = $tributo;
563 7
            $info['total'] += $tributo;
564 7
        }
565 7
        $info['info'] = $aliquota['info'];
566 7
        return $info;
567
    }
568
569 3
    public function toArray()
570
    {
571 3
        $produto = array();
572 3
        $produto['item'] = $this->getItem();
573 3
        $produto['pedido'] = $this->getPedido();
574 3
        $produto['codigo'] = $this->getCodigo();
575 3
        $produto['codigo_tributario'] = $this->getCodigoTributario();
576 3
        $produto['codigo_barras'] = $this->getCodigoBarras();
577 3
        $produto['descricao'] = $this->getDescricao();
578 3
        $produto['unidade'] = $this->getUnidade();
579 3
        $produto['multiplicador'] = $this->getMultiplicador();
580 3
        $produto['preco'] = $this->getPreco();
581 3
        $produto['quantidade'] = $this->getQuantidade();
582 3
        $produto['tributada'] = $this->getTributada();
583 3
        $produto['peso'] = $this->getPeso();
584 3
        $produto['desconto'] = $this->getDesconto();
585 3
        $produto['seguro'] = $this->getSeguro();
586 3
        $produto['frete'] = $this->getFrete();
587 3
        $produto['despesas'] = $this->getDespesas();
588 3
        $produto['excecao'] = $this->getExcecao();
589 3
        $produto['cfop'] = $this->getCFOP();
590 3
        $produto['ncm'] = $this->getNCM();
591 3
        $produto['cest'] = $this->getCEST();
592 3
        $produto['impostos'] = $this->getImpostos();
593 3
        return $produto;
594
    }
595
596 8
    public function fromArray($produto = array())
0 ignored issues
show
Complexity introduced by
This operation has 31850496 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...
597
    {
598 8
        if ($produto instanceof Produto) {
599 3
            $produto = $produto->toArray();
600 8
        } elseif (!is_array($produto)) {
601 3
            return $this;
602
        }
603 8
        if (isset($produto['item'])) {
604 1
            $this->setItem($produto['item']);
605 1
        } else {
606 8
            $this->setItem(null);
607
        }
608 8
        if (isset($produto['pedido'])) {
609 1
            $this->setPedido($produto['pedido']);
610 1
        } else {
611 8
            $this->setPedido(null);
612
        }
613 8
        if (isset($produto['codigo'])) {
614 3
            $this->setCodigo($produto['codigo']);
615 3
        } else {
616 8
            $this->setCodigo(null);
617
        }
618 8
        if (isset($produto['codigo_tributario'])) {
619 1
            $this->setCodigoTributario($produto['codigo_tributario']);
620 1
        } else {
621 8
            $this->setCodigoTributario(null);
622
        }
623 8
        if (isset($produto['codigo_barras'])) {
624 3
            $this->setCodigoBarras($produto['codigo_barras']);
625 3
        } else {
626 8
            $this->setCodigoBarras(null);
627
        }
628 8
        if (isset($produto['descricao'])) {
629 3
            $this->setDescricao($produto['descricao']);
630 3
        } else {
631 8
            $this->setDescricao(null);
632
        }
633 8
        if (!isset($produto['unidade']) || is_null($produto['unidade'])) {
634 8
            $this->setUnidade(self::UNIDADE_UNIDADE);
635 8
        } else {
636 3
            $this->setUnidade($produto['unidade']);
637
        }
638 8
        if (!isset($produto['multiplicador']) || is_null($produto['multiplicador'])) {
639 8
            $this->setMultiplicador(1);
640 8
        } else {
641 3
            $this->setMultiplicador($produto['multiplicador']);
642
        }
643 8
        if (isset($produto['preco'])) {
644 3
            $this->setPreco($produto['preco']);
645 3
        } else {
646 8
            $this->setPreco(null);
647
        }
648 8
        if (isset($produto['quantidade'])) {
649 3
            $this->setQuantidade($produto['quantidade']);
650 3
        } else {
651 8
            $this->setQuantidade(null);
652
        }
653 8
        if (isset($produto['tributada'])) {
654 3
            $this->setTributada($produto['tributada']);
655 3
        } else {
656 8
            $this->setTributada(null);
657
        }
658 8
        if (!isset($produto['peso']) || is_null($produto['peso'])) {
659 8
            $this->setPeso(new Peso());
660 8
        } else {
661 3
            $this->setPeso($produto['peso']);
662
        }
663 8
        if (isset($produto['desconto'])) {
664 3
            $this->setDesconto($produto['desconto']);
665 3
        } else {
666 8
            $this->setDesconto(null);
667
        }
668 8
        if (isset($produto['seguro'])) {
669 1
            $this->setSeguro($produto['seguro']);
670 1
        } else {
671 8
            $this->setSeguro(null);
672
        }
673 8
        if (isset($produto['frete'])) {
674 1
            $this->setFrete($produto['frete']);
675 1
        } else {
676 8
            $this->setFrete(null);
677
        }
678 8
        if (isset($produto['despesas'])) {
679 1
            $this->setDespesas($produto['despesas']);
680 1
        } else {
681 8
            $this->setDespesas(null);
682
        }
683 8
        if (isset($produto['excecao'])) {
684
            $this->setExcecao($produto['excecao']);
685
        } else {
686 8
            $this->setExcecao(null);
687
        }
688 8
        if (isset($produto['cfop'])) {
689 3
            $this->setCFOP($produto['cfop']);
690 3
        } else {
691 8
            $this->setCFOP(null);
692
        }
693 8
        if (isset($produto['ncm'])) {
694 3
            $this->setNCM($produto['ncm']);
695 3
        } else {
696 8
            $this->setNCM(null);
697
        }
698 8
        if (isset($produto['cest'])) {
699 3
            $this->setCEST($produto['cest']);
700 3
        } else {
701 8
            $this->setCEST(null);
702
        }
703 8
        if (!isset($produto['impostos']) || is_null($produto['impostos'])) {
704 8
            $this->setImpostos(array());
705 8
        } else {
706 3
            $this->setImpostos($produto['impostos']);
707
        }
708 8
        return $this;
709
    }
710
711 7
    public static function addNodeInformacoes($tributos, $element, $name = null)
712
    {
713 7
        $detalhes = array();
714
        $formatos = array(
715 7
            Imposto::TIPO_IMPORTADO => '%s Importado',
716 7
            Imposto::TIPO_NACIONAL => '%s Federal',
717 7
            Imposto::TIPO_ESTADUAL => '%s Estadual',
718 7
            Imposto::TIPO_MUNICIPAL => '%s Municipal'
719 7
        );
720 7
        foreach ($formatos as $tipo => $formato) {
721 7
            if (!isset($tributos[$tipo])) {
722 7
                continue;
723
            }
724 7
            if (!Util::isGreater($tributos[$tipo], 0.00)) {
725 7
                continue;
726
            }
727 7
            $detalhes[] = sprintf($formato, Util::toMoney($tributos[$tipo]));
728 7
        }
729 7
        if (count($detalhes) == 0) {
730
            return;
731
        }
732 7
        $dom = $element->ownerDocument;
733 7
        $fonte = 'Fonte: '.$tributos['info']['fonte'].' '.$tributos['info']['chave'];
734 7
        $ultimo = '';
735 7
        if (count($detalhes) > 1) {
736 7
            $ultimo = ' e '.array_pop($detalhes);
737 7
        }
738 7
        $texto = 'Trib. aprox.: '.implode(', ', $detalhes).$ultimo.'. '.$fonte;
739 7
        $info = $dom->createElement(is_null($name)?'infAdProd':$name, $texto);
740 7
        $element->appendChild($info);
741 7
    }
742
743 7
    public function getNode($name = null)
0 ignored issues
show
Complexity introduced by
This operation has 5760 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...
744
    {
745 7
        $dom = new \DOMDocument('1.0', 'UTF-8');
746 7
        $element = $dom->createElement(is_null($name)?'det':$name);
747 7
        $attr = $dom->createAttribute('nItem');
748 7
        $attr->value = $this->getItem(true);
749 7
        $element->appendChild($attr);
750
751 7
        $produto = $dom->createElement('prod');
752 7
        Util::appendNode($produto, 'cProd', $this->getCodigo(true));
753 7
        Util::appendNode($produto, 'cEAN', $this->getCodigoBarras(true));
754 7
        Util::appendNode($produto, 'xProd', $this->getDescricao(true));
755 7
        Util::appendNode($produto, 'NCM', $this->getNCM(true));
756
//		Util::appendNode($produto, 'NVE', $this->getNVE(true));
757 7
        if (!is_null($this->getCEST())) {
758 7
            Util::appendNode($produto, 'CEST', $this->getCEST(true));
759 7
        }
760 7
        if (!is_null($this->getExcecao())) {
761
            Util::appendNode($produto, 'EXTIPI', $this->getExcecao(true));
762
        }
763 7
        Util::appendNode($produto, 'CFOP', $this->getCFOP(true));
764 7
        Util::appendNode($produto, 'uCom', $this->getUnidade(true));
765 7
        Util::appendNode($produto, 'qCom', $this->getQuantidade(true));
766 7
        Util::appendNode($produto, 'vUnCom', $this->getPrecoUnitario(true));
767 7
        Util::appendNode($produto, 'vProd', $this->getPreco(true));
768 7
        Util::appendNode($produto, 'cEANTrib', $this->getCodigoTributario(true));
769 7
        Util::appendNode($produto, 'uTrib', $this->getUnidade(true));
770 7
        Util::appendNode($produto, 'qTrib', $this->getTributada(true));
771 7
        Util::appendNode($produto, 'vUnTrib', $this->getPrecoTributavel(true));
772 7
        if (!is_null($this->getFrete())) {
773 2
            Util::appendNode($produto, 'vFrete', $this->getFrete(true));
774 2
        }
775 7
        if (!is_null($this->getSeguro())) {
776 2
            Util::appendNode($produto, 'vSeg', $this->getSeguro(true));
777 2
        }
778 7
        if (!is_null($this->getDesconto())) {
779 7
            Util::appendNode($produto, 'vDesc', $this->getDesconto(true));
780 7
        }
781 7
        if (!is_null($this->getDespesas())) {
782 2
            Util::appendNode($produto, 'vOutro', $this->getDespesas(true));
783 2
        }
784 7
        Util::appendNode($produto, 'indTot', $this->getMultiplicador(true));
785
//		Util::appendNode($produto, 'DI', $this->getImportacoes(true));
786
//		Util::appendNode($produto, 'detExport', $this->getDetalhes(true));
787 7
        if (!is_null($this->getPedido())) {
788 2
            Util::appendNode($produto, 'xPed', $this->getPedido(true));
789 2
        }
790 7
        Util::appendNode($produto, 'nItemPed', $this->getItem(true));
791
//		Util::appendNode($produto, 'nFCI', $this->getControle(true));
792 7
        $element->appendChild($produto);
793
794 7
        $imposto = $dom->createElement('imposto');
795 7
        $grupos = array();
796 7
        $_impostos = $this->getImpostos();
797 7
        foreach ($_impostos as $_imposto) {
798 7
            if (is_null($_imposto->getBase())) {
799 2
                $_imposto->setBase($this->getBase());
800 2
            }
801 7
            $grupos[$_imposto->getGrupo(true)][] = $_imposto;
802 7
        }
803 7
        $imposto_info = $this->getImpostoInfo();
804 7
        $imp_total = $dom->createElement('vTotTrib', Util::toCurrency($imposto_info['total']));
805 7
        $imposto->appendChild($imp_total);
806 7
        foreach ($grupos as $tag => $_grupo) {
807 7
            $grupo = $dom->createElement($tag);
808 7
            foreach ($_grupo as $_imposto) {
809 7
                $node = $_imposto->getNode();
810 7
                $node = $dom->importNode($node, true);
811 7
                $grupo->appendChild($node);
812 7
            }
813 7
            $imposto->appendChild($grupo);
814 7
        }
815 7
        $element->appendChild($imposto);
816
        // TODO: verificar se é obrigatório a informação adicional abaixo
817 7
        self::addNodeInformacoes($imposto_info, $element);
818 7
        return $element;
819
    }
820
821 4
    public function loadNode($element, $name = null)
0 ignored issues
show
Complexity introduced by
This operation has 960 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...
822
    {
823 4
        $name = is_null($name)?'det':$name;
824 4
        if ($element->tagName != $name) {
825
            $_fields = $element->getElementsByTagName($name);
826
            if ($_fields->length == 0) {
827
                throw new \Exception('Tag "'.$name.'" do Produto não encontrada', 404);
828
            }
829
            $element = $_fields->item(0);
830
        }
831 4
        $root = $element;
832 4
        $_fields = $element->getElementsByTagName('prod');
833 4
        if ($_fields->length == 0) {
834
            throw new \Exception('Tag "prod" do Produto não encontrada', 404);
835
        }
836 4
        $element = $_fields->item(0);
837 4
        $this->setItem(Util::loadNode($element, 'nItemPed'));
838 4
        $this->setPedido(Util::loadNode($element, 'xPed'));
839 4
        $this->setCodigo(
840 4
            Util::loadNode(
841 4
                $element,
842 4
                'cProd',
843
                'Tag "cProd" do campo "Codigo" não encontrada no Produto'
844 4
            )
845 4
        );
846 4
        $this->setCodigoTributario(
847 4
            Util::loadNode(
848 4
                $element,
849 4
                'cEANTrib',
850
                'Tag "cEANTrib" do campo "CodigoTributario" não encontrada no Produto'
851 4
            )
852 4
        );
853 4
        $this->setCodigoBarras(
854 4
            Util::loadNode(
855 4
                $element,
856 4
                'cEAN',
857
                'Tag "cEAN" do campo "CodigoBarras" não encontrada no Produto'
858 4
            )
859 4
        );
860 4
        $this->setDescricao(
861 4
            Util::loadNode(
862 4
                $element,
863 4
                'xProd',
864
                'Tag "xProd" do campo "Descricao" não encontrada no Produto'
865 4
            )
866 4
        );
867 4
        $this->setUnidade(
868 4
            Util::loadNode(
869 4
                $element,
870 4
                'uCom',
871
                'Tag "uCom" do campo "Unidade" não encontrada no Produto'
872 4
            )
873 4
        );
874 4
        $this->setMultiplicador(
875 4
            Util::loadNode(
876 4
                $element,
877 4
                'indTot',
878
                'Tag "indTot" do campo "Multiplicador" não encontrada no Produto'
879 4
            )
880 4
        );
881 4
        $this->setPreco(
882 4
            Util::loadNode(
883 4
                $element,
884 4
                'vProd',
885
                'Tag "vProd" do campo "Preco" não encontrada no Produto'
886 4
            )
887 4
        );
888 4
        $this->setQuantidade(
889 4
            Util::loadNode(
890 4
                $element,
891 4
                'qCom',
892
                'Tag "qCom" do campo "Quantidade" não encontrada no Produto'
893 4
            )
894 4
        );
895 4
        $this->setTributada(
896 4
            Util::loadNode(
897 4
                $element,
898 4
                'qTrib',
899
                'Tag "qTrib" do campo "Tributada" não encontrada no Produto'
900 4
            )
901 4
        );
902 4
        $this->setDesconto(Util::loadNode($element, 'vDesc'));
903 4
        $this->setSeguro(Util::loadNode($element, 'vSeg'));
904 4
        $this->setFrete(Util::loadNode($element, 'vFrete'));
905 4
        $this->setDespesas(Util::loadNode($element, 'vOutro'));
906 4
        $this->setExcecao(Util::loadNode($element, 'EXTIPI'));
907 4
        $this->setCFOP(
908 4
            Util::loadNode(
909 4
                $element,
910 4
                'CFOP',
911
                'Tag "CFOP" do campo "CFOP" não encontrada no Produto'
912 4
            )
913 4
        );
914 4
        $this->setNCM(
915 4
            Util::loadNode(
916 4
                $element,
917 4
                'NCM',
918
                'Tag "NCM" do campo "NCM" não encontrada no Produto'
919 4
            )
920 4
        );
921 4
        $this->setCEST(Util::loadNode($element, 'CEST'));
922 4
        $impostos = array();
923 4
        $_fields = $root->getElementsByTagName('imposto');
924 4
        if ($_fields->length == 0) {
925
            throw new \Exception('Tag "imposto" da lista de "Impostos" não encontrada no Produto', 404);
926
        }
927 4
        $_items = $_fields->item(0)->childNodes;
928 4
        $total = new \NFe\Entity\Imposto\Total();
929 4
        foreach ($_items as $_item) {
930 4
            if (!$_item->hasChildNodes() || $_item->nodeType !== XML_ELEMENT_NODE) {
931 1
                continue;
932
            }
933 4
            $total->setGrupo($_item->tagName);
934 4
            foreach ($_item->childNodes as $_subitem) {
935 4
                if ($_subitem->nodeType !== XML_ELEMENT_NODE) {
936 4
                    continue;
937
                }
938 4
                $imposto = Imposto::loadImposto($_subitem, $total->getGrupo());
939 4
                if ($imposto === false) {
940
                    continue;
941
                }
942 4
                $imposto->setGrupo($total->getGrupo());
943 4
                $impostos[] = $imposto;
944 4
            }
945 4
        }
946 4
        $this->setImpostos($impostos);
947 4
        return $element;
948
    }
949
}
950