Passed
Push — master ( 22a4bb...4eeb09 )
by Francimar
05:29
created

Evento   D

Complexity

Total Complexity 98

Size/Duplication

Total Lines 696
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 80.21%

Importance

Changes 0
Metric Value
wmc 98
lcom 1
cbo 6
dl 0
loc 696
ccs 77
cts 96
cp 0.8021
rs 4.4629
c 0
b 0
f 0

41 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getID() 0 7 2
A setID() 0 5 1
A getOrgao() 0 9 3
A setOrgao() 0 5 1
A getIdentificador() 0 7 2
A setIdentificador() 0 5 1
A getChave() 0 7 2
A setChave() 0 5 1
A getData() 0 7 2
A setData() 0 8 2
A getTipo() 0 7 2
A setTipo() 0 5 1
A getSequencia() 0 7 2
A setSequencia() 0 5 1
A getDescricao() 0 7 2
A setDescricao() 0 5 1
A getNumero() 0 7 2
A setNumero() 0 5 1
A getJustificativa() 0 7 2
A setJustificativa() 0 5 1
A getEmail() 0 7 2
A setEmail() 0 5 1
A setModelo() 0 13 3
A setInformacao() 0 5 1
A getModelo() 0 13 4
A getInformacao() 0 4 1
A isCNPJ() 0 4 1
A isProcessado() 0 4 1
A isCancelado() 0 4 1
A toArray() 0 18 1
F fromArray() 0 75 19
A gerarID() 0 10 1
B getNode() 0 44 3
C getReturnNode() 0 44 8
C loadNode() 0 72 7
A getConteudo() 0 20 1
A envia() 0 18 2
B addInformacao() 0 30 2
A assinar() 0 16 2
B validar() 0 23 4

How to fix   Complexity   

Complex Class

Complex classes like Evento often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Evento, and based on these observations, apply Extract Interface, too.

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\Task;
29
30
use NFe\Core\Nota;
31
use NFe\Core\SEFAZ;
32
use NFe\Common\Util;
33
use NFe\Exception\ValidationException;
34
use FR3D\XmlDSig\Adapter\AdapterInterface;
35
use FR3D\XmlDSig\Adapter\XmlseclibsAdapter;
36
37
class Evento extends Retorno
0 ignored issues
show
Complexity introduced by
This class has a complexity of 98 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...
38
{
39
40
    const VERSAO = '1.00';
41
42
    const TIPO_CANCELAMENTO = '110111';
43
44
    private $id;
45
    private $orgao;
46
    private $identificador;
47
    private $chave;
48
    private $data;
49
    private $tipo;
50
    private $sequencia;
51
    private $descricao;
52
    private $numero;
53
    private $justificativa;
54
    private $email;
55
    private $modelo;
56
    private $informacao;
57
58 1
    public function __construct($evento = array())
59
    {
60 1
        parent::__construct($evento);
61 1
    }
62
63
    /**
64
     * Identificador da TAG a ser assinada, a regra de formação do Id é: "ID" +
65
     * tpEvento +  chave da NF-e + nSeqEvento
66
     */
67
    public function getID($normalize = false)
68
    {
69
        if (!$normalize) {
70
            return $this->id;
71
        }
72
        return 'ID'.$this->id;
73
    }
74
75 1
    public function setID($id)
76
    {
77 1
        $this->id = $id;
78 1
        return $this;
79
    }
80
81
    /**
82
     * Código do órgão de recepção do Evento. Utilizar a Tabela do IBGE
83
     * extendida, utilizar 91 para identificar o Ambiente Nacional
84
     */
85
    public function getOrgao($normalize = false)
86
    {
87
        if (!$normalize || is_numeric($this->orgao)) {
88
            return $this->orgao;
89
        }
90
91
        $db = SEFAZ::getInstance()->getConfiguracao()->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...
92
        return $db->getCodigoOrgao($this->orgao);
93
    }
94
95 1
    public function setOrgao($orgao)
96
    {
97 1
        $this->orgao = $orgao;
98 1
        return $this;
99
    }
100
101
    /**
102
     * Identificação do  autor do evento
103
     */
104
    public function getIdentificador($normalize = false)
105
    {
106
        if (!$normalize) {
107
            return $this->identificador;
108
        }
109
        return $this->identificador;
110
    }
111
112 1
    public function setIdentificador($identificador)
113
    {
114 1
        $this->identificador = $identificador;
115 1
        return $this;
116
    }
117
118
    /**
119
     * Chave de Acesso da NF-e vinculada ao evento
120
     */
121
    public function getChave($normalize = false)
122
    {
123
        if (!$normalize) {
124
            return $this->chave;
125
        }
126
        return $this->chave;
127
    }
128
129 1
    public function setChave($chave)
130
    {
131 1
        $this->chave = $chave;
132 1
        return $this;
133
    }
134
135
    /**
136
     * Data e Hora do Evento, formato UTC (AAAA-MM-DDThh:mm:ssTZD, onde TZD =
137
     * +hh:mm ou -hh:mm)
138
     */
139
    public function getData($normalize = false)
140
    {
141
        if (!$normalize) {
142
            return $this->data;
143
        }
144
        return Util::toDateTime($this->data);
145
    }
146
147 1
    public function setData($data)
148
    {
149 1
        if (!is_numeric($data)) {
150 1
            $data = strtotime($data);
151
        }
152 1
        $this->data = $data;
153 1
        return $this;
154
    }
155
156
    /**
157
     * Tipo do Evento
158
     */
159
    public function getTipo($normalize = false)
160
    {
161
        if (!$normalize) {
162
            return $this->tipo;
163
        }
164
        return $this->tipo;
165
    }
166
167 1
    public function setTipo($tipo)
168
    {
169 1
        $this->tipo = $tipo;
170 1
        return $this;
171
    }
172
173
    /**
174
     * Seqüencial do evento para o mesmo tipo de evento.  Para maioria dos
175
     * eventos será 1, nos casos em que possa existir mais de um evento, como é
176
     * o caso da carta de correção, o autor do evento deve numerar de forma
177
     * seqüencial.
178
     */
179
    public function getSequencia($normalize = false)
180
    {
181
        if (!$normalize) {
182
            return $this->sequencia;
183
        }
184
        return $this->sequencia;
185
    }
186
187 1
    public function setSequencia($sequencia)
188
    {
189 1
        $this->sequencia = $sequencia;
190 1
        return $this;
191
    }
192
193
    /**
194
     * Descrição do Evento
195
     */
196
    public function getDescricao($normalize = false)
197
    {
198
        if (!$normalize) {
199
            return $this->descricao;
200
        }
201
        return $this->descricao;
202
    }
203
204 1
    public function setDescricao($descricao)
205
    {
206 1
        $this->descricao = $descricao;
207 1
        return $this;
208
    }
209
210
    /**
211
     * Número do Protocolo de Status da NF-e. 1 posição (1 – Secretaria de
212
     * Fazenda Estadual 2 – Receita Federal); 2 posições ano; 10 seqüencial no
213
     * ano.
214
     */
215
    public function getNumero($normalize = false)
216
    {
217
        if (!$normalize) {
218
            return $this->numero;
219
        }
220
        return $this->numero;
221
    }
222
223 1
    public function setNumero($numero)
224
    {
225 1
        $this->numero = $numero;
226 1
        return $this;
227
    }
228
229
    /**
230
     * Justificativa do cancelamento
231
     */
232
    public function getJustificativa($normalize = false)
233
    {
234
        if (!$normalize) {
235
            return $this->justificativa;
236
        }
237
        return $this->justificativa;
238
    }
239
240 1
    public function setJustificativa($justificativa)
241
    {
242 1
        $this->justificativa = $justificativa;
243 1
        return $this;
244
    }
245
246
    /**
247
     * email do destinatário
248
     */
249
    public function getEmail($normalize = false)
250
    {
251
        if (!$normalize) {
252
            return $this->email;
253
        }
254
        return $this->email;
255
    }
256
257 1
    public function setEmail($email)
258
    {
259 1
        $this->email = $email;
260 1
        return $this;
261
    }
262
263
    /**
264
     * Código do modelo do Documento Fiscal. 55 = NF-e; 65 = NFC-e.
265
     * @param boolean $normalize informa se o modelo deve estar no formato do XML
266
     * @return mixed modelo do Envio
267
     */
268
    public function getModelo($normalize = false)
269
    {
270
        if (!$normalize) {
271
            return $this->modelo;
272
        }
273
        switch ($this->modelo) {
274
            case Nota::MODELO_NFE:
275
                return '55';
276
            case Nota::MODELO_NFCE:
277
                return '65';
278
        }
279
        return $this->modelo;
280
    }
281
282
    /**
283
     * Altera o valor do Modelo para o informado no parâmetro
284
     * @param mixed $modelo novo valor para Modelo
285
     * @return Envio A própria instância da classe
286
     */
287 1
    public function setModelo($modelo)
288
    {
289
        switch ($modelo) {
290 1
            case '55':
291
                $modelo = Nota::MODELO_NFE;
292
                break;
293 1
            case '65':
294
                $modelo = Nota::MODELO_NFCE;
295
                break;
296
        }
297 1
        $this->modelo = $modelo;
298 1
        return $this;
299
    }
300
301
    /**
302
     * Resposta de informação do evento
303
     */
304
    public function getInformacao()
305
    {
306
        return $this->informacao;
307
    }
308
309 1
    public function setInformacao($informacao)
310
    {
311 1
        $this->informacao = $informacao;
312 1
        return $this;
313
    }
314
315
    /**
316
     * Informa se a identificação é um CNPJ
317
     */
318
    public function isCNPJ()
319
    {
320
        return strlen($this->getIdentificador()) == 14;
321
    }
322
323
    /**
324
     * Informa se o lote já foi processado e já tem um protocolo
325
     */
326
    public function isProcessado()
327
    {
328
        return $this->getStatus() == '128';
329
    }
330
331
    /**
332
     * Informa se a nota foi cancelada com sucesso
333
     */
334
    public function isCancelado()
335
    {
336
        return in_array($this->getStatus(), array('135', '155'));
337
    }
338
339
    public function toArray($recursive = false)
340
    {
341
        $evento = parent::toArray($recursive);
342
        $evento['id'] = $this->getID();
343
        $evento['orgao'] = $this->getOrgao();
344
        $evento['identificador'] = $this->getIdentificador();
345
        $evento['chave'] = $this->getChave();
346
        $evento['data'] = $this->getData();
347
        $evento['tipo'] = $this->getTipo();
348
        $evento['sequencia'] = $this->getSequencia();
349
        $evento['descricao'] = $this->getDescricao();
350
        $evento['numero'] = $this->getNumero();
351
        $evento['justificativa'] = $this->getJustificativa();
352
        $evento['email'] = $this->getEmail();
353
        $evento['modelo'] = $this->getModelo();
354
        $evento['informacao'] = $this->getInformacao();
355
        return $evento;
356
    }
357
358 1
    public function fromArray($evento = array())
0 ignored issues
show
Complexity introduced by
This operation has 82944 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...
359
    {
360 1
        if ($evento instanceof Evento) {
361
            $evento = $evento->toArray();
362 1
        } elseif (!is_array($evento)) {
363
            return $this;
364
        }
365 1
        parent::fromArray($evento);
366 1
        if (isset($evento['id'])) {
367
            $this->setID($evento['id']);
368
        } else {
369 1
            $this->setID(null);
370
        }
371 1
        if (isset($evento['orgao'])) {
372
            $this->setOrgao($evento['orgao']);
373
        } else {
374 1
            $this->setOrgao(null);
375
        }
376 1
        if (isset($evento['identificador'])) {
377
            $this->setIdentificador($evento['identificador']);
378
        } else {
379 1
            $this->setIdentificador(null);
380
        }
381 1
        if (isset($evento['chave'])) {
382
            $this->setChave($evento['chave']);
383
        } else {
384 1
            $this->setChave(null);
385
        }
386 1
        if (isset($evento['data'])) {
387
            $this->setData($evento['data']);
388
        } else {
389 1
            $this->setData(null);
390
        }
391 1
        if (!isset($evento['tipo']) || is_null($evento['tipo'])) {
392 1
            $this->setTipo(self::TIPO_CANCELAMENTO);
393
        } else {
394
            $this->setTipo($evento['tipo']);
395
        }
396 1
        if (!isset($evento['sequencia']) || is_null($evento['sequencia'])) {
397 1
            $this->setSequencia(1);
398
        } else {
399
            $this->setSequencia($evento['sequencia']);
400
        }
401 1
        if (!isset($evento['descricao']) || is_null($evento['descricao'])) {
402 1
            $this->setDescricao('Cancelamento');
403
        } else {
404
            $this->setDescricao($evento['descricao']);
405
        }
406 1
        if (isset($evento['numero'])) {
407
            $this->setNumero($evento['numero']);
408
        } else {
409 1
            $this->setNumero(null);
410
        }
411 1
        if (isset($evento['justificativa'])) {
412
            $this->setJustificativa($evento['justificativa']);
413
        } else {
414 1
            $this->setJustificativa(null);
415
        }
416 1
        if (isset($evento['email'])) {
417
            $this->setEmail($evento['email']);
418
        } else {
419 1
            $this->setEmail(null);
420
        }
421 1
        if (isset($evento['modelo'])) {
422
            $this->setModelo($evento['modelo']);
423
        } else {
424 1
            $this->setModelo(null);
425
        }
426 1
        if (isset($evento['informacao'])) {
427
            $this->setInformacao($evento['informacao']);
428
        } else {
429 1
            $this->setInformacao(null);
430
        }
431 1
        return $this;
432
    }
433
434
    /**
435
     * Gera o ID, a regra de formação do Id é: "ID" +
436
     * tpEvento +  chave da NF-e + nSeqEvento
437
     */
438
    public function gerarID()
439
    {
440
        $id = sprintf(
441
            '%s%s%02d',
442
            $this->getTipo(true),
443
            $this->getChave(true),
444
            $this->getSequencia(true)
445
        );
446
        return $id;
447
    }
448
449
    public function getNode($name = null)
450
    {
451
        $this->setID($this->gerarID());
452
453
        $dom = new \DOMDocument('1.0', 'UTF-8');
454
        $element = $dom->createElement(is_null($name)?'evento':$name);
455
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
456
        $versao = $dom->createAttribute('versao');
457
        $versao->value = self::VERSAO;
458
        $element->appendChild($versao);
459
460
        $info = $dom->createElement('infEvento');
461
        $dom = $element->ownerDocument;
462
        $id = $dom->createAttribute('Id');
463
        $id->value = $this->getID(true);
464
        $info->appendChild($id);
465
        
466
        Util::appendNode($info, 'cOrgao', $this->getOrgao(true));
467
        Util::appendNode($info, 'tpAmb', $this->getAmbiente(true));
468
        if ($this->isCNPJ()) {
469
            Util::appendNode($info, 'CNPJ', $this->getIdentificador(true));
470
        } else {
471
            Util::appendNode($info, 'CPF', $this->getIdentificador(true));
472
        }
473
        Util::appendNode($info, 'chNFe', $this->getChave(true));
474
        Util::appendNode($info, 'dhEvento', $this->getData(true));
475
        Util::appendNode($info, 'tpEvento', $this->getTipo(true));
476
        Util::appendNode($info, 'nSeqEvento', $this->getSequencia(true));
477
        Util::appendNode($info, 'verEvento', self::VERSAO);
478
479
        $detalhes = $dom->createElement('detEvento');
480
        $versao = $dom->createAttribute('versao');
481
        $versao->value = self::VERSAO;
482
        $detalhes->appendChild($versao);
483
484
        Util::appendNode($detalhes, 'descEvento', $this->getDescricao(true));
485
        Util::appendNode($detalhes, 'nProt', $this->getNumero(true));
486
        Util::appendNode($detalhes, 'xJust', $this->getJustificativa(true));
487
        $info->appendChild($detalhes);
488
489
        $element->appendChild($info);
490
        $dom->appendChild($element);
491
        return $element;
492
    }
493
494
    public function getReturnNode()
495
    {
496
        $outros = parent::getNode('infEvento');
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getNode() instead of getReturnNode()). Are you sure this is correct? If so, you might want to change this to $this->getNode().

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...
497
        $element = $this->getNode('retEvento');
498
        $dom = $element->ownerDocument;
499
        $element->removeAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns');
500
        $info = $dom->getElementsByTagName('infEvento')->item(0);
501
        $info->removeAttribute('Id');
502
        $removeTags = array('detEvento', 'verEvento', 'dhEvento', 'CNPJ', 'CPF', 'cOrgao');
0 ignored issues
show
Coding Style introduced by
$removeTags does not seem to conform to the naming convention (^[a-z_][a-z0-9_]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
503
        foreach ($removeTags as $key) {
0 ignored issues
show
Coding Style introduced by
$removeTags does not seem to conform to the naming convention (^[a-z_][a-z0-9_]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
504
            $_fields = $info->getElementsByTagName($key);
505
            if ($_fields->length == 0) {
506
                continue;
507
            }
508
            $node = $_fields->item(0);
509
            $info->removeChild($node);
510
        }
511
        $chave = $info->getElementsByTagName('chNFe')->item(0);
512
        foreach ($outros->childNodes as $node) {
513
            $node = $dom->importNode($node, true);
514
            $list = $info->getElementsByTagName($node->nodeName);
515
            if ($list->length == 1) {
516
                continue;
517
            }
518
            $info->insertBefore($node, $chave);
519
        }
520
        $status = $info->getElementsByTagName('cStat')->item(0);
521
        $info->insertBefore($dom->createElement('cOrgao', $this->getOrgao(true)), $status);
522
        $sequencia = $info->getElementsByTagName('nSeqEvento')->item(0);
523
        $info->insertBefore($dom->createElement('xEvento', $this->getDescricao(true)), $sequencia);
524
        if (!is_null($this->getIdentificador())) {
525
            if ($this->isCNPJ()) {
526
                Util::appendNode($info, 'CNPJDest', $this->getIdentificador(true));
527
            } else {
528
                Util::appendNode($info, 'CPFDest', $this->getIdentificador(true));
529
            }
530
        }
531
        if (!is_null($this->getEmail())) {
532
            Util::appendNode($info, 'emailDest', $this->getEmail(true));
533
        }
534
        Util::appendNode($info, 'dhRegEvento', $this->getData(true));
535
        Util::appendNode($info, 'nProt', $this->getNumero(true));
536
        return $element;
537
    }
538
539
    public function loadNode($element, $name = null)
540
    {
541
        $name = is_null($name)?'infEvento':$name;
542
        $element = parent::loadNode($element, $name);
543
        $this->setOrgao(
544
            Util::loadNode(
545
                $element,
546
                'cOrgao',
547
                'Tag "cOrgao" do campo "Orgao" não encontrada'
548
            )
549
        );
550
        if ($name == 'retEnvEvento') {
551
            return $element;
552
        }
553
        $this->setChave(
554
            Util::loadNode(
555
                $element,
556
                'chNFe',
557
                'Tag "chNFe" do campo "Chave" não encontrada'
558
            )
559
        );
560
        $this->setTipo(
561
            Util::loadNode(
562
                $element,
563
                'tpEvento',
564
                'Tag "tpEvento" do campo "Tipo" não encontrada'
565
            )
566
        );
567
        $this->setDescricao(
568
            Util::loadNode(
569
                $element,
570
                'xEvento',
571
                'Tag "xEvento" do campo "Descricao" não encontrada'
572
            )
573
        );
574
        $this->setSequencia(
575
            Util::loadNode(
576
                $element,
577
                'nSeqEvento',
578
                'Tag "nSeqEvento" do campo "Sequencia" não encontrada'
579
            )
580
        );
581
        $this->setData(
582
            Util::loadNode(
583
                $element,
584
                'dhRegEvento',
585
                'Tag "dhRegEvento" do campo "Data" não encontrada'
586
            )
587
        );
588
        $identificador = null;
589
        $_fields = $element->getElementsByTagName('CNPJDest');
590
        if ($_fields->length == 0) {
591
            $_fields = $element->getElementsByTagName('CPFDest');
592
        }
593
        if ($_fields->length > 0) {
594
            $identificador = $_fields->item(0)->nodeValue;
595
        }
596
        $this->setIdentificador($identificador);
597
        $email = null;
598
        $_fields = $element->getElementsByTagName('emailDest');
599
        if ($_fields->length > 0) {
600
            $email = $_fields->item(0)->nodeValue;
601
        }
602
        $this->setEmail($email);
603
        $numero = null;
604
        $_fields = $element->getElementsByTagName('nProt');
605
        if ($_fields->length > 0) {
606
            $numero = $_fields->item(0)->nodeValue;
607
        }
608
        $this->setNumero($numero);
609
        return $element;
610
    }
611
612
    private function getConteudo($dom)
613
    {
614
        $config = SEFAZ::getInstance()->getConfiguracao();
0 ignored issues
show
Unused Code introduced by
$config is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
615
        $dob = new \DOMDocument('1.0', 'UTF-8');
616
        $envio = $dob->createElement('envEvento');
617
        $envio->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
618
        $versao = $dob->createAttribute('versao');
619
        $versao->value = self::VERSAO;
620
        $envio->appendChild($versao);
621
        Util::appendNode($envio, 'idLote', self::genLote());
622
        // Corrige xmlns:default
623
        // $data = $dob->importNode($dom->documentElement, true);
624
        // $envio->appendChild($data);
625
        Util::appendNode($envio, 'evento', 0);
626
        $dob->appendChild($envio);
627
        // Corrige xmlns:default
628
        // return $dob;
629
        $xml = $dob->saveXML($dob->documentElement);
630
        return str_replace('<evento>0</evento>', $dom->saveXML($dom->documentElement), $xml);
631
    }
632
633
    public function envia($dom)
634
    {
635
        $envio = new Envio();
636
        $envio->setServico(Envio::SERVICO_EVENTO);
637
        $envio->setAmbiente($this->getAmbiente());
638
        $envio->setModelo($this->getModelo());
639
        $envio->setEmissao(Nota::EMISSAO_NORMAL);
640
        $envio->setConteudo($this->getConteudo($dom));
641
        $resp = $envio->envia();
642
        $this->loadNode($resp, 'retEnvEvento');
643
        if (!$this->isProcessado()) {
644
            throw new \Exception($this->getMotivo(), $this->getStatus());
645
        }
646
        $retorno = new Evento();
647
        $retorno->loadNode($resp);
648
        $this->setInformacao($retorno);
649
        return $retorno;
650
    }
651
652
    /**
653
     * Adiciona a informação no XML do evento
654
     */
655
    public function addInformacao($dom)
656
    {
657
        if (is_null($this->getInformacao())) {
658
            throw new \Exception('A informação não foi informado no evento "'.$this->getID().'"', 404);
659
        }
660
        $evento = $dom->getElementsByTagName('evento')->item(0);
661
        // Corrige xmlns:default
662
        $evento_xml = $dom->saveXML($evento);
663
664
        $element = $dom->createElement('procEventoNFe');
665
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
666
        $versao = $dom->createAttribute('versao');
667
        $versao->value = self::VERSAO;
668
        $element->appendChild($versao);
669
        $dom->removeChild($evento);
670
        // Corrige xmlns:default
671
        $evento = $dom->createElement('evento', 0);
672
673
        $element->appendChild($evento);
674
        $info = $this->getInformacao()->getReturnNode();
675
        $info = $dom->importNode($info, true);
676
        $element->appendChild($info);
677
        $dom->appendChild($element);
678
        // Corrige xmlns:default
679
        $xml = $dom->saveXML();
680
        $xml = str_replace('<evento>0</evento>', $evento_xml, $xml);
681
        $dom->loadXML($xml);
682
683
        return $dom;
684
    }
685
686
    /**
687
     * Assina o XML com a assinatura eletrônica do tipo A1
688
     */
689
    public function assinar($dom = null)
690
    {
691
        if (is_null($dom)) {
692
            $xml = $this->getNode();
693
            $dom = $xml->ownerDocument;
694
        }
695
        $config = SEFAZ::getInstance()->getConfiguracao();
696
697
        $adapter = new XmlseclibsAdapter();
698
        $adapter->setPrivateKey($config->getChavePrivada());
699
        $adapter->setPublicKey($config->getChavePublica());
700
        $adapter->addTransform(AdapterInterface::ENVELOPED);
701
        $adapter->addTransform(AdapterInterface::XML_C14N);
702
        $adapter->sign($dom, 'infEvento');
703
        return $dom;
704
    }
705
706
    /**
707
     * Valida o documento após assinar
708
     */
709
    public function validar($dom)
710
    {
711
        $dom->loadXML($dom->saveXML());
712
        $xsd_path = dirname(__DIR__) . '/Core/schema';
713
        $xsd_file = $xsd_path . '/cancelamento/eventoCancNFe_v1.00.xsd';
714
        if (!file_exists($xsd_file)) {
715
            throw new \Exception('O arquivo "'.$xsd_file.'" de esquema XSD não existe!', 404);
716
        }
717
        // Enable user error handling
718
        $save = libxml_use_internal_errors(true);
719
        if ($dom->schemaValidate($xsd_file)) {
720
            libxml_use_internal_errors($save);
721
            return $dom;
722
        }
723
        $msg = array();
724
        $errors = libxml_get_errors();
725
        foreach ($errors as $error) {
726
            $msg[] = 'Não foi possível validar o XML: '.$error->message;
727
        }
728
        libxml_clear_errors();
729
        libxml_use_internal_errors($save);
730
        throw new ValidationException($msg);
731
    }
732
}
733