Passed
Push — master ( 86bb06...22a4bb )
by Francimar
08:25
created

Ajuste::onNotaContingencia()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 10
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 3
crap 20
1
<?php
2
/**
3
 * MIT License
4
 *
5
 * Copyright (c) 2016 MZ Desenvolvimento de Sistemas LTDA
6
 *
7
 * @author Francimar Alves <[email protected]>
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
namespace NFe\Common;
29
30
use NFe\Task\Tarefa;
31
use FR3D\XmlDSig\Adapter\XmlseclibsAdapter;
32
33
/**
34
 * Configurações padrão para emissão de nota fiscal
35
 */
36
class Ajuste extends Configuracao implements Evento
0 ignored issues
show
Complexity introduced by
This class has a complexity of 74 which exceeds the configured maximum of 50.

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

Some resources for further reading:

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

Loading history...
37
{
38
39
    private $pasta_xml_base;
40
    private $pasta_xml_inutilizado;
41
    private $pasta_xml_cancelado;
42
    private $pasta_xml_pendente;
43
    private $pasta_xml_denegado;
44
    private $pasta_xml_rejeitado;
45
    private $pasta_xml_autorizado;
46
    private $pasta_xml_processamento;
47
    private $pasta_xml_assinado;
48
49 7
    public function __construct($ajuste = array())
50
    {
51 7
        parent::__construct($ajuste);
52 7
        $this->setEvento($this);
53
        //$this->setSincrono(true);
54 7
        $this->setTempoLimite(4);
55 7
        $cert_dir = dirname(dirname(dirname(__DIR__))) . '/docs/cert';
56 7
        $this->setArquivoChavePublica($cert_dir . '/public.pem');
57 7
        $this->setArquivoChavePrivada($cert_dir . '/private.pem');
58
59 7
        $this->setPastaXmlBase(dirname(dirname(dirname(__DIR__))) . '/site/xml');
60 7
        $this->setPastaXmlInutilizado('{ambiente}/inutilizado');
61 7
        $this->setPastaXmlCancelado('{ambiente}/cancelado');
62 7
        $this->setPastaXmlPendente('{ambiente}/pendente');
63 7
        $this->setPastaXmlDenegado('{ambiente}/denegado');
64 7
        $this->setPastaXmlRejeitado('{ambiente}/rejeitado');
65 7
        $this->setPastaXmlAutorizado('{ambiente}/autorizado');
66 7
        $this->setPastaXmlProcessamento('{ambiente}/processamento');
67 7
        $this->setPastaXmlAssinado('{ambiente}/assinado');
68 7
    }
69
70
    /**
71
     * Caminho da pasta base para armazenamento dos XML
72
     */
73 1
    public function getPastaXmlBase()
74
    {
75 1
        return $this->pasta_xml_base;
76
    }
77
78 7
    public function setPastaXmlBase($pasta_xml_base)
79
    {
80 7
        $this->pasta_xml_base = $pasta_xml_base;
81 7
        return $this;
82
    }
83
84
    /**
85
     * Pasta onde ficam os XML das inutilizações de números de notas
86
     */
87
    private function aplicaAmbiente($ambiente, $caminho)
88
    {
89
        switch ($ambiente) {
90
            case '1':
91
                $ambiente = self::AMBIENTE_PRODUCAO;
92
                break;
93
            case '2':
94
                $ambiente = self::AMBIENTE_HOMOLOGACAO;
95
                break;
96
        }
97
        return rtrim(str_replace('{ambiente}', $ambiente, rtrim($this->getPastaXmlBase(), '/').
98
            '/'.ltrim($caminho, '/')), '/');
99
    }
100
101
    /**
102
     * Pasta onde ficam os XML das inutilizações de números de notas
103
     */
104 1
    public function getPastaXmlInutilizado($ambiente = null)
105
    {
106 1
        if (is_null($ambiente)) {
107 1
            return $this->pasta_xml_inutilizado;
108
        }
109
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_inutilizado);
110
    }
111
112 7
    public function setPastaXmlInutilizado($pasta_xml_inutilizado)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $pasta_xml_inutilizado exceeds the maximum configured length of 20.

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

Loading history...
113
    {
114 7
        $this->pasta_xml_inutilizado = $pasta_xml_inutilizado;
115 7
        return $this;
116
    }
117
118
    /**
119
     * Pasta onde ficam os XML das notas após serem aceitas e depois canceladas
120
     */
121 1
    public function getPastaXmlCancelado($ambiente = null)
122
    {
123 1
        if (is_null($ambiente)) {
124 1
            return $this->pasta_xml_cancelado;
125
        }
126
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_cancelado);
127
    }
128
129 7
    public function setPastaXmlCancelado($pasta_xml_cancelado)
130
    {
131 7
        $this->pasta_xml_cancelado = $pasta_xml_cancelado;
132 7
        return $this;
133
    }
134
135
    /**
136
     * Pasta onde ficam os XML das notas pendentes de consulta
137
     */
138 1
    public function getPastaXmlPendente($ambiente = null)
139
    {
140 1
        if (is_null($ambiente)) {
141 1
            return $this->pasta_xml_pendente;
142
        }
143
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_pendente);
144
    }
145
146 7
    public function setPastaXmlPendente($pasta_xml_pendente)
147
    {
148 7
        $this->pasta_xml_pendente = $pasta_xml_pendente;
149 7
        return $this;
150
    }
151
152
    /**
153
     * Pasta onde ficam os XMLs após enviados e denegados
154
     */
155 1
    public function getPastaXmlDenegado($ambiente = null)
156
    {
157 1
        if (is_null($ambiente)) {
158 1
            return $this->pasta_xml_denegado;
159
        }
160
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_denegado);
161
    }
162
163 7
    public function setPastaXmlDenegado($pasta_xml_denegado)
164
    {
165 7
        $this->pasta_xml_denegado = $pasta_xml_denegado;
166 7
        return $this;
167
    }
168
169
    /**
170
     * Pasta onde ficam os XML das notas após serem enviadas e rejeitadas
171
     */
172 1
    public function getPastaXmlRejeitado($ambiente = null)
173
    {
174 1
        if (is_null($ambiente)) {
175 1
            return $this->pasta_xml_rejeitado;
176
        }
177
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_rejeitado);
178
    }
179
180 7
    public function setPastaXmlRejeitado($pasta_xml_rejeitado)
181
    {
182 7
        $this->pasta_xml_rejeitado = $pasta_xml_rejeitado;
183 7
        return $this;
184
    }
185
186
    /**
187
     * Pasta onde ficam os XML das notas após serem enviados e aceitos pela
188
     * SEFAZ
189
     */
190 1
    public function getPastaXmlAutorizado($ambiente = null)
191
    {
192 1
        if (is_null($ambiente)) {
193 1
            return $this->pasta_xml_autorizado;
194
        }
195
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_autorizado);
196
    }
197
198 7
    public function setPastaXmlAutorizado($pasta_xml_autorizado)
199
    {
200 7
        $this->pasta_xml_autorizado = $pasta_xml_autorizado;
201 7
        return $this;
202
    }
203
204
    /**
205
     * Pasta onde ficam os XML das notas em processamento de retorno de
206
     * autorização
207
     */
208 1
    public function getPastaXmlProcessamento($ambiente = null)
209
    {
210 1
        if (is_null($ambiente)) {
211 1
            return $this->pasta_xml_processamento;
212
        }
213
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_processamento);
214
    }
215
216 7
    public function setPastaXmlProcessamento($pasta_xml_processamento)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $pasta_xml_processamento exceeds the maximum configured length of 20.

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

Loading history...
217
    {
218 7
        $this->pasta_xml_processamento = $pasta_xml_processamento;
219 7
        return $this;
220
    }
221
222
    /**
223
     * Pasta onde ficam os XMLs após assinado e antes de serem enviados
224
     */
225 1
    public function getPastaXmlAssinado($ambiente = null)
226
    {
227 1
        if (is_null($ambiente)) {
228 1
            return $this->pasta_xml_assinado;
229
        }
230
        return $this->aplicaAmbiente($ambiente, $this->pasta_xml_assinado);
231
    }
232
233 7
    public function setPastaXmlAssinado($pasta_xml_assinado)
234
    {
235 7
        $this->pasta_xml_assinado = $pasta_xml_assinado;
236 7
        return $this;
237
    }
238
239
    /**
240
     * Chamado quando o XML da nota foi gerado
241
     */
242
    public function onNotaGerada($nota, $xml)
243
    {
244
        //echo 'XML gerado!<br>';
245
    }
246
247
    /**
248
     * Chamado após o XML da nota ser assinado
249
     */
250
    public function onNotaAssinada($nota, $xml)
251
    {
252
        //echo 'XML assinado!<br>';
253
    }
254
255
    /**
256
     * Chamado após o XML da nota ser validado com sucesso
257
     */
258
    public function onNotaValidada($nota, $xml)
259
    {
260
        //echo 'XML validado!<br>';
261
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
262
        file_put_contents($filename, $xml->saveXML());
263
        $dom = new \DOMDocument();
264
        $dom->load($filename);
265
        $adapter = new XmlseclibsAdapter();
266
        if (!$adapter->verify($dom)) {
267
            throw new \Exception('Falha na assinatura do XML');
268
        }
269
    }
270
271
    /**
272
     * Chamado antes de enviar a nota para a SEFAZ
273
     */
274
    public function onNotaEnviando($nota, $xml)
275
    {
276
        //echo 'Enviando XML...<br>';
277
    }
278
279
    /**
280
     * Chamado quando a forma de emissão da nota fiscal muda para contigência,
281
     * aqui deve ser decidido se o número da nota deverá ser pulado e se esse
282
     * número deve ser cancelado ou inutilizado
283
     */
284
    public function onNotaContingencia($nota, $offline, $exception)
285
    {
286
        echo 'Forma de emissão alterada para "'.$nota->getEmissao().'" <br>';
287
        // remove o XML salvo anteriormente com a emissão normal
288
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
289
        if (file_exists($filename) && $offline) {
290
            unlink($filename); // só remove se tiver certeza que nenhum dado foi enviado para a SEFAZ
291
        }
292
        // incrementa o número da nota se existir a possibilidade de ter enviado com sucesso
293
        if (!$offline) {
294
            $nota->setNumero($nota->getNumero() + 1);
295
        }
296
    }
297
298
    /**
299
     * Chamado quando a nota foi enviada e aceita pela SEFAZ
300
     */
301 1
    public function onNotaAutorizada($nota, $xml, $retorno)
302 1
    {
303
        //echo 'XML autorizado com sucesso!<br>';
304
305
        // TODO: obter o estado da nota e remover apenas do local correto
306
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
307
        if (file_exists($filename)) {
308
            unlink($filename);
309
        }
310
311
        $filename = $this->getPastaXmlProcessamento($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
312
        if (file_exists($filename)) {
313
            unlink($filename);
314
        }
315
316
        $filename = $this->getPastaXmlAutorizado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
317
        file_put_contents($filename, $xml->saveXML());
318
    }
319
320
    /**
321
     * Chamado quando a emissão da nota foi concluída com sucesso independente
322
     * da forma de emissão
323
     */
324
    public function onNotaCompleto($nota, $xml)
325
    {
326
        //echo 'XML processado com sucesso!<br>';
327
    }
328
329
    /**
330
     * Chamado quando uma nota é rejeitada pela SEFAZ, a nota deve ser
331
     * corrigida para depois ser enviada novamente
332
     */
333
    public function onNotaRejeitada($nota, $xml, $retorno)
334
    {
335
        //echo 'XML rejeitado!<br>';
336
337
        // TODO: obter o estado da nota e remover apenas do local correto
338
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
339
        if (file_exists($filename)) {
340
            unlink($filename);
341
        }
342
343
        $filename = $this->getPastaXmlProcessamento($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
344
        if (file_exists($filename)) {
345
            unlink($filename);
346
        }
347
348
        $filename = $this->getPastaXmlRejeitado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
349
        file_put_contents($filename, $xml->saveXML());
350
    }
351
352
    /**
353
     * Chamado quando a nota é denegada e não pode ser utilizada (outra nota
354
     * deve ser gerada)
355
     */
356
    public function onNotaDenegada($nota, $xml, $retorno)
357
    {
358
        //echo 'XML denagado!<br>';
359
360
        // TODO: obter o estado da nota e remover apenas do local correto
361
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
362
        if (file_exists($filename)) {
363
            unlink($filename);
364
        }
365
366
        $filename = $this->getPastaXmlProcessamento($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
367
        if (file_exists($filename)) {
368
            unlink($filename);
369
        }
370
371
        $filename = $this->getPastaXmlDenegado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
372
        file_put_contents($filename, $xml->saveXML());
373
    }
374
375
    /**
376
     * Chamado após tentar enviar uma nota e não ter certeza se ela foi
377
     * recebida ou não (problemas técnicos), deverá ser feito uma consulta pela
378
     * chave para obter o estado da nota
379
     */
380
    public function onNotaPendente($nota, $xml, $exception)
381
    {
382
        //echo 'XML pendente!<br>';
383
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
384
        if (file_exists($filename)) {
385
            unlink($filename);
386
        }
387
388
        $filename = $this->getPastaXmlPendente($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
389
        file_put_contents($filename, $xml->saveXML());
390
    }
391
392
    /**
393
     * Chamado quando uma nota é enviada, mas não retornou o protocolo que será
394
     * consultado mais tarde
395
     */
396
    public function onNotaProcessando($nota, $xml, $retorno)
397
    {
398
        //echo 'XML em processamento!<br>';
399
        $filename = $this->getPastaXmlAssinado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
400
        if (file_exists($filename)) {
401
            unlink($filename);
402
        }
403
404
        $filename = $this->getPastaXmlProcessamento($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
405
        file_put_contents($filename, $xml->saveXML());
406
    }
407
408
    /**
409
     * Chamado quando uma nota autorizada é cancelada na SEFAZ
410
     */
411
    public function onNotaCancelada($nota, $xml, $retorno)
412
    {
413
        //echo 'XML cancelado!<br>';
414
        $filename = $this->getPastaXmlAutorizado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
415
        if (file_exists($filename)) {
416
            unlink($filename);
417
        }
418
        
419
        $filename = $this->getPastaXmlCancelado($nota->getAmbiente()) . '/' . $nota->getID() . '.xml';
420
        file_put_contents($filename, $xml->saveXML());
421
    }
422
423
    /**
424
     * Chamado quando ocorre um erro nas etapas de geração e envio da nota (Não
425
     * é chamado quando entra em contigência)
426
     */
427
    public function onNotaErro($nota, $exception)
428
    {
429
        echo 'Falha no processamento da nota: '.$exception->getMessage().'<br>';
430
    }
431
432
    /**
433
     * Chamado quando um ou mais números de notas forem inutilizados
434
     */
435
    public function onInutilizado($inutilizacao, $xml)
436
    {
437
        $filename = $this->getPastaXmlInutilizado($inutilizacao->getAmbiente()) . '/' . $inutilizacao->getID() . '.xml';
438
        file_put_contents($filename, $xml->saveXML());
439
    }
440
    
441
    /**
442
     * Chamado quando uma ação é executada
443
     */
444
    public function onTarefaExecutada($tarefa, $retorno)
445
    {
446
        //echo 'Tarefa executada!<br>';
447
        $nota = $tarefa->getNota();
448
        $xml = $tarefa->getDocumento();
449
        if ($tarefa->getAcao() == Tarefa::ACAO_CANCELAR && $retorno->isCancelado()) {
450
            $filename = $this->getPastaXmlCancelado($nota->getAmbiente()) . '/' . $nota->getID() . '-procEventoNFe.xml';
451
            file_put_contents($filename, $xml->saveXML());
452
        }
453
    }
454
455
    /**
456
     * Chamado quando ocorre uma falha na execução de uma tarefa
457
     */
458
    public function onTarefaErro($tarefa, $exception)
459
    {
460
        echo 'Falha no processamento da tarefa: '.$exception->getMessage().'<br>';
461
    }
462
463 1
    public function toArray()
464
    {
465 1
        $ajuste = parent::toArray();
466 1
        $ajuste['pasta_xml_base'] = $this->getPastaXmlBase();
467 1
        $ajuste['pasta_xml_inutilizado'] = $this->getPastaXmlInutilizado();
468 1
        $ajuste['pasta_xml_cancelado'] = $this->getPastaXmlCancelado();
469 1
        $ajuste['pasta_xml_pendente'] = $this->getPastaXmlPendente();
470 1
        $ajuste['pasta_xml_denegado'] = $this->getPastaXmlDenegado();
471 1
        $ajuste['pasta_xml_rejeitado'] = $this->getPastaXmlRejeitado();
472 1
        $ajuste['pasta_xml_autorizado'] = $this->getPastaXmlAutorizado();
473 1
        $ajuste['pasta_xml_processamento'] = $this->getPastaXmlProcessamento();
474 1
        $ajuste['pasta_xml_assinado'] = $this->getPastaXmlAssinado();
475 1
        return $ajuste;
476
    }
477
478 7
    public function fromArray($ajuste = array())
0 ignored issues
show
Complexity introduced by
This operation has 1536 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...
479
    {
480 7
        if ($ajuste instanceof Ajuste) {
481 1
            $ajuste = $ajuste->toArray();
482 7
        } elseif (!is_array($ajuste)) {
483 1
            return $this;
484
        }
485 7
        parent::fromArray($ajuste);
486 7
        if (isset($ajuste['pasta_xml_base'])) {
487 1
            $this->setPastaXmlBase($ajuste['pasta_xml_base']);
488 1
        } else {
489 7
            $this->setPastaXmlBase(null);
490
        }
491 7
        if (isset($ajuste['pasta_xml_inutilizado'])) {
492 1
            $this->setPastaXmlInutilizado($ajuste['pasta_xml_inutilizado']);
493 1
        } else {
494 7
            $this->setPastaXmlInutilizado(null);
495
        }
496 7
        if (isset($ajuste['pasta_xml_cancelado'])) {
497 1
            $this->setPastaXmlCancelado($ajuste['pasta_xml_cancelado']);
498 1
        } else {
499 7
            $this->setPastaXmlCancelado(null);
500
        }
501 7
        if (isset($ajuste['pasta_xml_pendente'])) {
502 1
            $this->setPastaXmlPendente($ajuste['pasta_xml_pendente']);
503 1
        } else {
504 7
            $this->setPastaXmlPendente(null);
505
        }
506 7
        if (isset($ajuste['pasta_xml_denegado'])) {
507 1
            $this->setPastaXmlDenegado($ajuste['pasta_xml_denegado']);
508 1
        } else {
509 7
            $this->setPastaXmlDenegado(null);
510
        }
511 7
        if (isset($ajuste['pasta_xml_rejeitado'])) {
512 1
            $this->setPastaXmlRejeitado($ajuste['pasta_xml_rejeitado']);
513 1
        } else {
514 7
            $this->setPastaXmlRejeitado(null);
515
        }
516 7
        if (isset($ajuste['pasta_xml_autorizado'])) {
517 1
            $this->setPastaXmlAutorizado($ajuste['pasta_xml_autorizado']);
518 1
        } else {
519 7
            $this->setPastaXmlAutorizado(null);
520
        }
521 7
        if (isset($ajuste['pasta_xml_processamento'])) {
522 1
            $this->setPastaXmlProcessamento($ajuste['pasta_xml_processamento']);
523 1
        } else {
524 7
            $this->setPastaXmlProcessamento(null);
525
        }
526 7
        if (isset($ajuste['pasta_xml_assinado'])) {
527 1
            $this->setPastaXmlAssinado($ajuste['pasta_xml_assinado']);
528 1
        } else {
529 7
            $this->setPastaXmlAssinado(null);
530
        }
531 7
        return $this;
532
    }
533
}
534