Completed
Push — master ( 7911f9...2e1b9d )
by Roberto
10:30
created

Tools::batchBuilder()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 45
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 0
cts 29
cp 0
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 34
nc 8
nop 1
crap 56
1
<?php
2
3
namespace NFePHP\eFinanc;
4
5
/**
6
 * Class Tools, performs communication with the federal revenue webservice
7
 *
8
 * @category  API
9
 * @package   NFePHP\eFinanc
10
 * @copyright Copyright (c) 2018
11
 * @license   http://www.gnu.org/licenses/lesser.html LGPL v3
12
 * @author    Roberto L. Machado <linux.rlm at gmail dot com>
13
 * @link      http://github.com/nfephp-org/sped-efinanceira for the canonical source repository
14
 */
15
use stdClass;
16
use NFePHP\Common\Validator;
17
use NFePHP\eFinanc\Common\Tools as Base;
18
use NFePHP\eFinanc\Common\Crypto;
19
use NFePHP\eFinanc\Common\FactoryInterface;
20
use NFePHP\eFinanc\Exception\EventsException;
21
use NFePHP\eFinanc\Exception\ProcessException;
22
use NFePHP\eFinanc\Exception\ConsultException;
23
24
class Tools extends Base
25
{
26
    const MODO_NORMAL = 0;
27
    const MODO_ZIP = 1;
28
    const MODO_CRYPTO = 2;
29
    const MODO_CRYPTOZIP = 3;
30
    
31
    /**
32
     * @var array
33
     */
34
    private $available;
35
    /**
36
     * @var stdClass
37
     */
38
    private $urls;
39
    
40 3
    /**
41
     * Constructor
42 3
     * @param string $config
43
     * @param \NFePHP\Common\Certificate $certificate
44
     */
45
    public function __construct(
46
        string $config,
47
        \NFePHP\Common\Certificate $certificate
48
    ) {
49
        parent::__construct($config, $certificate);
50
        $this->available = get_class_methods($this);
51
        $this->urls = new \stdClass();
52
        $this->urls->recepcao = 'https://preprod-efinanc.receita.fazenda.gov.br'
53
            . '/WsEFinanceira/WsRecepcao.asmx';
54
        $this->urls->compact = 'https://preprod-efinanc.receita.fazenda.gov.br'
55
            . '/WsEFinanceira/WsRecepcao.asmx';
56
        $this->urls->crypto = 'https://preprod-efinanc.receita.fazenda.gov.br'
57
            . '/WsEFinanceiraCripto/WsRecepcaoCripto.asmx';
58
        $this->urls->consulta = 'https://preprod-efinanc.receita.fazenda.gov.br'
59
            . '/WsEFinanceira/WsConsulta.asmx';
60
        if ($this->tpAmb == 1) {
61
            $this->urls->recepcao = 'https://efinanc.receita.fazenda.gov.br'
62
                . '/WsEFinanceira/WsRecepcao.asmx';
63
            $this->urls->compact = 'https://efinanc.receita.fazenda.gov.br'
64
                . '/WsEFinanceira/WsRecepcao.asmx';
65
            $this->urls->crypto = 'https://efinanc.receita.fazenda.gov.br'
66
                . '/WsEFinanceiraCripto/WsRecepcaoCripto.asmx';
67
            $this->urls->consulta = 'https://efinanc.receita.fazenda.gov.br'
68
                . '/WsEFinanceira/WsConsulta.asmx';
69
        }
70
    }
71
    
72
    /**
73
     * This method performs the desired query to the webservice
74
     * @param string $type indicate the query to be used
75
     * @param stdClass $std contain the parameters of this query
76
     * @return string xml webservice response
77
     * @throws type
78
     */
79
    public function consultar(string $type, stdClass $std):string
80
    {
81
        $type = lcfirst($type);
82
        if (!in_array($type, $this->available)) {
83
            //esta consulta não foi localizada
84
            throw EventsException::wrongArgument(1000, $type);
85
        }
86
        return $this->$type($std);
87
    }
88
    
89
    /**
90
     * This method sends the events to the webservice
91
     * @param array $events
92
     * @param integer $modo
93
     * @return string xml webservice response
94
     * @throws \InvalidArgumentException
95
     */
96
    public function enviar(array $events, $modo = self::MODO_NORMAL):string
97
    {
98
        //constructor do lote
99
        $body = $this->batchBuilder($events);
100
        //return $body;
101
        $url = $this->urls->recepcao;
102
        $method = 'ReceberLoteEvento';
103
        if ($modo == self::MODO_ZIP) {
104
            //apenas compacta a mensagem
105
            $url = $this->urls->compact;
106
            $method = 'ReceberLoteEventoGZip';
107
            $zip = base64_encode(gzencode($body));
108
            $body = "<sped:bufferXmlGZip>$zip</sped:bufferXmlGZip>";
109
        } elseif ($modo == self::MODO_CRYPTO) {
110
            //apenas encripta a mensagem
111
            $url = $this->urls->crypto;
112
            $method = 'ReceberLoteEventoCripto';
113
            $crypted = base64_encode($this->sendCripto($body));
114
            $body = "<sped:bufferXmlComLoteCriptografado>$crypted</sped:bufferXmlComLoteCriptografado>";
115
        } elseif ($modo == self::MODO_CRYPTOZIP) {
116
            //compacta a mensagem
117
            $url = $this->urls->crypto;
118
            $method = 'ReceberLoteEventoCriptoGZip';
119
            $zip = gzencode($body);
120
            //encripta a mensagem compactada
121
            $crypted = base64_encode($this->sendCripto($zip));
122
            $body = "<sped:bufferXmlComLoteCriptografadoGZip>$crypted</sped:bufferXmlComLoteCriptografadoGZip>";
123
        } else {
124
            $body = "<sped:loteEventos>$body</sped:loteEventos>";
125
        }
126
        return $this->sendRequest($body, $method, $url);
127
    }
128
    
129
    /**
130
     * Allow the registration of new certificates for encrypted messages
131
     * @param string $derdata certificate content in DER format (usual)
132
     * @throws NFePHP\eFincnac\Exception\ProcessException
133
     */
134
    public function setCertificateEFinanceira($derdata)
135
    {
136
        $crypto = new Crypto($derdata);
137
        $info = $crypto->certificateInfo();
138
        $std = json_decode(json_encode($info['details']));
139
        $commonName = $std->subject->commonName;
140
        if ($this->tpAmb == 1
141
            && $commonName != 'efinancentreposto.receita.fazenda.gov.br'
142
        ) {
143
            //O certificado do servidor fornecido não pertence ao commonName requerido
144
            throw ProcessException::wrongArgument(2005, '');
145
        } elseif ($this->tpAmb == 2
146
            && $commonName != 'preprod-efinancentreposto.receita.fazenda.gov.br'
147
        ) {
148
            //O certificado do servidor fornecido não pertence ao commonName requerido
149
            throw ProcessException::wrongArgument(2005, '');
150
        }
151
        $this->der = $derdata;
152
    }
153
    
154
    /**
155
     * This method constructs the event batch
156
     * @param array $events
157
     * @return string
158
     * @throws NFePHP\eFincnac\Exception\ProcessException
159
     */
160
    private function batchBuilder(array $events)
161
    {
162
        if (empty($events)) {
163
            //não foram passados os eventos
164
            throw ProcessException::wrongArgument(2002, '');
165
        }
166
        if (! is_array($events)) {
167
            //não foram passados os eventos
168
            throw ProcessException::wrongArgument(2002, '');
169
        }
170
        $num = count($events);
171
        if ($num > 100) {
172
            //excedido o numero máximo de eventos
173
            throw ProcessException::wrongArgument(2000, $num);
174
        }
175
        $xml = "<eFinanceira "
176
                . "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
177
                . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
178
                . "xmlns=\"http://www.eFinanceira.gov.br/schemas/envioLoteEventos/v$this->eventoVersion\">";
179
        $iCount = 0;
180
        $lote = date('YmdHms');
0 ignored issues
show
Unused Code introduced by
$lote 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...
181
        $xml .= "<loteEventos>";
182
        foreach ($events as $evt) {
183
            if (!is_a($evt, '\NFePHP\eFinanc\Common\FactoryInterface')) {
184
                throw ProcessException::wrongArgument(2002, '');
185
            }
186
            $this->checkCertificate($evt);
187
            $xml .= "<evento id=\"ID".$iCount."\">";
188
            $xml .= $evt->toXML();
189
            $xml .= "</evento>";
190
            $iCount++;
191
        }
192
        $xml .= "</loteEventos>";
193
        $xml .= "</eFinanceira>";
194
        $schema = $this->path
195
            . 'schemes/v'
196
            . $this->eventoVersion
197
            . '/envioLoteEventos-v'
198
            . $this->eventoVersion
199
            . '.xsd';
200
        if ($schema) {
201
            Validator::isValid($xml, $schema);
202
        }
203
        return $xml;
204
    }
205
    
206
    /**
207
     * This method encrypts the event batch
208
     * @param string $body
209
     * @return string
210
     * @throws NFePHP\eFincnac\Exception\ProcessException
211
     */
212
    private function sendCripto($body)
213
    {
214
        if (empty($this->der)) {
215
            //deve existir um certificado do servidor da Receita
216
            throw ProcessException::wrongArgument(2003, '');
217
        }
218
        $crypt = new Crypto($this->der);
219
        $resp = $crypt->certificateInfo();
220
        $dt = new \DateTime();
221
        if ($resp['validTo'] < $dt) {
222
            //a validade do certificado expirou
223
            throw Exception\ProcessException::wrongArgument(2004, '');
224
        }
225
        $id = 1;
226
        $key = $crypt->getEncrypedKey();
227
        $fingerprint = $crypt->getThumbprint();
228
        $crypted = $crypt->encryptMsg($body);
229
        $msg = "<eFinanceira xmlns=\"http://www.eFinanceira.gov.br/schemas"
230
            . "/envioLoteCriptografado/v$this->eventoVersion\">"
231
            . "<loteCriptografado>"
232
            . "<id>$id</id>"
233
            . "<idCertificado>$fingerprint</idCertificado>"
234
            . "<chave>$key</chave>"
235
            . "<lote>$crypted</lote>"
236
            . "</loteCriptografado>"
237
            . "</eFinanceira>";
238
        $schema = $this->path
239
            . 'schemes/v'
240
            . $this->eventoVersion
241
            . '/envioLoteCriptografado-v'
242
            . $this->eventoVersion
243
            . '.xsd';
244
        if ($schema) {
245
            Validator::isValid($msg, $schema);
246
        }
247
        return $msg;
248
    }
249
    
250
    /**
251
     * This method consults "Informacoes Cadastrais"
252
     * @param stdClass $std
253
     * @return string
254
     * @throws NFePHP\eFinanc\Exception\ConsultException
255
     */
256
    protected function consultarInformacoesCadastrais(stdClass $std):string
257
    {
258
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
259
            throw ConsultException::wrongArgument(
260
                'O CNPJ da empresa declarante deve ser informado para essa consulta'
261
            );
262
        }
263
        $method = 'ConsultarInformacoesCadastrais';
264
        $body = "<sped:$method><cnpj>$std->cnpj</cnpj></sped:$method>";
265
        return $this->sendRequest($body, $method, $this->urls->consulta);
266
    }
267
268
    /**
269
     * This method consults "Informacoes Intermediario"
270
     * @param stdClass $std
271
     * @return string
272
     * @throws NFePHP\eFinanc\Exception\ConsultException
273
     */
274
    protected function consultarInformacoesIntermediario(stdClass $std):string
275
    {
276
        $possible = [
277
            'cnpj',
278
            'giin',
279
            'tiponi',
280
            'numeroidentificacao'
281
        ];
282
        $std = $this->equilizeParameters($std, $possible);
283
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
284
            throw ConsultException::wrongArgument(
285
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
286
            );
287
        }
288
        if (empty($std->ginn) && empty($std->numeroidentificacao)) {
289
            throw ConsultException::wrongArgument(
290
                'Algum dado do intermediário deve ser passado.'
291
            );
292
        }
293 View Code Duplication
        if (!empty($std->giin)) {
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...
294
            if (preg_match("/^([0-9A-NP-Z]{6}[.][0-9A-NP-Z]{5}[.](LE|SL|ME|BR|"
295
                    . "SF|SD|SS|SB|SP)[.][0-9]{3})$/", $std->giin)) {
296
                throw ConsultException::wrongArgument(
297
                    'Este GIIN passado não atende a estrutura estabelecida.'
298
                );
299
            }
300
        }
301
        $method = 'ConsultarInformacoesIntermediario';
302
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>";
303
        if (!empty($ginn)) {
0 ignored issues
show
Bug introduced by
The variable $ginn seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
304
            $body .= "<sped:GINN>$std->giin</sped:GINN>";
305
        } elseif (!empty($std->numeroidentificacao)) {
306
            $body .= "<sped:TipoNI>$std->tiponi</sped:TipoNI>"
307
            . "<sped:NumeroIdentificacao>$std->numeroidentificacao</sped:NumeroIdentificacao>";
308
        } else {
309
            throw ConsultException::wrongArgument(
310
                'Deve ser indicado algum documento do Intermediario.'
311
            );
312
        }
313
        $body .= "</sped:$method>";
314
        return $this->sendRequest($body, $method, $this->urls->consulta);
315
    }
316
        
317
    /**
318
     * This method consults "Informacoes Movimento"
319
     * @param stdClass $std
320
     * @return string
321
     * @throws NFePHP\eFinanc\Exception\ConsultException
322
     */
323
    protected function consultarInformacoesMovimento(stdClass $std):string
324
    {
325
        $possible = [
326
            'cnpj',
327
            'situacaoinformacao',
328
            'anomesiniciovigencia',
329
            'anomesterminovigencia',
330
            'tipomovimento',
331
            'tipoidentificacao',
332
            'identificacao'
333
        ];
334
        $std = $this->equilizeParameters($std, $possible);
335
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
336
            throw ConsultException::wrongArgument(
337
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
338
            );
339
        }
340 View Code Duplication
        if (!is_numeric($std->situacaoinformacao)
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...
341
                || !($std->situacaoinformacao >=0 && $std->situacaoinformacao<=3)
342
        ) {
343
            throw ConsultException::wrongArgument(
344
                'A situação deve ser informada: 0-Todas, 1-Ativo, 2-Retificado,3-Excluído.'
345
            );
346
        }
347
        if (!preg_match(
348
            "/^(19[0-9][0-9]|2[0-9][0-9][0-9])[\/](0?[1-9]|1[0-2])$/",
349
            $std->anomesiniciovigencia
350
        )
351
        ) {
352
            throw ConsultException::wrongArgument(
353
                'O ano e mês do inicio da vigência deve ser informado: AAAA/MM.'
354
            );
355
        }
356
        if (!preg_match(
357
            "/^(19[0-9][0-9]|2[0-9][0-9][0-9])[\/](0?[1-9]|1[0-2])$/",
358
            $std->anomesterminovigencia
359
        )
360
        ) {
361
            throw ConsultException::wrongArgument(
362
                'O ano e mês do inicio do término da vigência deve ser informado: AAAA/MM.'
363
            );
364
        }
365
        $method = 'ConsultarInformacoesMovimento';
366
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>"
367
           . "<sped:situacaoInformacao>$std->situacaoinformacao</sped:situacaoInformacao>"
368
           ."<sped:anoMesInicioVigencia>$std->anomesiniciovigencia</sped:anoMesInicioVigencia>"
369
           . "<sped:anoMesTerminoVigencia>$std->anomesterminovigencia</sped:anoMesTerminoVigencia>";
370
        if (!empty($std->tipomovimento)) {
371
            if (preg_match("/[1-2]{1}/", $std->tipomovimento)) {
372
                $body .= "<sped:tipoMovimento>$std->tipomovimento</sped:tipoMovimento>";
373
            }
374
        }
375
        if (!empty($std->tipoidentificacao)) {
376
            if (preg_match("/[1-7]{1}|99/", $std->tipoidentificacao)) {
377
                $body .= "<sped:tipoIdentificacao>$std->tipoidentificacao</sped:tipoIdentificacao>";
378
                $body .= "<sped:identificacao>$std->identificacao</sped:identificacao>";
379
            }
380
        }
381
        $body .= "</sped:$method>";
382
        return $this->sendRequest($body, $method, $this->urls->consulta);
383
    }
384
385
    /**
386
     * This method consults "Informacoes Patrocinado"
387
     * @param stdClass $std
388
     * @return string
389
     * @throws NFePHP\eFinanc\Exception\ConsultException
390
     */
391
    protected function consultarInformacoesPatrocinado(stdClass $std):string
392
    {
393
        $possible = [
394
            'cnpj',
395
            'giin',
396
            'numeroidentificacao'
397
        ];
398
        $std = $this->equilizeParameters($std, $possible);
399
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
400
            throw ConsultException::wrongArgument(
401
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
402
            );
403
        }
404
        if (empty($std->ginn) && empty($std->numeroidentificacao)) {
405
            throw ConsultException::wrongArgument(
406
                'Algum dado do patrocinado deve ser passado.'
407
            );
408
        }
409 View Code Duplication
        if (!empty($std->giin)) {
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...
410
            if (!preg_match("/^([0-9A-NP-Z]{6}[.][0-9A-NP-Z]{5}[.](LE|SL|ME|BR|SF"
411
                    . "|SD|SS|SB|SP)[.][0-9]{3})$/", $std->giin)) {
412
                throw ConsultException::wrongArgument(
413
                    'Este GIIN passado não atende a estrutura estabelecida.'
414
                );
415
            }
416
        }
417
        $method = 'ConsultarInformacoesPatrocinado';
418
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>";
419
        if (!empty($std->giin)) {
420
            $body .= "<sped:GINN>$std->giin</sped:GINN>";
421
        }
422
        if (!empty($std->numeroidentificacao)) {
423
            $body .= "<sped:NumeroIdentificacao>$std->numeroidentificacao</sped:NumeroIdentificacao>";
424
        }
425
        $body .= "</sped:$method>";
426
        return $this->sendRequest($body, $method, $this->urls->consulta);
427
    }
428
429
    /**
430
     * This method consults "Informacoes Rerct"
431
     * @param stdClass $std
432
     * @return string
433
     * @throws NFePHP\eFinanc\Exception\ConsultException
434
     */
435
    protected function consultarInformacoesRerct(stdClass $std):string
436
    {
437
        $possible = [
438
            'ideventorerct',
439
            'situacaoinformacao',
440
            'numerorecibo',
441
            'cnpjdeclarante',
442
            'tipoinscricaodeclarado',
443
            'inscricaodeclarado',
444
            'tipoinscricaotitular',
445
            'inscricaotitular',
446
            'cpfbeneficiariofinal'
447
        ];
448
        $std = $this->equilizeParameters($std, $possible);
449
        if (empty($std->cnpjdeclarante) && !preg_match("/^[0-9]{14}/", $std->cnpjdeclarante)) {
450
            throw ConsultException::wrongArgument(
451
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
452
            );
453
        }
454
        if (!is_numeric($std->ideventorerct)
455
                || !($std->ideventorerct == 1 || $std->ideventorerct == 2)
456
        ) {
457
            throw ConsultException::wrongArgument(
458
                'A Identificação do Evento RERCT deve ser informada.'
459
            );
460
        }
461 View Code Duplication
        if (!is_numeric($std->situacaoinformacao)
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...
462
                || !($std->situacaoinformacao >=0 && $std->situacaoinformacao<=3)
463
        ) {
464
            throw ConsultException::wrongArgument(
465
                'A situação deve ser informada: 0-Todas, 1-Ativo, 2-Retificado,3-Excluído.'
466
            );
467
        }
468
        $method = 'ConsultarInformacoesRerct';
469
        $body = "<sped:$method><sped:idEventoRerct>$std->ideventorerct</sped:idEventoRerct>"
470
            . "<sped:situacaoInformacao>$std->situacaoinformacao</sped:situacaoInformacao>";
471
        
472
        if (preg_match("/^([0-9]{1,18}[-][0-9]{2}[-][0-9]{3}[-][0-9]{4}[-][0-9]{1,18})$/", $std->numerorecibo)) {
473
            $body .= "<sped:numeroRecibo>$std->numerorecibo</sped:numeroRecibo>";
474
        }
475
        $body .= "<sped:cnpjDeclarante>$std->cnpjdeclarante</sped:cnpjDeclarante>";
476
        if (preg_match('/[0-9]{11,14}/', $std->inscricaodeclarado)) {
477
            $body .= "<sped:tipoInscricaoDeclarado>$std->tipoinscricaodeclarado</sped:tipoInscricaoDeclarado>"
478
                . "<sped:inscricaoDeclarado>$std->inscricaodeclarado</sped:inscricaoDeclarado>";
479
        }
480
        if (preg_match('/[0-9]{11,14}/', $std->inscricaotitular)) {
481
            $body .= "<sped:tipoInscricaoTitular>$std->tipoinscricaotitular</sped:tipoInscricaoTitular>"
482
                . "<sped:inscricaoTitular>$std->inscricaotitular</sped:inscricaoTitular>";
483
        }
484
        if (preg_match('/[0-9]{11}/', $std->cpfbeneficiariofinal)) {
485
            $body .= "<sped:cpfBeneficiarioFinal>$std->cpfbeneficiariofinal</sped:cpfBeneficiarioFinal>";
486
        }
487
        $body .= "</sped:$method>";
488
        return $this->sendRequest($body, $method, $this->urls->consulta);
489
    }
490
491
    /**
492
     * This method consults "Lista EFinanceira"
493
     * @param stdClass $std
494
     * @return string
495
     * @throws NFePHP\eFinanc\Exception\ConsultException
496
     */
497
    protected function consultarListaEFinanceira(stdClass $std):string
498
    {
499
        $possible = [
500
            'cnpj',
501
            'situacaoefinanceira',
502
            'datainicio',
503
            'dataFim'
504
        ];
505
        $std = $this->equilizeParameters($std, $possible);
506
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
507
            throw ConsultException::wrongArgument(
508
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
509
            );
510
        }
511 View Code Duplication
        if (!is_numeric($std->situacaoefinanceira)
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...
512
                || !($std->situacaoefinanceira >=0 && $std->situacaoefinanceira<=4)
513
        ) {
514
            throw ConsultException::wrongArgument(
515
                'A situação deve ser informada: 0-Todas,1-Em Andamento,2-Ativa,'
516
                    . '3-Retificada,4-Excluída.'
517
            );
518
        }
519
        $method = 'ConsultarListaEFinanceira';
520
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>"
521
            . "<sped:situacaoEFinanceira>$std->situacaoefinanceira</sped:situacaoEFinanceira>";
522
        if (!empty($std->datainicio)) {
523
            $body .= "<sped:dataInicio>$std->datainicio</sped:dataInicio>";
524
        }
525
        if (!empty($std->datafim)) {
526
            $body .= "<sped:dataFim>$std->datafim</sped:dataFim>";
527
        }
528
        $body .= "</sped:$method>";
529
        return $this->sendRequest($body, $method, $this->urls->consulta);
530
    }
531
    
532
    /**
533
     * Verify the availability of a digital certificate.
534
     * If available, place it where it is needed
535
     * @param FactoryInterface $evento
536
     * @throws RuntimeException
537
     */
538
    protected function checkCertificate(FactoryInterface $evento)
539
    {
540
        //try to get certificate from event
541
        $certificate = $evento->getCertificate();
542
        if (empty($certificate)) {
543
            $evento->setCertificate($this->certificate);
544
        }
545
    }
546
}
547