Passed
Push — master ( c1d1cf...f48ccd )
by Francimar
03:58
created

Produto::getPeso()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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 135 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 28
    public function __construct($produto = array())
68
    {
69 28
        $this->fromArray($produto);
70 28
    }
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 27
    public function getItem($normalize = false)
77
    {
78 27
        if (!$normalize) {
79 26
            return $this->item;
80
        }
81 27
        return $this->item;
82
    }
83
84 28
    public function setItem($item)
85
    {
86 28
        if (trim($item) != '') {
87 27
            $item = intval($item);
88 27
        }
89 28
        $this->item = $item;
90 28
        return $this;
91
    }
92
93
    /**
94
     * informar o número do pedido de compra, o campo é de livre uso do emissor
95
     */
96 27
    public function getPedido($normalize = false)
97
    {
98 27
        if (!$normalize) {
99 27
            return $this->pedido;
100
        }
101 2
        return $this->pedido;
102
    }
103
104 28
    public function setPedido($pedido)
105
    {
106 28
        $this->pedido = $pedido;
107 28
        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 27
    public function getCodigo($normalize = false)
117
    {
118 27
        if (!$normalize) {
119 4
            return $this->codigo;
120
        }
121 27
        return $this->codigo;
122
    }
123
124 28
    public function setCodigo($codigo)
125
    {
126 28
        $this->codigo = $codigo;
127 28
        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 27
    public function getCodigoTributario($normalize = false)
137
    {
138 27
        if (!$normalize) {
139 4
            return $this->codigo_tributario;
140
        }
141 27
        return $this->codigo_tributario;
142
    }
143
144 28
    public function setCodigoTributario($codigo_tributario)
145
    {
146 28
        $this->codigo_tributario = $codigo_tributario;
147 28
        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 27
    public function getCodigoBarras($normalize = false)
155
    {
156 27
        if (!$normalize) {
157 4
            return $this->codigo_barras;
158
        }
159 27
        return $this->codigo_barras;
160
    }
161
162 28
    public function setCodigoBarras($codigo_barras)
163
    {
164 28
        $this->codigo_barras = $codigo_barras;
165 28
        return $this;
166
    }
167
168
    /**
169
     * Descrição do produto ou serviço
170
     */
171 27
    public function getDescricao($normalize = false)
172
    {
173 27
        if (!$normalize) {
174 4
            return $this->descricao;
175
        }
176 27
        return $this->descricao;
177
    }
178
179 28
    public function setDescricao($descricao)
180
    {
181 28
        $this->descricao = $descricao;
182 28
        return $this;
183
    }
184
185
    /**
186
     * Unidade do produto, Não informar a grandeza
187
     */
188 27
    public function getUnidade($normalize = false)
189
    {
190 27
        if (!$normalize) {
191 4
            return $this->unidade;
192
        }
193 27
        switch ($this->unidade) {
194 27
            case self::UNIDADE_UNIDADE:
195 27
                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 28
    public function setUnidade($unidade)
209
    {
210
        switch ($unidade) {
211 28
            case 'UN':
212 24
                $unidade = self::UNIDADE_UNIDADE;
213 24
                break;
214 28
            case 'PC':
215
                $unidade = self::UNIDADE_PECA;
216
                break;
217 28
            case 'm':
218
                $unidade = self::UNIDADE_METRO;
219
                break;
220 28
            case 'g':
221
                $unidade = self::UNIDADE_GRAMA;
222
                break;
223 28
            case 'L':
224
                $unidade = self::UNIDADE_LITRO;
225
                break;
226
        }
227 28
        $this->unidade = $unidade;
228 28
        return $this;
229
    }
230
231 27
    public function getMultiplicador($normalize = false)
232
    {
233 27
        if (!$normalize) {
234 26
            return $this->multiplicador;
235
        }
236 27
        return $this->multiplicador;
237
    }
238
239 28
    public function setMultiplicador($multiplicador)
240
    {
241 28
        if (trim($multiplicador) != '') {
242 28
            $multiplicador = intval($multiplicador);
243 28
        }
244 28
        $this->multiplicador = $multiplicador;
245 28
        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 27
    public function getPreco($normalize = false)
253
    {
254 27
        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 28
    public function setPreco($preco)
263
    {
264 28
        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 27
    public function getQuantidade($normalize = false)
272
    {
273 27
        if (!$normalize) {
274 27
            return $this->quantidade;
275
        }
276 27
        return Util::toFloat($this->quantidade);
277
    }
278
279 28
    public function setQuantidade($quantidade)
280
    {
281 28
        if (trim($quantidade) != '') {
282 27
            $quantidade = floatval($quantidade);
283 27
        }
284 28
        $this->quantidade = $quantidade;
285 28
        return $this;
286
    }
287
288
    /**
289
     * Informa a quantidade tributada
290
     */
291 27
    public function getTributada($normalize = false)
292
    {
293 27
        if (!$normalize) {
294 27
            return is_null($this->tributada)?$this->getQuantidade():$this->tributada;
295
        }
296 27
        return Util::toFloat($this->getTributada());
297
    }
298
299 28
    public function setTributada($tributada)
300
    {
301 28
        if (trim($tributada) != '') {
302 27
            $tributada = floatval($tributada);
303 27
        }
304 28
        $this->tributada = $tributada;
305 28
        return $this;
306
    }
307
308 4
    public function getPeso()
309
    {
310 4
        return $this->peso;
311
    }
312
313 28
    public function setPeso($peso)
314
    {
315 28
        $this->peso = $peso;
316 28
        return $this;
317
    }
318
319
    /**
320
     * Código EX TIPI
321
     */
322 27
    public function getExcecao($normalize = false)
323
    {
324 27
        if (!$normalize) {
325 27
            return $this->excecao;
326
        }
327
        return Util::padDigit($this->excecao, 2);
328
    }
329
330 28
    public function setExcecao($excecao)
331
    {
332 28
        $this->excecao = $excecao;
333 28
        return $this;
334
    }
335
336 27
    public function getCFOP($normalize = false)
337
    {
338 27
        if (!$normalize) {
339 4
            return $this->cfop;
340
        }
341 27
        return $this->cfop;
342
    }
343
344 28
    public function setCFOP($cfop)
345
    {
346 28
        if (trim($cfop) != '') {
347 27
            $cfop = intval($cfop);
348 27
        }
349 28
        $this->cfop = $cfop;
350 28
        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 27
    public function getNCM($normalize = false)
362
    {
363 27
        if (!$normalize) {
364 27
            return $this->ncm;
365
        }
366 27
        return $this->ncm;
367
    }
368
369 28
    public function setNCM($ncm)
370
    {
371 28
        $this->ncm = $ncm;
372 28
        return $this;
373
    }
374
375 27
    public function getCEST($normalize = false)
376
    {
377 27
        if (!$normalize) {
378 27
            return $this->cest;
379
        }
380 27
        return $this->cest;
381
    }
382
383 28
    public function setCEST($cest)
384
    {
385 28
        $this->cest = $cest;
386 28
        return $this;
387
    }
388
389 27
    public function getImpostos()
390
    {
391 27
        return $this->impostos;
392
    }
393
394 28
    public function setImpostos($impostos)
395
    {
396 28
        $this->impostos = $impostos;
397 28
        return $this;
398
    }
399
400 3
    public function addImposto($imposto)
401
    {
402 3
        $this->impostos[] = $imposto;
403 3
        return $this;
404
    }
405
406
    /**
407
     * Valor unitário
408
     */
409 27
    public function getPrecoUnitario($normalize = false)
410
    {
411 27
        if (!$normalize) {
412 27
            return $this->getPreco() / $this->getQuantidade();
413
        }
414 27
        return Util::toCurrency($this->getPrecoUnitario(), 10);
415
    }
416
417
    /**
418
     * Valor tributável
419
     */
420 27
    public function getPrecoTributavel($normalize = false)
421
    {
422 27
        if (!$normalize) {
423 27
            return $this->getPreco() / $this->getTributada();
424
        }
425 27
        return Util::toCurrency($this->getPrecoTributavel(), 10);
426
    }
427
428 27
    public function getBase($normalize = false)
429
    {
430 27
        if (!$normalize) {
431 27
            return $this->getPreco() - $this->getDesconto();
432
        }
433
        return Util::toCurrency($this->getBase());
434
    }
435
436 27
    public function getImpostoInfo()
437
    {
438 27
        $config = SEFAZ::getInstance()->getConfiguracao();
439 27
        $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 27
        $endereco = $config->getEmitente()->getEndereco();
441 27
        $info = array('total' => 0.00);
442
        $tipos = array(
443
            // Imposto::TIPO_IMPORTADO, // TODO: determinar quando usar
444 27
            Imposto::TIPO_NACIONAL,
445 27
            Imposto::TIPO_ESTADUAL,
446
            Imposto::TIPO_MUNICIPAL
447 27
        );
448 27
        $imposto = new \NFe\Entity\Imposto\Total();
449 27
        $imposto->setBase($this->getBase());
450 27
        $aliquota = $db->getImpostoAliquota(
451 27
            $this->getNCM(),
452 27
            $endereco->getMunicipio()->getEstado()->getUF(),
453 27
            $this->getExcecao(),
454 27
            $config->getEmitente()->getCNPJ(),
455 27
            $config->getTokenIBPT()
456 27
        );
457 27
        if ($aliquota === false) {
458
            throw new \Exception('Não foi possível obter o tributo aproximado do produto "'.
459
                $this->getDescricao().'" e item '.$this->getItem(), 404);
460
        }
461 27
        foreach ($tipos as $tipo) {
462 27
            $imposto->setAliquota($aliquota[$tipo]);
463 27
            $tributo = round($imposto->getTotal(), 2);
464 27
            $info[$tipo] = $tributo;
465 27
            $info['total'] += $tributo;
466 27
        }
467 27
        $info['info'] = $aliquota['info'];
468 27
        return $info;
469
    }
470
471 4
    public function toArray($recursive = false)
472
    {
473 4
        $produto = parent::toArray($recursive);
474 4
        unset($produto['produtos']);
475 4
        $produto['item'] = $this->getItem();
476 4
        $produto['pedido'] = $this->getPedido();
477 4
        $produto['codigo'] = $this->getCodigo();
478 4
        $produto['codigo_tributario'] = $this->getCodigoTributario();
479 4
        $produto['codigo_barras'] = $this->getCodigoBarras();
480 4
        $produto['descricao'] = $this->getDescricao();
481 4
        $produto['unidade'] = $this->getUnidade();
482 4
        $produto['multiplicador'] = $this->getMultiplicador();
483 4
        $produto['preco'] = $this->getPreco();
484 4
        $produto['quantidade'] = $this->getQuantidade();
485 4
        $produto['tributada'] = $this->getTributada();
486 4
        if (!is_null($this->getPeso()) && $recursive) {
487 1
            $produto['peso'] = $this->getPeso()->toArray($recursive);
488 1
        } else {
489 3
            $produto['peso'] = $this->getPeso();
490
        }
491 4
        $produto['excecao'] = $this->getExcecao();
492 4
        $produto['cfop'] = $this->getCFOP();
493 4
        $produto['ncm'] = $this->getNCM();
494 4
        $produto['cest'] = $this->getCEST();
495 4
        if ($recursive) {
496 1
            $impostos = array();
497 1
            $_impostos = $this->getImpostos();
498 1
            foreach ($_impostos as $_imposto) {
499 1
                $impostos[] = $_imposto->toArray($recursive);
500 1
            }
501 1
            $produto['impostos'] = $impostos;
502 1
        } else {
503 3
            $produto['impostos'] = $this->getImpostos();
504
        }
505 4
        return $produto;
506
    }
507
508 28
    public function fromArray($produto = array())
0 ignored issues
show
Complexity introduced by
This operation has 1990656 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...
509
    {
510 28
        if ($produto instanceof Produto) {
511 3
            $produto = $produto->toArray();
512 28
        } elseif (!is_array($produto)) {
513 3
            return $this;
514
        }
515 28
        parent::fromArray($produto);
516 28
        if (isset($produto['item'])) {
517 1
            $this->setItem($produto['item']);
518 1
        } else {
519 28
            $this->setItem(null);
520
        }
521 28
        if (isset($produto['pedido'])) {
522 1
            $this->setPedido($produto['pedido']);
523 1
        } else {
524 28
            $this->setPedido(null);
525
        }
526 28
        if (isset($produto['codigo'])) {
527 3
            $this->setCodigo($produto['codigo']);
528 3
        } else {
529 28
            $this->setCodigo(null);
530
        }
531 28
        if (isset($produto['codigo_tributario'])) {
532 1
            $this->setCodigoTributario($produto['codigo_tributario']);
533 1
        } else {
534 28
            $this->setCodigoTributario(null);
535
        }
536 28
        if (isset($produto['codigo_barras'])) {
537 3
            $this->setCodigoBarras($produto['codigo_barras']);
538 3
        } else {
539 28
            $this->setCodigoBarras(null);
540
        }
541 28
        if (isset($produto['descricao'])) {
542 3
            $this->setDescricao($produto['descricao']);
543 3
        } else {
544 28
            $this->setDescricao(null);
545
        }
546 28
        if (!isset($produto['unidade']) || is_null($produto['unidade'])) {
547 28
            $this->setUnidade(self::UNIDADE_UNIDADE);
548 28
        } else {
549 3
            $this->setUnidade($produto['unidade']);
550
        }
551 28
        if (!isset($produto['multiplicador']) || is_null($produto['multiplicador'])) {
552 28
            $this->setMultiplicador(1);
553 28
        } else {
554 3
            $this->setMultiplicador($produto['multiplicador']);
555
        }
556 28
        if (isset($produto['preco'])) {
557 3
            $this->setPreco($produto['preco']);
558 3
        } else {
559 28
            $this->setPreco(null);
560
        }
561 28
        if (isset($produto['quantidade'])) {
562 3
            $this->setQuantidade($produto['quantidade']);
563 3
        } else {
564 28
            $this->setQuantidade(null);
565
        }
566 28
        if (isset($produto['tributada'])) {
567 3
            $this->setTributada($produto['tributada']);
568 3
        } else {
569 28
            $this->setTributada(null);
570
        }
571 28
        if (!isset($produto['peso']) || is_null($produto['peso'])) {
572 28
            $this->setPeso(new Peso());
573 28
        } else {
574 3
            $this->setPeso($produto['peso']);
575
        }
576 28
        if (isset($produto['excecao'])) {
577
            $this->setExcecao($produto['excecao']);
578
        } else {
579 28
            $this->setExcecao(null);
580
        }
581 28
        if (isset($produto['cfop'])) {
582 3
            $this->setCFOP($produto['cfop']);
583 3
        } else {
584 28
            $this->setCFOP(null);
585
        }
586 28
        if (isset($produto['ncm'])) {
587 3
            $this->setNCM($produto['ncm']);
588 3
        } else {
589 28
            $this->setNCM(null);
590
        }
591 28
        if (isset($produto['cest'])) {
592 3
            $this->setCEST($produto['cest']);
593 3
        } else {
594 28
            $this->setCEST(null);
595
        }
596 28
        if (!isset($produto['impostos']) || is_null($produto['impostos'])) {
597 28
            $this->setImpostos(array());
598 28
        } else {
599 3
            $this->setImpostos($produto['impostos']);
600
        }
601 28
        return $this;
602
    }
603
604 27
    public static function addNodeInformacoes($tributos, $element, $name = null)
605
    {
606 27
        $detalhes = array();
607
        $formatos = array(
608 27
            Imposto::TIPO_IMPORTADO => '%s Importado',
609 27
            Imposto::TIPO_NACIONAL => '%s Federal',
610 27
            Imposto::TIPO_ESTADUAL => '%s Estadual',
611 27
            Imposto::TIPO_MUNICIPAL => '%s Municipal'
612 27
        );
613 27
        foreach ($formatos as $tipo => $formato) {
614 27
            if (!isset($tributos[$tipo])) {
615 27
                continue;
616
            }
617 27
            if (!Util::isGreater($tributos[$tipo], 0.00)) {
618 27
                continue;
619
            }
620 27
            $detalhes[] = sprintf($formato, Util::toMoney($tributos[$tipo]));
621 27
        }
622 27
        if (count($detalhes) == 0) {
623
            return null;
624
        }
625 27
        $fonte = 'Fonte: '.$tributos['info']['fonte'].' '.$tributos['info']['chave'];
626 27
        $ultimo = '';
627 27
        if (count($detalhes) > 1) {
628 27
            $ultimo = ' e '.array_pop($detalhes);
629 27
        }
630 27
        $texto = 'Trib. aprox.: '.implode(', ', $detalhes).$ultimo.'. '.$fonte;
631 27
        Util::appendNode($element, is_null($name)?'infAdProd':$name, $texto);
632 27
        return $texto;
633
    }
634
635 27
    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...
636
    {
637 27
        $dom = new \DOMDocument('1.0', 'UTF-8');
638 27
        $element = $dom->createElement(is_null($name)?'det':$name);
639 27
        $attr = $dom->createAttribute('nItem');
640 27
        $attr->value = $this->getItem(true);
641 27
        $element->appendChild($attr);
642
643 27
        $produto = $dom->createElement('prod');
644 27
        Util::appendNode($produto, 'cProd', $this->getCodigo(true));
645 27
        Util::appendNode($produto, 'cEAN', $this->getCodigoBarras(true));
646 27
        Util::appendNode($produto, 'xProd', $this->getDescricao(true));
647 27
        Util::appendNode($produto, 'NCM', $this->getNCM(true));
648
//		Util::appendNode($produto, 'NVE', $this->getNVE(true));
649 27
        if (!is_null($this->getCEST())) {
650 27
            Util::appendNode($produto, 'CEST', $this->getCEST(true));
651 27
        }
652 27
        if (!is_null($this->getExcecao())) {
653
            Util::appendNode($produto, 'EXTIPI', $this->getExcecao(true));
654
        }
655 27
        Util::appendNode($produto, 'CFOP', $this->getCFOP(true));
656 27
        Util::appendNode($produto, 'uCom', $this->getUnidade(true));
657 27
        Util::appendNode($produto, 'qCom', $this->getQuantidade(true));
658 27
        Util::appendNode($produto, 'vUnCom', $this->getPrecoUnitario(true));
659 27
        Util::appendNode($produto, 'vProd', $this->getPreco(true));
660 27
        Util::appendNode($produto, 'cEANTrib', $this->getCodigoTributario(true));
661 27
        Util::appendNode($produto, 'uTrib', $this->getUnidade(true));
662 27
        Util::appendNode($produto, 'qTrib', $this->getTributada(true));
663 27
        Util::appendNode($produto, 'vUnTrib', $this->getPrecoTributavel(true));
664 27
        if (Util::isGreater($this->getFrete(), 0.00)) {
665 2
            Util::appendNode($produto, 'vFrete', $this->getFrete(true));
666 2
        }
667 27
        if (Util::isGreater($this->getSeguro(), 0.00)) {
668 2
            Util::appendNode($produto, 'vSeg', $this->getSeguro(true));
669 2
        }
670 27
        if (Util::isGreater($this->getDesconto(), 0.00)) {
671 27
            Util::appendNode($produto, 'vDesc', $this->getDesconto(true));
672 27
        }
673 27
        if (Util::isGreater($this->getDespesas(), 0.00)) {
674 2
            Util::appendNode($produto, 'vOutro', $this->getDespesas(true));
675 2
        }
676 27
        Util::appendNode($produto, 'indTot', $this->getMultiplicador(true));
677
//		Util::appendNode($produto, 'DI', $this->getImportacoes(true));
678
//		Util::appendNode($produto, 'detExport', $this->getDetalhes(true));
679 27
        if (!is_null($this->getPedido())) {
680 2
            Util::appendNode($produto, 'xPed', $this->getPedido(true));
681 2
        }
682 27
        Util::appendNode($produto, 'nItemPed', $this->getItem(true));
683
//		Util::appendNode($produto, 'nFCI', $this->getControle(true));
684 27
        $element->appendChild($produto);
685
686 27
        $imposto = $dom->createElement('imposto');
687 27
        $grupos = array();
688 27
        $_impostos = $this->getImpostos();
689 27
        foreach ($_impostos as $_imposto) {
690 27
            if (is_null($_imposto->getBase())) {
691 2
                $_imposto->setBase($this->getBase());
692 2
            }
693 27
            $grupos[$_imposto->getGrupo(true)][] = $_imposto;
694 27
        }
695 27
        $imposto_info = $this->getImpostoInfo();
696 27
        $this->setTributos($imposto_info['total']);
697 27
        Util::appendNode($imposto, 'vTotTrib', Util::toCurrency($imposto_info['total']));
698 27
        foreach ($grupos as $tag => $_grupo) {
699 27
            $grupo = $dom->createElement($tag);
700 27
            foreach ($_grupo as $_imposto) {
701 27
                $node = $_imposto->getNode();
702 27
                $node = $dom->importNode($node, true);
703 27
                $grupo->appendChild($node);
704 27
            }
705 27
            $imposto->appendChild($grupo);
706 27
        }
707 27
        $element->appendChild($imposto);
708
        // TODO: verificar se é obrigatório a informação adicional abaixo
709 27
        $complemento = self::addNodeInformacoes($imposto_info, $element);
710 27
        $this->setComplemento($complemento);
711 27
        return $element;
712
    }
713
714 24
    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...
715
    {
716 24
        $name = is_null($name)?'det':$name;
717 24
        if ($element->nodeName != $name) {
718
            $_fields = $element->getElementsByTagName($name);
719
            if ($_fields->length == 0) {
720
                throw new \Exception('Tag "'.$name.'" do Produto não encontrada', 404);
721
            }
722
            $element = $_fields->item(0);
723
        }
724 24
        $root = $element;
725 24
        $element = parent::loadNode($element, $name);
726 24
        $this->setItem(Util::loadNode($element, 'nItemPed'));
727 24
        $this->setPedido(Util::loadNode($element, 'xPed'));
728 24
        $this->setCodigo(
729 24
            Util::loadNode(
730 24
                $element,
731 24
                'cProd',
732
                'Tag "cProd" do campo "Codigo" não encontrada no Produto'
733 24
            )
734 24
        );
735 24
        $this->setCodigoTributario(
736 24
            Util::loadNode(
737 24
                $element,
738 24
                'cEANTrib',
739
                'Tag "cEANTrib" do campo "CodigoTributario" não encontrada no Produto'
740 24
            )
741 24
        );
742 24
        $this->setCodigoBarras(
743 24
            Util::loadNode(
744 24
                $element,
745 24
                'cEAN',
746
                'Tag "cEAN" do campo "CodigoBarras" não encontrada no Produto'
747 24
            )
748 24
        );
749 24
        $this->setDescricao(
750 24
            Util::loadNode(
751 24
                $element,
752 24
                'xProd',
753
                'Tag "xProd" do campo "Descricao" não encontrada no Produto'
754 24
            )
755 24
        );
756 24
        $this->setUnidade(
757 24
            Util::loadNode(
758 24
                $element,
759 24
                'uCom',
760
                'Tag "uCom" do campo "Unidade" não encontrada no Produto'
761 24
            )
762 24
        );
763 24
        $this->setMultiplicador(
764 24
            Util::loadNode(
765 24
                $element,
766 24
                'indTot',
767
                'Tag "indTot" do campo "Multiplicador" não encontrada no Produto'
768 24
            )
769 24
        );
770 24
        $this->setQuantidade(
771 24
            Util::loadNode(
772 24
                $element,
773 24
                'qCom',
774
                'Tag "qCom" do campo "Quantidade" não encontrada no Produto'
775 24
            )
776 24
        );
777 24
        $this->setTributada(
778 24
            Util::loadNode(
779 24
                $element,
780 24
                'qTrib',
781
                'Tag "qTrib" do campo "Tributada" não encontrada no Produto'
782 24
            )
783 24
        );
784 24
        $this->setExcecao(Util::loadNode($element, 'EXTIPI'));
785 24
        $this->setCFOP(
786 24
            Util::loadNode(
787 24
                $element,
788 24
                'CFOP',
789
                'Tag "CFOP" do campo "CFOP" não encontrada no Produto'
790 24
            )
791 24
        );
792 24
        $this->setNCM(
793 24
            Util::loadNode(
794 24
                $element,
795 24
                'NCM',
796
                'Tag "NCM" do campo "NCM" não encontrada no Produto'
797 24
            )
798 24
        );
799 24
        $this->setCEST(Util::loadNode($element, 'CEST'));
800 24
        $impostos = array();
801 24
        $_fields = $root->getElementsByTagName('imposto');
802 24
        if ($_fields->length == 0) {
803
            throw new \Exception('Tag "imposto" da lista de "Impostos" não encontrada no Produto', 404);
804
        }
805 24
        $imposto_node = $_fields->item(0);
806 24
        $this->setTributos(Util::loadNode($imposto_node, 'vTotTrib'));
807 24
        $_items = $imposto_node->childNodes;
808 24
        $total = new \NFe\Entity\Imposto\Total();
809 24
        foreach ($_items as $_item) {
810 24
            if (!$_item->hasChildNodes() || $_item->nodeType !== XML_ELEMENT_NODE) {
811 22
                continue;
812
            }
813 24
            $total->setGrupo($_item->nodeName);
814 24
            foreach ($_item->childNodes as $_subitem) {
815 24
                if ($_subitem->nodeType !== XML_ELEMENT_NODE) {
816 24
                    continue;
817
                }
818 24
                $imposto = Imposto::loadImposto($_subitem, $total->getGrupo());
819 24
                if ($imposto === false) {
820
                    continue;
821
                }
822 24
                $imposto->setGrupo($total->getGrupo());
823 24
                $impostos[] = $imposto;
824 24
            }
825 24
        }
826 24
        $this->setImpostos($impostos);
827 24
        $this->setComplemento(Util::loadNode($root, 'infAdProd'));
828 24
        return $element;
829
    }
830
}
831