Completed
Push — master ( db74f7...065741 )
by Roberto
07:09 queued 04:22
created

Tools::sefazCartaCorrecao()   B

Complexity

Conditions 8
Paths 3

Size

Total Lines 57
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 0
cts 51
cp 0
rs 7.2648
c 0
b 0
f 0
cc 8
eloc 46
nc 3
nop 10
crap 72

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace NFePHP\CTe;
4
5
/**
6
 * Classe principal para a comunicação com a SEFAZ
7
 *
8
 * @category  Library
9
 * @package   nfephp-org/sped-cte
10
 * @copyright 2009-2016 NFePHP
11
 * @license   http://www.gnu.org/licenses/lesser.html LGPL v3
12
 * @link      http://github.com/nfephp-org/sped-cte for the canonical source repository
13
 * @author    Roberto L. Machado <linux.rlm at gmail dot com>
14
 *
15
 *        CONTRIBUIDORES (em ordem alfabetica):
16
 *
17
 *          Maison K. Sakamoto <maison.sakamoto at gmail do com>
18
 */
19
20
//use NFePHP\Common\Base\BaseTools;
21
use NFePHP\CTe\BaseTools;
22
use NFePHP\Common\LotNumber\LotNumber;
23
use NFePHP\Common\Strings\Strings;
24
use NFePHP\Common\Files;
25
use NFePHP\Common\Exception;
26
use NFePHP\CTe\Auxiliar\Response;
27
use NFePHP\CTe\Auxiliar\IdentifyCTe;
28
use NFePHP\Common\Dom\ValidXsd;
29
30
if (!defined('NFEPHP_ROOT')) {
31
    define('NFEPHP_ROOT', dirname(dirname(__FILE__)));
32
}
33
34
class Tools extends BaseTools
35
{
36
    /**
37
     * urlPortal
38
     * Instância do WebService
39
     * @var string
40
     */
41
    protected $urlPortal = 'http://www.portalfiscal.inf.br/cte';
42
43
    /**
44
     * errrors
45
     * @var string
46
     */
47
    public $erros = array();
48
    
49
    protected $modelo = '57';
50
    
51
    public function printCTe()
52
    {
53
    }
54
55
    public function mailCTe()
56
    {
57
    }
58
59
    /**
60
     * assina
61
     * @param string $xml
62
     * @param boolean $saveFile
63
     * @return string
64
     * @throws Exception\RuntimeException
65
     */
66
    public function assina($xml = '', $saveFile = false)
67
    {
68
        return $this->assinaDoc($xml, 'cte', 'infCte', $saveFile);
69
    }
70
71
    public function sefazEnvia(
72
        $aXml,
73
        $tpAmb = '2',
74
        $idLote = '',
75
        &$aRetorno = array(),
76
        $indSinc = 0,
0 ignored issues
show
Unused Code introduced by
The parameter $indSinc is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
77
        $compactarZip = false
0 ignored issues
show
Unused Code introduced by
The parameter $compactarZip is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
78
    ) {
79
        $sxml = $aXml;
80
        if (empty($aXml)) {
81
            $msg = "Pelo menos uma NFe deve ser informada.";
82
            throw new Exception\InvalidArgumentException($msg);
83
        }
84
        if (is_array($aXml)) {
85
            if (count($aXml) > 1) {
86
                //multiplas cte, não pode ser sincrono
87
                $indSinc = 0;
0 ignored issues
show
Unused Code introduced by
$indSinc 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...
88
            }
89
            $sxml = implode("", $sxml);
90
        }
91
        $sxml = preg_replace("/<\?xml.*\?>/", "", $sxml);
92
        $siglaUF = $this->aConfig['siglaUF'];
93
        
94
        if ($tpAmb == '') {
95
            $tpAmb = $this->aConfig['tpAmb'];
96
        }
97
        if ($idLote == '') {
98
            $idLote = LotNumber::geraNumLote(15);
99
        }
100
        //carrega serviço
101
        $servico = 'CteRecepcao';
102
        $this->zLoadServico(
103
            'cte',
104
            $servico,
105
            $siglaUF,
106
            $tpAmb
107
        );
108
        
109
        if ($this->urlService == '') {
110
            $msg = "O envio de lote não está disponível na SEFAZ $siglaUF!!!";
111
            throw new Exception\RuntimeException($msg);
112
        }
113
        
114
        // Montagem dos dados da mensagem SOAP
115
        $dados = "<cteDadosMsg xmlns=\"$this->urlNamespace\">"
116
            . "<enviCTe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
117
            . "<idLote>$idLote</idLote>"
118
            . "$sxml"
119
            . "</enviCTe>"
120
            . "</cteDadosMsg>";
121
        
122
        // Envia dados via SOAP
123
        $retorno = $this->oSoap->send(
124
            $this->urlService,
125
            $this->urlNamespace,
126
            $this->urlHeader,
127
            $dados,
128
            $this->urlMethod
129
        );
130
131
//        if ($compactarZip) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
132
//            $gzdata = base64_encode(gzencode($cons, 9, FORCE_GZIP));
133
//            $body = "<cteDadosMsgZip xmlns=\"$this->urlNamespace\">$gzdata</cteDadosMsgZip>";
134
//            $method = $this->urlMethod."Zip";
135
//        }
136
137
        $lastMsg = $this->oSoap->lastMsg;
138
        $this->soapDebug = $this->oSoap->soapDebug;
0 ignored issues
show
Bug introduced by
The property soapDebug does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
139
        //salva mensagens
140
        $filename = "$idLote-enviCTe.xml";
141
        $this->zGravaFile('cte', $tpAmb, $filename, $lastMsg);
142
        $filename = "$idLote-retEnviCTe.xml";
143
        $this->zGravaFile('cte', $tpAmb, $filename, $retorno);
144
        //tratar dados de retorno
145
146
        $aRetorno = Response::readReturnSefaz($servico, $retorno);
147
        //caso o envio seja recebido com sucesso mover a NFe da pasta
148
        //das assinadas para a pasta das enviadas
149
        return (string) $retorno;
150
    }
151
152
    public function sefazConsultaRecibo($recibo = '', $tpAmb = '2', &$aRetorno = array())
153
    {
154
        if ($recibo == '') {
155
            $msg = "Deve ser informado um recibo.";
156
            throw new Exception\InvalidArgumentException($msg);
157
        }
158
        if ($tpAmb == '') {
159
            $tpAmb = $this->aConfig['tpAmb'];
160
        }
161
        $siglaUF = $this->aConfig['siglaUF'];
162
        //carrega serviço
163
        $servico = 'CteRetRecepcao';
164
        $this->zLoadServico(
165
            'cte',
166
            $servico,
167
            $siglaUF,
168
            $tpAmb
169
        );
170
        if ($this->urlService == '') {
171
            $msg = "A consulta de NFe não está disponível na SEFAZ $siglaUF!!!";
172
            throw new Exception\RuntimeException($msg);
173
        }
174
        $cons = "<consReciCTe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
175
            . "<tpAmb>$tpAmb</tpAmb>"
176
            . "<nRec>$recibo</nRec>"
177
            . "</consReciCTe>";
178
        //validar mensagem com xsd
179
        //if (! $this->validarXml($cons)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
180
        //    $msg = 'Falha na validação. '.$this->error;
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
181
        //    throw new Exception\RuntimeException($msg);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
182
        //}
183
        //montagem dos dados da mensagem SOAP
184
        $body = "<cteDadosMsg xmlns=\"$this->urlNamespace\">$cons</cteDadosMsg>";
185
             
186
        //envia a solicitação via SOAP
187
        $retorno = $this->oSoap->send(
188
            $this->urlService,
189
            $this->urlNamespace,
190
            $this->urlHeader,
191
            $body,
192
            $this->urlMethod
193
        );
194
        $lastMsg = $this->oSoap->lastMsg;
195
        $this->soapDebug = $this->oSoap->soapDebug;
196
        //salva mensagens
197
        $filename = "$recibo-consReciCTe.xml";
198
        $this->zGravaFile('cte', $tpAmb, $filename, $lastMsg);
199
        $filename = "$recibo-retConsReciCTe.xml";
200
        $this->zGravaFile('cte', $tpAmb, $filename, $retorno);
201
        //tratar dados de retorno
202
        $aRetorno = Response::readReturnSefaz($servico, $retorno);
203
        //podem ser retornados nenhum, um ou vários protocolos
204
        //caso existam protocolos protocolar as NFe e movelas-las para a
205
        //pasta enviadas/aprovadas/anomes
206
        return (string) $retorno;
207
    }
208
209
    public function sefazConsultaChave($chave = '', $tpAmb = '2', &$aRetorno = array())
210
    {
211
        $chNFe = preg_replace('/[^0-9]/', '', $chave);
212
        if (strlen($chNFe) != 44) {
213
            $msg = "Uma chave de 44 dígitos da NFe deve ser passada.";
214
            throw new Exception\InvalidArgumentException($msg);
215
        }
216
        if ($tpAmb == '') {
217
            $tpAmb = $this->aConfig['tpAmb'];
218
        }
219
        $cUF = substr($chNFe, 0, 2);
220
        $siglaUF = $this->zGetSigla($cUF);
221
        //carrega serviço
222
        $servico = 'CteConsultaProtocolo';
223
        $this->zLoadServico(
224
            'cte',
225
            $servico,
226
            $siglaUF,
227
            $tpAmb
228
        );
229
        if ($this->urlService == '') {
230
            $msg = "A consulta de NFe não está disponível na SEFAZ $siglaUF!!!";
231
            throw new Exception\RuntimeException($msg);
232
        }
233
        $cons = "<consSitCTe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
234
            . "<tpAmb>$tpAmb</tpAmb>"
235
            . "<xServ>CONSULTAR</xServ>"
236
            . "<chCTe>$chNFe</chCTe>"
237
            . "</consSitCTe>";
238
        //validar mensagem com xsd
239
        //if (! $this->validarXml($cons)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
240
        //    $msg = 'Falha na validação. '.$this->error;
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
241
        //    throw new Exception\RuntimeException($msg);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
242
        //}
243
        //montagem dos dados da mensagem SOAP
244
        $body = "<cteDadosMsg xmlns=\"$this->urlNamespace\">$cons</cteDadosMsg>";
245
        //envia a solicitação via SOAP
246
        $retorno = $this->oSoap->send(
247
            $this->urlService,
248
            $this->urlNamespace,
249
            $this->urlHeader,
250
            $body,
251
            $this->urlMethod
252
        );
253
        $lastMsg = $this->oSoap->lastMsg;
254
        $this->soapDebug = $this->oSoap->soapDebug;
255
        //salva mensagens
256
        $filename = "$chNFe-consSitCTe.xml";
257
        $this->zGravaFile('cte', $tpAmb, $filename, $lastMsg);
258
        $filename = "$chNFe-retConsSitNFe.xml";
259
        $this->zGravaFile('cte', $tpAmb, $filename, $retorno);
260
        //tratar dados de retorno
261
        $aRetorno = Response::readReturnSefaz($servico, $retorno);
262
        return (string) $retorno;
263
    }
264
265
    public function sefazStatus($siglaUF = '', $tpAmb = '2', &$aRetorno = array())
266
    {
267
        if ($tpAmb == '') {
268
            $tpAmb = $this->aConfig['tpAmb'];
269
        }
270
        if ($siglaUF == '') {
271
            $siglaUF = $this->aConfig['siglaUF'];
272
        }
273
        //carrega serviço
274
        $servico = 'CteStatusServico';
275
        $this->zLoadServico(
276
            'cte',
277
            $servico,
278
            $siglaUF,
279
            $tpAmb
280
        );
281
        if ($this->urlService == '') {
282
            $msg = "O status não está disponível na SEFAZ $siglaUF!!!";
283
            throw new Exception\RuntimeException($msg);
284
        }
285
        $cons = "<consStatServCte xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
286
            . "<tpAmb>$tpAmb</tpAmb>"
287
            . "<xServ>STATUS</xServ></consStatServCte>";
288
        //valida mensagem com xsd
289
        //validar mensagem com xsd
290
        //if (! $this->validarXml($cons)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
291
        //    $msg = 'Falha na validação. '.$this->error;
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
292
        //    throw new Exception\RuntimeException($msg);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
293
        //}
294
        //montagem dos dados da mensagem SOAP
295
        $body = "<cteDadosMsg xmlns=\"$this->urlNamespace\">$cons</cteDadosMsg>";
296
        //consome o webservice e verifica o retorno do SOAP
297
        $retorno = $this->oSoap->send(
298
            $this->urlService,
299
            $this->urlNamespace,
300
            $this->urlHeader,
301
            $body,
302
            $this->urlMethod
303
        );
304
        $lastMsg = $this->oSoap->lastMsg;
305
        $this->soapDebug = $this->oSoap->soapDebug;
306
        $datahora = date('Ymd_His');
307
        $filename = $siglaUF."_"."$datahora-consStatServCte.xml";
308
        $this->zGravaFile('cte', $tpAmb, $filename, $lastMsg);
309
        $filename = $siglaUF."_"."$datahora-retConsStatServCte.xml";
310
        $this->zGravaFile('cte', $tpAmb, $filename, $retorno);
311
        //tratar dados de retorno
312
        $aRetorno = Response::readReturnSefaz($servico, $retorno);
313
        return (string) $retorno;
314
    }
315
316
    public function sefazInutiliza(
317
        $nSerie = '1',
318
        $nIni = '',
319
        $nFin = '',
320
        $xJust = '',
321
        $tpAmb = '2',
322
        &$aRetorno = array(),
323
        $salvarMensagens = true
324
    ) {
325
        $nSerie = (integer) $nSerie;
326
        $nIni = (integer) $nIni;
327
        $nFin = (integer) $nFin;
328
        $xJust = Strings::cleanString($xJust);
329
        $this->zValidParamInut($xJust, $nSerie, $nIni, $nFin);
330
        if ($tpAmb == '') {
331
            $tpAmb = $this->aConfig['tpAmb'];
332
        }
333
        
334
        // Identificação do serviço
335
        $servico = 'CteInutilizacao';
0 ignored issues
show
Unused Code introduced by
$servico 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...
336
        //monta serviço
337
        $siglaUF = $this->aConfig['siglaUF'];
338
        //carrega serviço
339
        $servico = 'CteInutilizacao';
340
        $this->zLoadServico(
341
            'cte',
342
            $servico,
343
            $siglaUF,
344
            $tpAmb
345
        );
346
347
        if ($this->urlService == '') {
348
            $msg = "A inutilização não está disponível na SEFAZ $siglaUF!!!";
349
            throw new Exception\RuntimeException($msg);
350
        }
351
352
        //montagem dos dados da mensagem SOAP
353
        $cnpj = $this->aConfig['cnpj'];
354
        $sAno = (string) date('y');
355
        $sSerie = str_pad($nSerie, 3, '0', STR_PAD_LEFT);
356
        $sInicio = str_pad($nIni, 9, '0', STR_PAD_LEFT);
357
        $sFinal = str_pad($nFin, 9, '0', STR_PAD_LEFT);
358
359
        //limpa os caracteres indesejados da justificativa
360
        $xJust = Strings::cleanString($xJust);
361
362
        // Identificador da TAG a ser assinada formada com Código da UF +
363
        // precedida do literal “ID”
364
        // 41 posições
365
        $id = 'ID'.$this->urlcUF.$cnpj.'57'.$sSerie.$sInicio.$sFinal;
366
367
        // Montagem do corpo da mensagem
368
        $dXML = "<inutCTe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
369
            ."<infInut Id=\"$id\">"
370
            ."<tpAmb>$tpAmb</tpAmb>"
371
            ."<xServ>INUTILIZAR</xServ>"
372
            ."<cUF>$this->urlcUF</cUF>"
373
            ."<ano>$sAno</ano>"
374
            ."<CNPJ>$cnpj</CNPJ>"
375
            ."<mod>57</mod>"
376
            ."<serie>$nSerie</serie>"
377
            ."<nCTIni>$nIni</nCTIni>"
378
            ."<nCTFin>$nFin</nCTFin>"
379
            ."<xJust>$xJust</xJust>"
380
            ."</infInut></inutCTe>";
381
382
        //assina a solicitação de inutilização
383
        $signedMsg = $this->oCertificate->signXML($dXML, 'infInut');
384
        $signedMsg = Strings::clearXml($signedMsg, true);
385
386
        $body = "<cteDadosMsg xmlns=\"$this->urlNamespace\">$signedMsg</cteDadosMsg>";
387
388
        //envia a solicitação via SOAP
389
        $retorno = $this->oSoap->send(
390
            $this->urlService,
391
            $this->urlNamespace,
392
            $this->urlHeader,
393
            $body,
394
            $this->urlMethod
395
        );
396
        $lastMsg = $this->oSoap->lastMsg;
397
        $this->soapDebug = $this->oSoap->soapDebug;
398
399
        //salva mensagens
400
        if ($salvarMensagens) {
401
            $filename = "$sAno-$this->modelo-$sSerie-".$sInicio."_".$sFinal."-inutCTe.xml";
402
            $this->zGravaFile('cte', $tpAmb, $filename, $lastMsg);
403
            $filename = "$sAno-$this->modelo-$sSerie-".$sInicio."_".$sFinal."-retInutCTe.xml";
404
            $this->zGravaFile('cte', $tpAmb, $filename, $retorno);
405
        }
406
407
        //tratar dados de retorno
408
        $aRetorno = Response::readReturnSefaz($servico, $retorno);
409
        if ($aRetorno['cStat'] == '102') {
410
            $retorno = $this->zAddProtMsg('ProcInutCTe', 'inutCTe', $signedMsg, 'retInutCTe', $retorno);
411
            if ($salvarMensagens) {
412
                $filename = "$sAno-$this->modelo-$sSerie-".$sInicio."_".$sFinal."-procInutCTe.xml";
413
                $this->zGravaFile('cte', $tpAmb, $filename, $retorno, 'inutilizadas');
414
            }
415
        }
416
417
        return (string) $retorno;
418
    }
419
420
    public function sefazCancela($chCTe = '', $tpAmb = '2', $xJust = '', $nProt = '', &$aRetorno = array())
421
    {
422
        $chCTe = preg_replace('/[^0-9]/', '', $chCTe);
423
        $nProt = preg_replace('/[^0-9]/', '', $nProt);
424
        $xJust = Strings::cleanString($xJust);
425
        //validação dos dados de entrada
426
        if (strlen($chCTe) != 44) {
427
            $msg = "Uma chave de CTe válida não foi passada como parâmetro $chCTe.";
428
            throw new Exception\InvalidArgumentException($msg);
429
        }
430
        if ($nProt == '') {
431
            $msg = "Não foi passado o numero do protocolo!!";
432
            throw new Exception\InvalidArgumentException($msg);
433
        }
434
        if (strlen($xJust) < 15 || strlen($xJust) > 255) {
435
            $msg = "A justificativa deve ter pelo menos 15 digitos e no máximo 255!!";
436
            throw new Exception\InvalidArgumentException($msg);
437
        }
438
        $siglaUF = $this->zGetSigla(substr($chCTe, 0, 2));
439
440
        //estabelece o codigo do tipo de evento CANCELAMENTO
441
        $tpEvento = '110111';
442
        $descEvento = 'Cancelamento';
443
        $nSeqEvento = 1;
444
        //monta mensagem
445
        $tagAdic = "<evCancCTe>"
446
            . "<descEvento>$descEvento</descEvento>"
447
            . "<nProt>$nProt</nProt>"
448
            . "<xJust>$xJust</xJust>"
449
            . "</evCancCTe>";
450
        $retorno = $this->zSefazEvento($siglaUF, $chCTe, $tpAmb, $tpEvento, $nSeqEvento, $tagAdic);
451
        $aRetorno = $this->aLastRetEvent;
0 ignored issues
show
Bug introduced by
The property aLastRetEvent does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
452
        return $retorno;
453
    }
454
455
    public function enviaMail($pathXml = '', $aMails = array(), $templateFile = '', $comPdf = false, $pathPdf = '')
0 ignored issues
show
Unused Code introduced by
The parameter $templateFile is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
456
    {
457
        $mail = new Mail($this->aMailConf);
458
        // Se não for informado o caminho do PDF, monta um através do XML
459
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
460
        if ($comPdf && $this->modelo == '55' && $pathPdf == '') {
461
            $docxml = Files\FilesFolders::readFile($pathXml);
462
            $danfe = new Extras\Danfe($docxml, 'P', 'A4', $this->aDocFormat['pathLogoFile'], 'I', '');
463
            $id = $danfe->montaDANFE();
464
            $pathPdf = $this->aConfig['pathNFeFiles']
465
                . DIRECTORY_SEPARATOR
466
                . $this->ambiente
467
                . DIRECTORY_SEPARATOR
468
                . 'pdf'
469
                . DIRECTORY_SEPARATOR
470
                . $id . '-danfe.pdf';
471
            $pdf = $danfe->printDANFE($pathPdf, 'F');
472
        }
473
         *
474
         */
475
        if ($mail->envia($pathXml, $aMails, $comPdf, $pathPdf) === false) {
476
            throw new Exception\RuntimeException('Email não enviado. '.$mail->error);
477
        }
478
        return true;
479
    }
480
481
    /**
482
     * zSefazEvento
483
     * @param string $siglaUF
484
     * @param string $chCTe
485
     * @param string $tpAmb
486
     * @param string $tpEvento
487
     * @param string $nSeqEvento
488
     * @param string $tagAdic
489
     * @return string
490
     * @throws Exception\RuntimeException
491
     * @internal function zLoadServico (Common\Base\BaseTools)
492
     */
493
    protected function zSefazEvento(
494
        $siglaUF = '',
495
        $chCTe = '',
496
        $tpAmb = '2',
497
        $tpEvento = '',
498
        $nSeqEvento = '1',
499
        $tagAdic = ''
500
    ) {
501
        if ($tpAmb == '') {
502
            $tpAmb = $this->aConfig['tpAmb'];
503
        }
504
        //carrega serviço
505
        $servico = 'CteRecepcaoEvento';
506
        $this->zLoadServico(
507
            'cte',
508
            $servico,
509
            $siglaUF,
510
            $tpAmb
511
        );
512
        if ($this->urlService == '') {
513
            $msg = "A recepção de eventos não está disponível na SEFAZ $siglaUF!!!";
514
            throw new Exception\RuntimeException($msg);
515
        }
516
        $aRet = $this->zTpEv($tpEvento);
517
        $aliasEvento = $aRet['alias'];
518
        $descEvento = $aRet['desc'];
0 ignored issues
show
Unused Code introduced by
$descEvento 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...
519
        $cnpj = $this->aConfig['cnpj'];
520
        $dhEvento = (string) str_replace(' ', 'T', date('Y-m-d H:i:s'));
521
//        $dhEvento = (string) str_replace(' ', 'T', date('Y-m-d H:i:sP'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
522
        $sSeqEvento = str_pad($nSeqEvento, 2, "0", STR_PAD_LEFT);
523
        $eventId = "ID".$tpEvento.$chCTe.$sSeqEvento;
524
        $cOrgao = $this->urlcUF;
525
        if ($siglaUF == 'AN') {
526
            $cOrgao = '91';
527
        }
528
        $mensagem = "<infEvento Id=\"$eventId\">"
529
            . "<cOrgao>$cOrgao</cOrgao>"
530
            . "<tpAmb>$tpAmb</tpAmb>"
531
            . "<CNPJ>$cnpj</CNPJ>"
532
            . "<chCTe>$chCTe</chCTe>"
533
            . "<dhEvento>$dhEvento</dhEvento>"
534
            . "<tpEvento>$tpEvento</tpEvento>"
535
            . "<nSeqEvento>$nSeqEvento</nSeqEvento>"
536
            //. "<nSeqEvento>$sSeqEvento</nSeqEvento>"
537
            . "<detEvento versaoEvento=\"$this->urlVersion\">"
538
            . "$tagAdic"
539
            . "</detEvento>"
540
            . "</infEvento>";
541
542
        $cons = "<eventoCTe xmlns=\"$this->urlPortal\" versao=\"$this->urlVersion\">"
543
            . "$mensagem"
544
            . "</eventoCTe>";
545
546
        $signedMsg = $this->oCertificate->signXML($cons, 'infEvento');
547
        $signedMsg = preg_replace("/<\?xml.*\?>/", "", $signedMsg);
548
549
        //$signedMsg = Strings::clearXml($signedMsg, true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
550
551
//        if (! $this->zValidMessage($signedMsg, 'cte', 'envEvento', $this->urlVersion)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
552
//            $msg = 'Falha na validação. '.$this->error;
553
//            throw new Exception\RuntimeException($msg);
554
//        }
555
556
557
//        $filename = "../cancelamento.xml";
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
558
//        $xml = file_get_contents($filename);
559
560
561
        //$body = "<cteDadosMsg xmlns=\"$this->urlNamespace\">$xml</cteDadosMsg>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
562
        $body = "<cteDadosMsg xmlns=\"$this->urlNamespace\">$signedMsg</cteDadosMsg>";
563
564
        $retorno = $this->oSoap->send(
565
            $this->urlService,
566
            $this->urlNamespace,
567
            $this->urlHeader,
568
            $body,
569
            $this->urlMethod
570
        );
571
        $lastMsg = $this->oSoap->lastMsg;
572
        $this->soapDebug = $this->oSoap->soapDebug;
573
        //salva mensagens
574
        $filename = "$chCTe-$aliasEvento-envEvento.xml";
575
        $this->zGravaFile('cte', $tpAmb, $filename, $lastMsg);
576
        $filename = "$chCTe-$aliasEvento-retEnvEvento.xml";
577
        $this->zGravaFile('cte', $tpAmb, $filename, $retorno);
578
        //tratar dados de retorno
579
        $this->aLastRetEvent = Response::readReturnSefaz($servico, $retorno);
580
        if ($this->aLastRetEvent['cStat'] == '128') {
581
            if ($this->aLastRetEvent['evento'][0]['cStat'] == '135' ||
582
                $this->aLastRetEvent['evento'][0]['cStat'] == '136' ||
583
                $this->aLastRetEvent['evento'][0]['cStat'] == '155'
584
            ) {
585
                $pasta = 'eventos'; //default
586
                if ($aliasEvento == 'CanCTe') {
587
                    $pasta = 'canceladas';
588
                    $filename = "$chCTe-$aliasEvento-procEvento.xml";
589
                } elseif ($aliasEvento == 'CCe') {
590
                    $pasta = 'cartacorrecao';
591
                    $filename = "$chCTe-$aliasEvento-$nSeqEvento-procEvento.xml";
592
                }
593
                $retorno = $this->zAddProtMsg('procEventoCTe', 'evento', $signedMsg, 'retEvento', $retorno);
594
                $this->zGravaFile('cte', $tpAmb, $filename, $retorno, $pasta);
595
            }
596
        }
597
        return (string) $retorno;
598
    }
599
600
    /**
601
     * zAddProtMsg
602
     *
603
     * @param  string $tagproc
604
     * @param  string $tagmsg
605
     * @param  string $xmlmsg
606
     * @param  string $tagretorno
607
     * @param  string $xmlretorno
608
     * @return string
609
     */
610
    protected function zAddProtMsg($tagproc, $tagmsg, $xmlmsg, $tagretorno, $xmlretorno)
611
    {
612
        $doc = new Dom();
613
        $doc->loadXMLString($xmlmsg);
614
        $nodedoc = $doc->getNode($tagmsg, 0);
615
        $procver = $nodedoc->getAttribute("versao");
616
        $procns = $nodedoc->getAttribute("xmlns");
617
618
        $doc1 = new Dom();
619
        $doc1->loadXMLString($xmlretorno);
620
        $nodedoc1 = $doc1->getNode($tagretorno, 0);
621
622
        $proc = new \DOMDocument('1.0', 'utf-8');
623
        $proc->formatOutput = false;
624
        $proc->preserveWhiteSpace = false;
625
        //cria a tag nfeProc
626
        $procNode = $proc->createElement($tagproc);
627
        $proc->appendChild($procNode);
628
        //estabele o atributo de versão
629
        $procNodeAtt1 = $procNode->appendChild($proc->createAttribute('versao'));
630
        $procNodeAtt1->appendChild($proc->createTextNode($procver));
631
        //estabelece o atributo xmlns
632
        $procNodeAtt2 = $procNode->appendChild($proc->createAttribute('xmlns'));
633
        $procNodeAtt2->appendChild($proc->createTextNode($procns));
634
        //inclui a tag inutNFe
635
        $node = $proc->importNode($nodedoc, true);
636
        $procNode->appendChild($node);
637
        //inclui a tag retInutNFe
638
        $node = $proc->importNode($nodedoc1, true);
639
        $procNode->appendChild($node);
640
        //salva o xml como string em uma variável
641
        $procXML = $proc->saveXML();
642
        //remove as informações indesejadas
643
        $procXML = Strings::clearProt($procXML);
644
        return $procXML;
645
    }
646
647
    /**
648
     * zTpEv
649
     * @param string $tpEvento
650
     * @return array
651
     * @throws Exception\RuntimeException
652
     */
653
    private function zTpEv($tpEvento = '')
654
    {
655
        //montagem dos dados da mensagem SOAP
656
        switch ($tpEvento) {
657
            case '110110':
658
                //CCe
659
                $aliasEvento = 'CCe';
660
                $descEvento = 'Carta de Correcao';
661
                break;
662
            case '110111':
663
                //cancelamento
664
                $aliasEvento = 'CancNFe';
665
                $descEvento = 'Cancelamento';
666
                break;
667
            case '110140':
668
                //EPEC
669
                //emissão em contingência EPEC
670
                $aliasEvento = 'EPEC';
671
                $descEvento = 'EPEC';
672
                break;
673
            case '111500':
674
            case '111501':
675
                //EPP
676
                //Pedido de prorrogação
677
                $aliasEvento = 'EPP';
678
                $descEvento = 'Pedido de Prorrogacao';
679
                break;
680
            case '111502':
681
            case '111503':
682
                //ECPP
683
                //Cancelamento do Pedido de prorrogação
684
                $aliasEvento = 'ECPP';
685
                $descEvento = 'Cancelamento de Pedido de Prorrogacao';
686
                break;
687
            case '210200':
688
                //Confirmacao da Operacao
689
                $aliasEvento = 'EvConfirma';
690
                $descEvento = 'Confirmacao da Operacao';
691
                break;
692
            case '210210':
693
                //Ciencia da Operacao
694
                $aliasEvento = 'EvCiencia';
695
                $descEvento = 'Ciencia da Operacao';
696
                break;
697
            case '210220':
698
                //Desconhecimento da Operacao
699
                $aliasEvento = 'EvDesconh';
700
                $descEvento = 'Desconhecimento da Operacao';
701
                break;
702
            case '210240':
703
                //Operacao não Realizada
704
                $aliasEvento = 'EvNaoRealizada';
705
                $descEvento = 'Operacao nao Realizada';
706
                break;
707
            default:
708
                $msg = "O código do tipo de evento informado não corresponde a "
709
                    . "nenhum evento estabelecido.";
710
                throw new Exception\RuntimeException($msg);
711
        }
712
        return array('alias' => $aliasEvento, 'desc' => $descEvento);
713
    }
714
715
    private function zValidParamInut($xJust, $nSerie, $nIni, $nFin)
716
    {
717
        $msg = '';
718
        $nL = strlen($xJust);
719
720
        // Valida dos dados de entrada
721
        if ($nIni == '' || $nFin == '' || $xJust == '') {
722
            $msg = "Não foi passado algum dos parametos necessários"
723
                    . "inicio=$nIni fim=$nFin justificativa=$xJust.";
724 View Code Duplication
        } elseif (strlen($nSerie) == 0 || strlen($nSerie) > 3) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
725
            $msg = "O campo serie está errado: $nSerie. Corrija e refaça o processo!!";
726
        } elseif (strlen($nIni) < 1 || strlen($nIni) > 9) {
727
            $msg = "O campo numero inicial está errado: $nIni. Corrija e refaça o processo!!";
728
        } elseif (strlen($nFin) < 1 || strlen($nFin) > 9) {
729
            $msg = "O campo numero final está errado: $nFin. Corrija e refaça o processo!!";
730
        } elseif ($nL < 15 || $nL > 255) {
731
            $msg = "A justificativa tem que ter entre 15 e 255 caracteres, encontrado $nL. "
732
                . "Corrija e refaça o processo!!";
733
        }
734
735
        if ($msg != '') {
736
            throw new Exception\InvalidArgumentException($msg);
737
        }
738
    }
739
740
    /**
741
     * validarXml
742
     * Valida qualquer xml do sistema NFe com seu xsd
743
     * NOTA: caso não exista um arquivo xsd apropriado retorna false
744
     * @param string $xml path ou conteudo do xml
745
     * @return boolean
746
     */
747
    public function validarXml($xml = '')
748
    {
749
        $aResp = array();
750
        $schem = IdentifyCTe::identificar($xml, $aResp);
751
        if ($schem == '') {
752
            return true;
753
        }
754
        $xsdFile = $aResp['Id'].'_v'.$aResp['versao'].'.xsd';
755
        $xsdPath = NFEPHP_ROOT.DIRECTORY_SEPARATOR .
756
            'schemas' .
757
            DIRECTORY_SEPARATOR .
758
            $this->aConfig['schemesCTe'] .
759
            DIRECTORY_SEPARATOR .
760
            $xsdFile;
761
        if (! is_file($xsdPath)) {
762
            $this->erros[] = "O arquivo XSD $xsdFile não foi localizado.";
763
            return false;
764
        }
765
        if (! ValidXsd::validar($aResp['xml'], $xsdPath)) {
766
            $this->erros[] = ValidXsd::$errors;
767
            return false;
768
        }
769
        return true;
770
    }
771
    
772
    public function sefazInutiliza(
773
        $nAno = '',
774
        $nSerie = '1',
775
        $nIni = '',
776
        $nFin = '',
777
        $xJust = '',
778
        $tpAmb = '2',
779
        &$aRetorno = array()
780
    ) {
781
        // Variavel de retorno do metodo
782
        $aRetorno = array (
783
            'bStat' => false,
784
            'cStat' => '',
785
            'xMotivo' => '',
786
            'dhRecbto' => '',
787
            'nProt' => '');
788
        // Valida dos dados de entrada
789
        if ($nAno == '' || $nIni == '' || $nFin == '' || $xJust == '') {
790
            $this->errStatus = true;
0 ignored issues
show
Bug introduced by
The property errStatus does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
791
            $this->errMsg = "Não foi passado algum dos parametos necessários "
0 ignored issues
show
Bug introduced by
The property errMsg does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
792
                    . "ANO=$nAno inicio=$nIni fim=$nFin justificativa=$xJust.";
793
            return false;
794
        }
795
        
796
        $siglaUF = $this->aConfig['siglaUF'];
797
        $cnpj = $this->aConfig['cnpj'];
798
        $this->urlOperation = 'CteInutilizacao';
799
        
800
        $this->zLoadServico('cte', 'CteInutilizacao', $siglaUF, $tpAmb);
801
        
802
        
803
        if ($this->urlService == '') {
804
            $msg = "A recepção de eventos não está disponível na SEFAZ $siglaUF!!!";
805
            throw new Exception\RuntimeException($msg);
806
        }
807
        if (strlen($nAno) != 2) {
808
            $msg = "Informe o ano com 2 digitos";
809
            throw new Exception\InvalidArgumentException($msg);
810
        }
811 View Code Duplication
        if (strlen($nSerie) == 0 || strlen($nSerie) > 3) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
812
            $msg = "O campo serie está errado: $nSerie. usar 3 digitos";
813
            throw new Exception\InvalidArgumentException($msg);
814
        }
815 View Code Duplication
        if (strlen($nIni) < 1 || strlen($nIni) > 9) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
816
            $msg = "O campo numero inicial está errado: $nIni. Corrija e refaça o processo!!";
817
            throw new Exception\InvalidArgumentException($msg);
818
        }
819 View Code Duplication
        if (strlen($nFin) < 1 || strlen($nFin) > 9) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
820
            $msg = "O campo numero final está errado: $nFin. Corrija e refaça o processo!!";
821
            throw new Exception\InvalidArgumentException($msg);
822
        }
823
        if (strlen($xJust) < 15 || strlen($xJust) > 255) {
824
            $msg = "O campo justificativa deve ter no minimo 15 chars e no maximo 255, verifique!";
825
            throw new Exception\InvalidArgumentException($msg);
826
        }
827
        
828
        // Identificador da TAG a ser assinada formada com Código da UF +
829
        // Ano (2 posições) + CNPJ + modelo + série + nro inicial e nro final
830
        // precedida do literal “ID”
831
        // 43 posições
832
        //     2      4       6       20      22    25       34      43
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
833
        //     2      2       2       14       2     3        9       9
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
834
        $id = 'ID' . $this->urlcUF .  $cnpj . '57' .
835
                str_pad($nSerie, 3, '0', STR_PAD_LEFT) .
836
                str_pad($nIni, 9, '0', STR_PAD_LEFT) .
837
                str_pad($nFin, 9, '0', STR_PAD_LEFT);
838
        
839
        // Montagem do corpo da mensagem
840
        $dXML = '<inutCTe xmlns="' . $this->urlPortal . '" versao="' . $this->urlVersion . '">';
841
        $dXML .= '<infInut Id="' . $id . '">';
842
        $dXML .= '<tpAmb>' . $tpAmb . '</tpAmb>';
843
        $dXML .= '<xServ>INUTILIZAR</xServ>';
844
        $dXML .= '<cUF>' . $this->urlcUF . '</cUF>';
845
        $dXML .= '<ano>' . $nAno . '</ano>';
846
        $dXML .= '<CNPJ>' . $cnpj . '</CNPJ>';
847
        $dXML .= '<mod>57</mod>';
848
        $dXML .= '<serie>' . $nSerie . '</serie>';
849
        $dXML .= '<nCTIni>' . $nIni . '</nCTIni>';
850
        $dXML .= '<nCTFin>' . $nFin . '</nCTFin>';
851
        $dXML .= '<xJust>' . $xJust . '</xJust>';
852
        $dXML .= '</infInut>';
853
        $dXML .= '</inutCTe>';
854
        
855
        // Assina a lsolicitação de inutilização
856
        $dXML = $this->oCertificate->signXML($dXML, 'infInut');
857
        $dados = '<cteDadosMsg xmlns="' . $this->urlNamespace . '">' . $dXML . '</cteDadosMsg>';
858
    
859
        // Remove as tags xml que porventura tenham sido inclusas
860
        $dados = str_replace('<?xml version="1.0"?>', '', $dados);
861
        $dados = str_replace('<?xml version="1.0" encoding="utf-8"?>', '', $dados);
862
        $dados = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $dados);
863
        $dados = str_replace(array("\r","\n","\s"), "", $dados);
864
        
865
        // Envia a solicitação via SOAP
866
        $retorno = $this->oSoap->send(
867
            $this->urlService,
868
            $this->urlNamespace,
869
            $this->urlHeader,
870
            $dados,
871
            $this->urlMethod
872
        );
873
        // Verifica o retorno
874
        $lastMsg = $this->oSoap->lastMsg;
0 ignored issues
show
Unused Code introduced by
$lastMsg 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...
875
        $this->soapDebug = $this->oSoap->soapDebug;
876
        $aRetorno = Response::readReturnSefaz($this->urlOperation, $retorno);
877
        return (string) $retorno;
878
    }
879
    
880
    public function sefazCartaCorrecao(
881
        $siglaUF = '',
882
        $tpAmb = '2',
883
        $cnpj = '',
884
        $chave = '',
885
        $nSeqEvento = '1',
886
        $grupoAlterado = '',
887
        $campoAlterado = '',
888
        $valorAlterado = '',
889
        $nroItemAlterado = '01',
890
        &$aRetorno = array()
891
    ) {
892
        $chCTe = preg_replace('/[^0-9]/', '', $chave);
893
        
894
        //validação dos dados de entrada
895
        if (strlen($chCTe) != 44) {
896
            $msg = "Uma chave de CTe válida não foi passada como parâmetro $chCTe.";
897
            throw new Exception\InvalidArgumentException($msg);
898
        }
899
        if ($siglaUF == '' || $cnpj == '' || $chave == '' ||
900
            $grupoAlterado == '' || $campoAlterado == '' || $valorAlterado == ''
901
        ) {
902
            $msg = "Preencha os campos obrigatórios!";
903
            throw new Exception\InvalidArgumentException($msg);
904
        }
905
        
906
        //estabelece o codigo do tipo de evento CARTA DE CORRECAO
907
        $tpEvento = '110110';
908
        $descEvento = 'Carta de Correcao';
909
        
910
        //monta mensagem
911
        $tagAdic =
912
            "<evCCeCTe>"
913
                . "<descEvento>$descEvento</descEvento>"
914
                . "<infCorrecao>"
915
                    . "<grupoAlterado>$grupoAlterado</grupoAlterado>"
916
                    . "<campoAlterado>$campoAlterado</campoAlterado>"
917
                    . "<valorAlterado>$valorAlterado</valorAlterado>"
918
                    . "<nroItemAlterado>$nroItemAlterado</nroItemAlterado>"
919
                . "</infCorrecao>"
920
                . "<xCondUso>"
921
                    . "A Carta de Correcao e disciplinada pelo Art. 58-B do "
922
                    . "CONVENIO/SINIEF 06/89: Fica permitida a utilizacao de carta de "
923
                    . "correcao, para regularizacao de erro ocorrido na emissao de "
924
                    . "documentos fiscais relativos a prestacao de servico de transporte, "
925
                    . "desde que o erro nao esteja relacionado com: I - as variaveis que "
926
                    . "determinam o valor do imposto tais como: base de calculo, "
927
                    . "aliquota, diferenca de preco, quantidade, valor da prestacao;II - "
928
                    . "a correcao de dados cadastrais que implique mudanca do emitente, "
929
                    . "tomador, remetente ou do destinatario;III - a data de emissao ou "
930
                    . "de saida."
931
                . "</xCondUso>"
932
            ."</evCCeCTe>";
933
        $retorno = $this->zSefazEvento($siglaUF, $chCTe, $tpAmb, $tpEvento, $nSeqEvento, $tagAdic);
934
        $aRetorno = $this->aLastRetEvent;
935
        return $retorno;
936
    }
937
}
938