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

Produto::setPeso()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 extends Total
0 ignored issues
show
Complexity introduced by
This class has 45 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 16 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 131 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 $quantidade;
59
    private $tributada;
60
    private $peso;
61
    private $excecao;
62
    private $cfop;
63
    private $ncm;
64
    private $cest;
65
    private $impostos;
66
67 36
    public function __construct($produto = [])
68
    {
69 36
        $this->fromArray($produto);
70 36
    }
71
72
    /**
73
     * Número do Item do Pedido de Compra - Identificação do número do item do
74
     * pedido de Compra
75
     */
76 35
    public function getItem($normalize = false)
77
    {
78 35
        if (!$normalize) {
79 34
            return $this->item;
80
        }
81 34
        return $this->item;
82
    }
83
84 36
    public function setItem($item)
85
    {
86 36
        if (trim($item) != '') {
87 35
            $item = intval($item);
88
        }
89 36
        $this->item = $item;
90 36
        return $this;
91
    }
92
93
    /**
94
     * informar o número do pedido de compra, o campo é de livre uso do emissor
95
     */
96 34
    public function getPedido($normalize = false)
97
    {
98 34
        if (!$normalize) {
99 34
            return $this->pedido;
100
        }
101 2
        return $this->pedido;
102
    }
103
104 36
    public function setPedido($pedido)
105
    {
106 36
        $this->pedido = $pedido;
107 36
        return $this;
108
    }
109
110
    /**
111
     * Código do produto ou serviço. Preencher com CFOP caso se trate de itens
112
     * não relacionados com mercadorias/produto e que o contribuinte não possua
113
     * codificação própria
114
     * Formato ”CFOP9999”.
115
     */
116 34
    public function getCodigo($normalize = false)
117
    {
118 34
        if (!$normalize) {
119 8
            return $this->codigo;
120
        }
121 34
        return $this->codigo;
122
    }
123
124 36
    public function setCodigo($codigo)
125
    {
126 36
        $this->codigo = $codigo;
127 36
        return $this;
128
    }
129
130
    /**
131
     * Código do produto ou serviço. Preencher com CFOP caso se trate de itens
132
     * não relacionados com mercadorias/produto e que o contribuinte não possua
133
     * codificação própria
134
     * Formato ”CFOP9999”.
135
     */
136 34
    public function getCodigoTributario($normalize = false)
137
    {
138 34
        if (!$normalize) {
139 8
            return $this->codigo_tributario;
140
        }
141 34
        return $this->codigo_tributario;
142
    }
143
144 36
    public function setCodigoTributario($codigo_tributario)
145
    {
146 36
        $this->codigo_tributario = $codigo_tributario;
147 36
        return $this;
148
    }
149
150
    /**
151
     * GTIN (Global Trade Item Number) do produto, antigo código EAN ou código
152
     * de barras
153
     */
154 34
    public function getCodigoBarras($normalize = false)
155
    {
156 34
        if (!$normalize) {
157 8
            return $this->codigo_barras;
158
        }
159 34
        return $this->codigo_barras;
160
    }
161
162 36
    public function setCodigoBarras($codigo_barras)
163
    {
164 36
        $this->codigo_barras = $codigo_barras;
165 36
        return $this;
166
    }
167
168
    /**
169
     * Descrição do produto ou serviço
170
     */
171 35
    public function getDescricao($normalize = false)
172
    {
173 35
        if (!$normalize) {
174 9
            return $this->descricao;
175
        }
176 34
        return $this->descricao;
177
    }
178
179 36
    public function setDescricao($descricao)
180
    {
181 36
        $this->descricao = $descricao;
182 36
        return $this;
183
    }
184
185
    /**
186
     * Unidade do produto, Não informar a grandeza
187
     */
188 34
    public function getUnidade($normalize = false)
189
    {
190 34
        if (!$normalize) {
191 8
            return $this->unidade;
192
        }
193 34
        switch ($this->unidade) {
194 34
            case self::UNIDADE_UNIDADE:
195 34
                return 'UN';
196
            case self::UNIDADE_PECA:
197
                return 'PC';
198
            case self::UNIDADE_METRO:
199
                return 'm';
200
            case self::UNIDADE_GRAMA:
201
                return 'g';
202
            case self::UNIDADE_LITRO:
203
                return 'L';
204
        }
205
        return $this->unidade;
206
    }
207
208 36
    public function setUnidade($unidade)
209
    {
210 36
        switch ($unidade) {
211 36
            case 'UN':
212 29
                $unidade = self::UNIDADE_UNIDADE;
213 29
                break;
214 36
            case 'PC':
215
                $unidade = self::UNIDADE_PECA;
216
                break;
217 36
            case 'm':
218
                $unidade = self::UNIDADE_METRO;
219
                break;
220 36
            case 'g':
221
                $unidade = self::UNIDADE_GRAMA;
222
                break;
223 36
            case 'L':
224
                $unidade = self::UNIDADE_LITRO;
225
                break;
226
        }
227 36
        $this->unidade = $unidade;
228 36
        return $this;
229
    }
230
231 34
    public function getMultiplicador($normalize = false)
232
    {
233 34
        if (!$normalize) {
234 33
            return $this->multiplicador;
235
        }
236 34
        return $this->multiplicador;
237
    }
238
239 36
    public function setMultiplicador($multiplicador)
240
    {
241 36
        if (trim($multiplicador) != '') {
242 36
            $multiplicador = intval($multiplicador);
243
        }
244 36
        $this->multiplicador = $multiplicador;
245 36
        return $this;
246
    }
247
248
    /**
249
     * Valor unitário de comercialização  - alterado para aceitar 0 a 10 casas
250
     * decimais e 11 inteiros
251
     */
252 35
    public function getPreco($normalize = false)
253
    {
254 35
        return parent::getProdutos($normalize);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getProdutos() instead of getPreco()). Are you sure this is correct? If so, you might want to change this to $this->getProdutos().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
255
    }
256
257
    /**
258
     * Altera o preço total do produto para o informado no parâmetro
259
     * @param mixed $preco novo preço para o Produto
260
     * @return Produto A própria instância da classe
261
     */
262 36
    public function setPreco($preco)
263
    {
264 36
        return parent::setProdutos($preco);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (setProdutos() instead of setPreco()). Are you sure this is correct? If so, you might want to change this to $this->setProdutos().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
265
    }
266
267
    /**
268
     * Quantidade Comercial  do produto, alterado para aceitar de 0 a 4 casas
269
     * decimais e 11 inteiros.
270
     */
271 34
    public function getQuantidade($normalize = false)
272
    {
273 34
        if (!$normalize) {
274 34
            return $this->quantidade;
275
        }
276 34
        return Util::toFloat($this->quantidade);
277
    }
278
279 36
    public function setQuantidade($quantidade)
280
    {
281 36
        if (trim($quantidade) != '') {
282 35
            $quantidade = floatval($quantidade);
283
        }
284 36
        $this->quantidade = $quantidade;
285 36
        return $this;
286
    }
287
288
    /**
289
     * Informa a quantidade tributada
290
     */
291 34
    public function getTributada($normalize = false)
292
    {
293 34
        if (!$normalize) {
294 34
            return is_null($this->tributada)?$this->getQuantidade():$this->tributada;
295
        }
296 34
        return Util::toFloat($this->getTributada());
297
    }
298
299 36
    public function setTributada($tributada)
300
    {
301 36
        if (trim($tributada) != '') {
302 35
            $tributada = floatval($tributada);
303
        }
304 36
        $this->tributada = $tributada;
305 36
        return $this;
306
    }
307
308 8
    public function getPeso()
309
    {
310 8
        return $this->peso;
311
    }
312
313 36
    public function setPeso($peso)
314
    {
315 36
        $this->peso = $peso;
316 36
        return $this;
317
    }
318
319
    /**
320
     * Código EX TIPI
321
     */
322 35
    public function getExcecao($normalize = false)
323
    {
324 35
        if (!$normalize) {
325 35
            return $this->excecao;
326
        }
327
        return Util::padDigit($this->excecao, 2);
328
    }
329
330 36
    public function setExcecao($excecao)
331
    {
332 36
        $this->excecao = $excecao;
333 36
        return $this;
334
    }
335
336 34
    public function getCFOP($normalize = false)
337
    {
338 34
        if (!$normalize) {
339 8
            return $this->cfop;
340
        }
341 34
        return $this->cfop;
342
    }
343
344 36
    public function setCFOP($cfop)
345
    {
346 36
        if (trim($cfop) != '') {
347 35
            $cfop = intval($cfop);
348
        }
349 36
        $this->cfop = $cfop;
350 36
        return $this;
351
    }
352
353
    /**
354
     * Código NCM (8 posições), será permitida a informação do gênero (posição
355
     * do capítulo do NCM) quando a operação não for de comércio exterior
356
     * (importação/exportação) ou o produto não seja tributado pelo IPI. Em
357
     * caso de item de serviço ou item que não tenham produto (Ex.
358
     * transferência de crédito, crédito do ativo imobilizado, etc.), informar
359
     * o código 00 (zeros) (v2.0)
360
     */
361 35
    public function getNCM($normalize = false)
362
    {
363 35
        if (!$normalize) {
364 35
            return $this->ncm;
365
        }
366 34
        return $this->ncm;
367
    }
368
369 36
    public function setNCM($ncm)
370
    {
371 36
        $this->ncm = $ncm;
372 36
        return $this;
373
    }
374
375 34
    public function getCEST($normalize = false)
376
    {
377 34
        if (!$normalize) {
378 34
            return $this->cest;
379
        }
380 34
        return $this->cest;
381
    }
382
383 36
    public function setCEST($cest)
384
    {
385 36
        $this->cest = $cest;
386 36
        return $this;
387
    }
388
389 34
    public function getImpostos()
390
    {
391 34
        return $this->impostos;
392
    }
393
394 36
    public function setImpostos($impostos)
395
    {
396 36
        $this->impostos = $impostos;
397 36
        return $this;
398
    }
399
400 7
    public function addImposto($imposto)
401
    {
402 7
        $this->impostos[] = $imposto;
403 7
        return $this;
404
    }
405
406
    /**
407
     * Valor unitário
408
     */
409 34
    public function getPrecoUnitario($normalize = false)
410
    {
411 34
        if (!$normalize) {
412 34
            return $this->getPreco() / $this->getQuantidade();
413
        }
414 34
        return Util::toCurrency($this->getPrecoUnitario(), 10);
415
    }
416
417
    /**
418
     * Valor tributável
419
     */
420 34
    public function getPrecoTributavel($normalize = false)
421
    {
422 34
        if (!$normalize) {
423 34
            return $this->getPreco() / $this->getTributada();
424
        }
425 34
        return Util::toCurrency($this->getPrecoTributavel(), 10);
426
    }
427
428 35
    public function getBase($normalize = false)
429
    {
430 35
        if (!$normalize) {
431 35
            return $this->getPreco() - $this->getDesconto();
432
        }
433
        return Util::toCurrency($this->getBase());
434
    }
435
436 35
    public function getImpostoInfo()
437
    {
438 35
        $config = SEFAZ::getInstance()->getConfiguracao();
439 35
        $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...
440 35
        $endereco = $config->getEmitente()->getEndereco();
441 35
        $info = ['total' => 0.00];
442
        $tipos = [
443
            // Imposto::TIPO_IMPORTADO, // TODO: determinar quando usar
444 35
            Imposto::TIPO_NACIONAL,
445
            Imposto::TIPO_ESTADUAL,
446
            Imposto::TIPO_MUNICIPAL
447
        ];
448 35
        $imposto = new \NFe\Entity\Imposto\Total();
449 35
        $imposto->setBase($this->getBase());
450 35
        $aliquota = $db->getImpostoAliquota(
451 35
            $this->getNCM(),
452 35
            $endereco->getMunicipio()->getEstado()->getUF(),
453 35
            $this->getExcecao(),
454 35
            $config->getEmitente()->getCNPJ(),
455 35
            $config->getTokenIBPT()
456
        );
457 35
        if ($aliquota === false) {
458 1
            throw new \Exception(
459 1
                sprintf(
460 1
                    'NCM inválido no item %d - "%s"',
461 1
                    $this->getItem(),
462 1
                    $this->getDescricao()
463
                ),
464 1
                404
465
            );
466
        }
467 34
        foreach ($tipos as $tipo) {
468 34
            $imposto->setAliquota($aliquota[$tipo]);
469 34
            $tributo = round($imposto->getTotal(), 2);
470 34
            $info[$tipo] = $tributo;
471 34
            $info['total'] += $tributo;
472
        }
473 34
        $info['info'] = $aliquota['info'];
474 34
        return $info;
475
    }
476
477 8
    public function toArray($recursive = false)
478
    {
479 8
        $produto = parent::toArray($recursive);
480 8
        unset($produto['produtos']);
481 8
        $produto['item'] = $this->getItem();
482 8
        $produto['pedido'] = $this->getPedido();
483 8
        $produto['codigo'] = $this->getCodigo();
484 8
        $produto['codigo_tributario'] = $this->getCodigoTributario();
485 8
        $produto['codigo_barras'] = $this->getCodigoBarras();
486 8
        $produto['descricao'] = $this->getDescricao();
487 8
        $produto['unidade'] = $this->getUnidade();
488 8
        $produto['multiplicador'] = $this->getMultiplicador();
489 8
        $produto['preco'] = $this->getPreco();
490 8
        $produto['quantidade'] = $this->getQuantidade();
491 8
        $produto['tributada'] = $this->getTributada();
492 8
        if (!is_null($this->getPeso()) && $recursive) {
493 1
            $produto['peso'] = $this->getPeso()->toArray($recursive);
494
        } else {
495 7
            $produto['peso'] = $this->getPeso();
496
        }
497 8
        $produto['excecao'] = $this->getExcecao();
498 8
        $produto['cfop'] = $this->getCFOP();
499 8
        $produto['ncm'] = $this->getNCM();
500 8
        $produto['cest'] = $this->getCEST();
501 8
        if ($recursive) {
502 1
            $impostos = [];
503 1
            $_impostos = $this->getImpostos();
504 1
            foreach ($_impostos as $_imposto) {
505 1
                $impostos[] = $_imposto->toArray($recursive);
506
            }
507 1
            $produto['impostos'] = $impostos;
508
        } else {
509 7
            $produto['impostos'] = $this->getImpostos();
510
        }
511 8
        return $produto;
512
    }
513
514 36
    public function fromArray($produto = [])
0 ignored issues
show
Complexity introduced by
This operation has 983040 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...
515
    {
516 36
        if ($produto instanceof Produto) {
517 7
            $produto = $produto->toArray();
518 36
        } elseif (!is_array($produto)) {
519 7
            return $this;
520
        }
521 36
        parent::fromArray($produto);
522 36
        if (isset($produto['item'])) {
523 1
            $this->setItem($produto['item']);
524
        } else {
525 36
            $this->setItem(null);
526
        }
527 36
        if (isset($produto['pedido'])) {
528 1
            $this->setPedido($produto['pedido']);
529
        } else {
530 36
            $this->setPedido(null);
531
        }
532 36
        if (isset($produto['codigo'])) {
533 7
            $this->setCodigo($produto['codigo']);
534
        } else {
535 36
            $this->setCodigo(null);
536
        }
537 36
        if (isset($produto['codigo_tributario'])) {
538 1
            $this->setCodigoTributario($produto['codigo_tributario']);
539
        } else {
540 36
            $this->setCodigoTributario(null);
541
        }
542 36
        if (isset($produto['codigo_barras'])) {
543 7
            $this->setCodigoBarras($produto['codigo_barras']);
544
        } else {
545 36
            $this->setCodigoBarras(null);
546
        }
547 36
        if (isset($produto['descricao'])) {
548 7
            $this->setDescricao($produto['descricao']);
549
        } else {
550 36
            $this->setDescricao(null);
551
        }
552 36
        if (!isset($produto['unidade'])) {
553 36
            $this->setUnidade(self::UNIDADE_UNIDADE);
554
        } else {
555 7
            $this->setUnidade($produto['unidade']);
556
        }
557 36
        if (!isset($produto['multiplicador'])) {
558 36
            $this->setMultiplicador(1);
559
        } else {
560 7
            $this->setMultiplicador($produto['multiplicador']);
561
        }
562 36
        if (isset($produto['preco'])) {
563 7
            $this->setPreco($produto['preco']);
564
        } else {
565 36
            $this->setPreco(null);
566
        }
567 36
        if (isset($produto['quantidade'])) {
568 7
            $this->setQuantidade($produto['quantidade']);
569
        } else {
570 36
            $this->setQuantidade(null);
571
        }
572 36
        if (isset($produto['tributada'])) {
573 7
            $this->setTributada($produto['tributada']);
574
        } else {
575 36
            $this->setTributada(null);
576
        }
577 36
        $this->setPeso(new Peso(isset($produto['peso']) ? $produto['peso'] : []));
578 36
        if (isset($produto['excecao'])) {
579
            $this->setExcecao($produto['excecao']);
580
        } else {
581 36
            $this->setExcecao(null);
582
        }
583 36
        if (isset($produto['cfop'])) {
584 7
            $this->setCFOP($produto['cfop']);
585
        } else {
586 36
            $this->setCFOP(null);
587
        }
588 36
        if (isset($produto['ncm'])) {
589 7
            $this->setNCM($produto['ncm']);
590
        } else {
591 36
            $this->setNCM(null);
592
        }
593 36
        if (isset($produto['cest'])) {
594 7
            $this->setCEST($produto['cest']);
595
        } else {
596 36
            $this->setCEST(null);
597
        }
598 36
        if (!isset($produto['impostos'])) {
599 36
            $this->setImpostos([]);
600
        } else {
601 7
            $this->setImpostos($produto['impostos']);
602
        }
603 36
        return $this;
604
    }
605
606 34
    public static function addNodeInformacoes($tributos, $element, $name = null)
607
    {
608 34
        $detalhes = [];
609
        $formatos = [
610 34
            Imposto::TIPO_IMPORTADO => '%s Importado',
611
            Imposto::TIPO_NACIONAL => '%s Federal',
612
            Imposto::TIPO_ESTADUAL => '%s Estadual',
613
            Imposto::TIPO_MUNICIPAL => '%s Municipal'
614
        ];
615 34
        foreach ($formatos as $tipo => $formato) {
616 34
            if (!isset($tributos[$tipo])) {
617 34
                continue;
618
            }
619 34
            if (!Util::isGreater($tributos[$tipo], 0.00)) {
620 34
                continue;
621
            }
622 34
            $detalhes[] = sprintf($formato, Util::toMoney($tributos[$tipo]));
623
        }
624 34
        if (count($detalhes) == 0) {
625
            return null;
626
        }
627 34
        $fonte = 'Fonte: '.$tributos['info']['fonte'].' '.$tributos['info']['chave'];
628 34
        $ultimo = '';
629 34
        if (count($detalhes) > 1) {
630 34
            $ultimo = ' e '.array_pop($detalhes);
631
        }
632 34
        $texto = 'Trib. aprox.: '.implode(', ', $detalhes).$ultimo.'. '.$fonte;
633 34
        Util::appendNode($element, is_null($name)?'infAdProd':$name, $texto);
634 34
        return $texto;
635
    }
636
637 34
    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...
638
    {
639 34
        $dom = new \DOMDocument('1.0', 'UTF-8');
640 34
        $element = $dom->createElement(is_null($name)?'det':$name);
641 34
        $attr = $dom->createAttribute('nItem');
642 34
        $attr->value = $this->getItem(true);
643 34
        $element->appendChild($attr);
644
645 34
        $produto = $dom->createElement('prod');
646 34
        Util::appendNode($produto, 'cProd', $this->getCodigo(true));
647 34
        Util::appendNode($produto, 'cEAN', $this->getCodigoBarras(true));
648 34
        Util::appendNode($produto, 'xProd', $this->getDescricao(true));
649 34
        Util::appendNode($produto, 'NCM', $this->getNCM(true));
650
//      Util::appendNode($produto, 'NVE', $this->getNVE(true));
651 34
        if (!is_null($this->getCEST())) {
652 34
            Util::appendNode($produto, 'CEST', $this->getCEST(true));
653
        }
654 34
        if (!is_null($this->getExcecao())) {
655
            Util::appendNode($produto, 'EXTIPI', $this->getExcecao(true));
656
        }
657 34
        Util::appendNode($produto, 'CFOP', $this->getCFOP(true));
658 34
        Util::appendNode($produto, 'uCom', $this->getUnidade(true));
659 34
        Util::appendNode($produto, 'qCom', $this->getQuantidade(true));
660 34
        Util::appendNode($produto, 'vUnCom', $this->getPrecoUnitario(true));
661 34
        Util::appendNode($produto, 'vProd', $this->getPreco(true));
662 34
        Util::appendNode($produto, 'cEANTrib', $this->getCodigoTributario(true));
663 34
        Util::appendNode($produto, 'uTrib', $this->getUnidade(true));
664 34
        Util::appendNode($produto, 'qTrib', $this->getTributada(true));
665 34
        Util::appendNode($produto, 'vUnTrib', $this->getPrecoTributavel(true));
666 34
        if (Util::isGreater($this->getFrete(), 0.00)) {
667 2
            Util::appendNode($produto, 'vFrete', $this->getFrete(true));
668
        }
669 34
        if (Util::isGreater($this->getSeguro(), 0.00)) {
670 2
            Util::appendNode($produto, 'vSeg', $this->getSeguro(true));
671
        }
672 34
        if (Util::isGreater($this->getDesconto(), 0.00)) {
673 34
            Util::appendNode($produto, 'vDesc', $this->getDesconto(true));
674
        }
675 34
        if (Util::isGreater($this->getDespesas(), 0.00)) {
676 2
            Util::appendNode($produto, 'vOutro', $this->getDespesas(true));
677
        }
678 34
        Util::appendNode($produto, 'indTot', $this->getMultiplicador(true));
679
//      Util::appendNode($produto, 'DI', $this->getImportacoes(true));
680
//      Util::appendNode($produto, 'detExport', $this->getDetalhes(true));
681 34
        if (!is_null($this->getPedido())) {
682 2
            Util::appendNode($produto, 'xPed', $this->getPedido(true));
683
        }
684 34
        Util::appendNode($produto, 'nItemPed', $this->getItem(true));
685
//      Util::appendNode($produto, 'nFCI', $this->getControle(true));
686 34
        $element->appendChild($produto);
687
688 34
        $imposto = $dom->createElement('imposto');
689 34
        $grupos = [];
690 34
        $_impostos = $this->getImpostos();
691 34
        foreach ($_impostos as $_imposto) {
692 34
            if (is_null($_imposto->getBase())) {
693 6
                $_imposto->setBase($this->getBase());
694
            }
695 34
            $grupos[$_imposto->getGrupo(true)][] = $_imposto;
696
        }
697 34
        $imposto_info = $this->getImpostoInfo();
698 34
        $this->setTributos($imposto_info['total']);
699 34
        Util::appendNode($imposto, 'vTotTrib', Util::toCurrency($imposto_info['total']));
700 34
        foreach ($grupos as $tag => $_grupo) {
701 34
            $grupo = $dom->createElement($tag);
702 34
            foreach ($_grupo as $_imposto) {
703 34
                $node = $_imposto->getNode();
704 34
                $node = $dom->importNode($node, true);
705 34
                $grupo->appendChild($node);
706
            }
707 34
            $imposto->appendChild($grupo);
708
        }
709 34
        $element->appendChild($imposto);
710
        // TODO: verificar se é obrigatório a informação adicional abaixo
711 34
        $complemento = self::addNodeInformacoes($imposto_info, $element);
712 34
        $this->setComplemento($complemento);
713 34
        return $element;
714
    }
715
716 29
    public function loadNode($element, $name = null)
0 ignored issues
show
Complexity introduced by
This operation has 480 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...
717
    {
718 29
        $name = is_null($name)?'det':$name;
719 29
        if ($element->nodeName != $name) {
720
            $_fields = $element->getElementsByTagName($name);
721
            if ($_fields->length == 0) {
722
                throw new \Exception('Tag "'.$name.'" do Produto não encontrada', 404);
723
            }
724
            $element = $_fields->item(0);
725
        }
726 29
        $root = $element;
727 29
        $element = parent::loadNode($element, $name);
728 29
        $this->setItem(Util::loadNode($element, 'nItemPed'));
729 29
        $this->setPedido(Util::loadNode($element, 'xPed'));
730 29
        $this->setCodigo(
731 29
            Util::loadNode(
732 29
                $element,
733 29
                'cProd',
734 29
                'Tag "cProd" do campo "Codigo" não encontrada no Produto'
735
            )
736
        );
737 29
        $this->setCodigoTributario(
738 29
            Util::loadNode(
739 29
                $element,
740 29
                'cEANTrib',
741 29
                'Tag "cEANTrib" do campo "CodigoTributario" não encontrada no Produto'
742
            )
743
        );
744 29
        $this->setCodigoBarras(
745 29
            Util::loadNode(
746 29
                $element,
747 29
                'cEAN',
748 29
                'Tag "cEAN" do campo "CodigoBarras" não encontrada no Produto'
749
            )
750
        );
751 29
        $this->setDescricao(
752 29
            Util::loadNode(
753 29
                $element,
754 29
                'xProd',
755 29
                'Tag "xProd" do campo "Descricao" não encontrada no Produto'
756
            )
757
        );
758 29
        $this->setUnidade(
759 29
            Util::loadNode(
760 29
                $element,
761 29
                'uCom',
762 29
                'Tag "uCom" do campo "Unidade" não encontrada no Produto'
763
            )
764
        );
765 29
        $this->setMultiplicador(
766 29
            Util::loadNode(
767 29
                $element,
768 29
                'indTot',
769 29
                'Tag "indTot" do campo "Multiplicador" não encontrada no Produto'
770
            )
771
        );
772 29
        $this->setQuantidade(
773 29
            Util::loadNode(
774 29
                $element,
775 29
                'qCom',
776 29
                'Tag "qCom" do campo "Quantidade" não encontrada no Produto'
777
            )
778
        );
779 29
        $this->setTributada(
780 29
            Util::loadNode(
781 29
                $element,
782 29
                'qTrib',
783 29
                'Tag "qTrib" do campo "Tributada" não encontrada no Produto'
784
            )
785
        );
786 29
        $this->setExcecao(Util::loadNode($element, 'EXTIPI'));
787 29
        $this->setCFOP(
788 29
            Util::loadNode(
789 29
                $element,
790 29
                'CFOP',
791 29
                'Tag "CFOP" do campo "CFOP" não encontrada no Produto'
792
            )
793
        );
794 29
        $this->setNCM(
795 29
            Util::loadNode(
796 29
                $element,
797 29
                'NCM',
798 29
                'Tag "NCM" do campo "NCM" não encontrada no Produto'
799
            )
800
        );
801 29
        $this->setCEST(Util::loadNode($element, 'CEST'));
802 29
        $impostos = [];
803 29
        $_fields = $root->getElementsByTagName('imposto');
804 29
        if ($_fields->length == 0) {
805
            throw new \Exception('Tag "imposto" da lista de "Impostos" não encontrada no Produto', 404);
806
        }
807 29
        $imposto_node = $_fields->item(0);
808 29
        $this->setTributos(Util::loadNode($imposto_node, 'vTotTrib'));
809 29
        $_items = $imposto_node->childNodes;
810 29
        $total = new \NFe\Entity\Imposto\Total();
811 29
        foreach ($_items as $_item) {
812 29
            if (!$_item->hasChildNodes() || $_item->nodeType !== XML_ELEMENT_NODE) {
813 26
                continue;
814
            }
815 29
            $total->setGrupo($_item->nodeName);
816 29
            foreach ($_item->childNodes as $_subitem) {
817 29
                if ($_subitem->nodeType !== XML_ELEMENT_NODE) {
818 29
                    continue;
819
                }
820 29
                $imposto = Imposto::loadImposto($_subitem, $total->getGrupo());
0 ignored issues
show
Unused Code introduced by
The call to Imposto::loadImposto() has too many arguments starting with $total->getGrupo().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
821 29
                if ($imposto === false) {
822
                    continue;
823
                }
824 29
                $imposto->setGrupo($total->getGrupo());
825 29
                $impostos[] = $imposto;
826
            }
827
        }
828 29
        $this->setImpostos($impostos);
829 29
        $this->setComplemento(Util::loadNode($root, 'infAdProd'));
830 29
        return $element;
831
    }
832
}
833