Tools   F
last analyzed

Complexity

Total Complexity 78

Size/Duplication

Total Lines 542
Duplicated Lines 8.3 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 1.12%

Importance

Changes 0
Metric Value
wmc 78
lcom 1
cbo 6
dl 45
loc 542
ccs 2
cts 178
cp 0.0112
rs 2.16
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 26 2
A consultar() 0 9 2
A enviar() 0 34 4
A setCertificateEFinanceira() 0 28 5
B batchBuilder() 0 46 7
A sendCripto() 0 38 4
A consultarInformacoesCadastrais() 0 11 3
B consultarInformacoesIntermediario() 8 42 9
C consultarInformacoesMovimento() 7 67 10
B consultarInformacoesPatrocinado() 8 37 9
C consultarInformacoesRerct() 14 55 13
B consultarListaEFinanceira() 8 34 8
A checkCertificate() 0 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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

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

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

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
        //header('Content-Type: application/xml; charset=utf-8');
101
        //echo $body;
102
        //die;
103
        $url = $this->urls->recepcao;
104
        $method = 'ReceberLoteEvento';
105
        if ($modo == self::MODO_ZIP) {
106
            //apenas compacta a mensagem
107
            $url = $this->urls->compact;
108
            $method = 'ReceberLoteEventoGZip';
109
            $zip = base64_encode(gzencode($body));
110
            $body = "<sped:bufferXmlGZip>$zip</sped:bufferXmlGZip>";
111
        } elseif ($modo == self::MODO_CRYPTO) {
112
            //apenas encripta a mensagem
113
            $url = $this->urls->crypto;
114
            $method = 'ReceberLoteEventoCripto';
115
            $crypted = base64_encode($this->sendCripto($body));
116
            $body = "<sped:bufferXmlComLoteCriptografado>$crypted</sped:bufferXmlComLoteCriptografado>";
117
        } elseif ($modo == self::MODO_CRYPTOZIP) {
118
            //compacta a mensagem
119
            $url = $this->urls->crypto;
120
            $method = 'ReceberLoteEventoCriptoGZip';
121
            $zip = gzencode($body);
122
            //encripta a mensagem compactada
123
            $crypted = base64_encode($this->sendCripto($zip));
124
            $body = "<sped:bufferXmlComLoteCriptografadoGZip>$crypted</sped:bufferXmlComLoteCriptografadoGZip>";
125
        } else {
126
            $body = "<sped:loteEventos>$body</sped:loteEventos>";
127
        }
128
        return $this->sendRequest($body, $method, $url);
129
    }
130
    
131
    /**
132
     * Allow the registration of new certificates for encrypted messages
133
     * @param string $derdata certificate content in DER format (usual)
134
     * @throws NFePHP\eFincnac\Exception\ProcessException
135
     */
136
    public function setCertificateEFinanceira($derdata)
137
    {
138
        $crypto = new Crypto($derdata);
139
        $info = $crypto->certificateInfo();
140
        //$std = json_decode(json_encode($info['details']));
141
        //$commonName = $std->subject->commonName;
142
        $commonName = $info['details']['subject']['commonName'];
143
        if ($this->tpAmb == 1
144
            && $commonName != 'efinancentreposto.receita.fazenda.gov.br'
145
        ) {
146
            //O certificado do servidor fornecido não pertence ao commonName requerido
147
            throw ProcessException::wrongArgument(
148
                2005,
149
                " requerido [efinancentreposto.receita.fazenda.gov.br] != "
150
                . "encontrado [$commonName] "
151
            );
152
        } elseif ($this->tpAmb == 2
153
            && $commonName != 'preprod-efinancentreposto.receita.fazenda.gov.br'
154
        ) {
155
            //O certificado do servidor fornecido não pertence ao commonName requerido
156
            throw ProcessException::wrongArgument(
157
                2005,
158
                " requerido [preprod-efinancentreposto.receita.fazenda.gov.br] "
159
                . "!= encontrado [$commonName] "
160
            );
161
        }
162
        $this->der = $derdata;
163
    }
164
    
165
    /**
166
     * This method constructs the event batch
167
     * @param array $events
168
     * @return string
169
     * @throws NFePHP\eFinanc\Exception\ProcessException
170
     */
171
    private function batchBuilder(array $events)
172
    {
173
        if (empty($events)) {
174
            //não foram passados os eventos
175
            throw ProcessException::wrongArgument(2002, '');
176
        }
177
        if (! is_array($events)) {
178
            //não foram passados os eventos
179
            throw ProcessException::wrongArgument(2002, '');
180
        }
181
        $num = count($events);
182
        if ($num > 100) {
183
            //excedido o numero máximo de eventos
184
            throw ProcessException::wrongArgument(2000, $num);
185
        }
186
        $layout = $this->versions['envioLoteEventos'];
187
        $xml = "<eFinanceira "
188
                . "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
189
                . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
190
                . "xmlns=\"http://www.eFinanceira.gov.br/schemas/envioLoteEventos/v$layout\">";
191
        $iCount = 0;
192
        $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...
193
        $xml .= "<loteEventos>";
194
        foreach ($events as $evt) {
195
            if (!is_a($evt, '\NFePHP\eFinanc\Common\FactoryInterface')) {
196
                throw ProcessException::wrongArgument(2002, '');
197
            }
198
            $this->checkCertificate($evt);
199
            $xml .= "<evento id=\"ID".$iCount."\">";
200
            $xml .= $evt->toXML();
201
            $xml .= "</evento>";
202
            $iCount++;
203
        }
204
        $xml .= "</loteEventos>";
205
        $xml .= "</eFinanceira>";
206
        $schema = $this->path
207
            . 'schemes/v'
208
            . $this->eventoVersion
209
            . '/envioLoteEventos-v'
210
            . $layout
211
            . '.xsd';
212
        if ($schema) {
213
            Validator::isValid($xml, $schema);
214
        }
215
        return $xml;
216
    }
217
    
218
    /**
219
     * This method encrypts the event batch
220
     * @param string $body
221
     * @return string
222
     * @throws NFePHP\eFincnac\Exception\ProcessException
223
     */
224
    public function sendCripto($body)
225
    {
226
        if (empty($this->der)) {
227
            //deve existir um certificado do servidor da Receita
228
            throw ProcessException::wrongArgument(2003, '');
229
        }
230
        $crypt = new Crypto($this->der);
231
        $resp = $crypt->certificateInfo();
232
        $dt = new \DateTime();
233
        if ($resp['validTo'] < $dt) {
234
            //a validade do certificado expirou
235
            throw Exception\ProcessException::wrongArgument(2004, '');
236
        }
237
        $id = 1;
238
        $layout = $this->versions['envioLoteCriptografado'];
239
        $key = $crypt->getEncrypedKey();
240
        $fingerprint = $crypt->getThumbprint();
241
        $crypted = $crypt->encryptMsg($body);
242
        $msg = "<eFinanceira xmlns=\"http://www.eFinanceira.gov.br/schemas"
243
            . "/envioLoteCriptografado/v$layout\">"
244
            . "<loteCriptografado>"
245
            . "<id>$id</id>"
246
            . "<idCertificado>$fingerprint</idCertificado>"
247
            . "<chave>$key</chave>"
248
            . "<lote>$crypted</lote>"
249
            . "</loteCriptografado>"
250
            . "</eFinanceira>";
251
        $schema = $this->path
252
            . 'schemes/v'
253
            . $this->eventoVersion
254
            . '/envioLoteCriptografado-v'
255
            . $layout
256
            . '.xsd';
257
        if ($schema) {
258
            Validator::isValid($msg, $schema);
259
        }
260
        return $msg;
261
    }
262
    
263
    /**
264
     * This method consults "Informacoes Cadastrais"
265
     * @param stdClass $std
266
     * @return string
267
     * @throws NFePHP\eFinanc\Exception\ConsultException
268
     */
269
    protected function consultarInformacoesCadastrais(stdClass $std):string
270
    {
271
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
272
            throw ConsultException::wrongArgument(
273
                'O CNPJ da empresa declarante deve ser informado para essa consulta'
274
            );
275
        }
276
        $method = 'ConsultarInformacoesCadastrais';
277
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj></sped:$method>";
278
        return $this->sendRequest($body, $method, $this->urls->consulta);
279
    }
280
281
    /**
282
     * This method consults "Informacoes Intermediario"
283
     * @param stdClass $std
284
     * @return string
285
     * @throws NFePHP\eFinanc\Exception\ConsultException
286
     */
287
    protected function consultarInformacoesIntermediario(stdClass $std):string
288
    {
289
        $possible = [
290
            'cnpj',
291
            'giin',
292
            'tiponi',
293
            'numeroidentificacao'
294
        ];
295
        $std = $this->equilizeParameters($std, $possible);
296
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
297
            throw ConsultException::wrongArgument(
298
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
299
            );
300
        }
301
        if (empty($std->ginn) && empty($std->numeroidentificacao)) {
302
            throw ConsultException::wrongArgument(
303
                'Algum dado do intermediário deve ser passado.'
304
            );
305
        }
306 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...
307
            if (preg_match("/^([0-9A-NP-Z]{6}[.][0-9A-NP-Z]{5}[.](LE|SL|ME|BR|"
308
                    . "SF|SD|SS|SB|SP)[.][0-9]{3})$/", $std->giin)) {
309
                throw ConsultException::wrongArgument(
310
                    'Este GIIN passado não atende a estrutura estabelecida.'
311
                );
312
            }
313
        }
314
        $method = 'ConsultarInformacoesIntermediario';
315
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>";
316
        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...
317
            $body .= "<sped:GINN>$std->giin</sped:GINN>";
318
        } elseif (!empty($std->numeroidentificacao)) {
319
            $body .= "<sped:TipoNI>$std->tiponi</sped:TipoNI>"
320
            . "<sped:NumeroIdentificacao>$std->numeroidentificacao</sped:NumeroIdentificacao>";
321
        } else {
322
            throw ConsultException::wrongArgument(
323
                'Deve ser indicado algum documento do Intermediario.'
324
            );
325
        }
326
        $body .= "</sped:$method>";
327
        return $this->sendRequest($body, $method, $this->urls->consulta);
328
    }
329
        
330
    /**
331
     * This method consults "Informacoes Movimento"
332
     * @param stdClass $std
333
     * @return string
334
     * @throws NFePHP\eFinanc\Exception\ConsultException
335
     */
336
    protected function consultarInformacoesMovimento(stdClass $std):string
337
    {
338
        $possible = [
339
            'cnpj',
340
            'situacaoinformacao',
341
            'anomesiniciovigencia',
342
            'anomesterminovigencia',
343
            'tipomovimento',
344
            'tipoidentificacao',
345
            'identificacao'
346
        ];
347
        $std = $this->equilizeParameters($std, $possible);
348
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
349
            throw ConsultException::wrongArgument(
350
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
351
            );
352
        }
353 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...
354
                || !($std->situacaoinformacao >=0 && $std->situacaoinformacao<=3)
355
        ) {
356
            throw ConsultException::wrongArgument(
357
                'A situação deve ser informada: 0-Todas, 1-Ativo, 2-Retificado,3-Excluído.'
358
            );
359
        }
360
        /*
361
        if (!preg_match(
362
            "/^(19[0-9][0-9]|2[0-9][0-9][0-9])[\/](0?[1-9]|1[0-2])$/",
363
            $std->anomesiniciovigencia
364
        )
365
        ) {
366
            throw ConsultException::wrongArgument(
367
                'O ano e mês do inicio da vigência deve ser informado: AAAA/MM.'
368
            );
369
        }
370
        if (!preg_match(
371
            "/^(19[0-9][0-9]|2[0-9][0-9][0-9])[\/](0?[1-9]|1[0-2])$/",
372
            $std->anomesterminovigencia
373
        )
374
        ) {
375
            throw ConsultException::wrongArgument(
376
                'O ano e mês do inicio do término da vigência deve ser informado: AAAA/MM.'
377
            );
378
        }
379
         */
380
        $method = 'ConsultarInformacoesMovimento';
381
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>"
382
           . "<sped:situacaoInformacao>$std->situacaoinformacao</sped:situacaoInformacao>"
383
           . "<sped:anoMesInicioVigencia>$std->anomesiniciovigencia</sped:anoMesInicioVigencia>"
384
           . "<sped:anoMesTerminoVigencia>$std->anomesterminovigencia</sped:anoMesTerminoVigencia>";
385
        if (!empty($std->tipomovimento)) {
386
            if (preg_match("/[1-2]{1}/", $std->tipomovimento)) {
387
                $body .= "<sped:tipoMovimento>$std->tipomovimento</sped:tipoMovimento>";
388
            }
389
        }
390
        if (!empty($std->tipoidentificacao)) {
391
            if (!preg_match("/^[1-7]{1}|99$/", $std->tipoidentificacao)) {
392
                throw ConsultException::wrongArgument(
393
                    "O tipo de identificação deve ser numerico e deve estar entre 1 e 7 ou 99."
394
                    . " [$std->tipoidentificacao] não atende os requisitos."
395
                );
396
            }
397
            $body .= "<sped:tipoIdentificacao>$std->tipoidentificacao</sped:tipoIdentificacao>";
398
            $body .= "<sped:identificacao>$std->identificacao</sped:identificacao>";
399
        }
400
        $body .= "</sped:$method>";
401
        return $this->sendRequest($body, $method, $this->urls->consulta);
402
    }
403
404
    /**
405
     * This method consults "Informacoes Patrocinado"
406
     * @param stdClass $std
407
     * @return string
408
     * @throws NFePHP\eFinanc\Exception\ConsultException
409
     */
410
    protected function consultarInformacoesPatrocinado(stdClass $std):string
411
    {
412
        $possible = [
413
            'cnpj',
414
            'giin',
415
            'numeroidentificacao'
416
        ];
417
        $std = $this->equilizeParameters($std, $possible);
418
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
419
            throw ConsultException::wrongArgument(
420
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
421
            );
422
        }
423
        if (empty($std->ginn) && empty($std->numeroidentificacao)) {
424
            throw ConsultException::wrongArgument(
425
                'Algum dado do patrocinado deve ser passado.'
426
            );
427
        }
428 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...
429
            if (!preg_match("/^([0-9A-NP-Z]{6}[.][0-9A-NP-Z]{5}[.](LE|SL|ME|BR|SF"
430
                    . "|SD|SS|SB|SP)[.][0-9]{3})$/", $std->giin)) {
431
                throw ConsultException::wrongArgument(
432
                    'Este GIIN passado não atende a estrutura estabelecida.'
433
                );
434
            }
435
        }
436
        $method = 'ConsultarInformacoesPatrocinado';
437
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>";
438
        if (!empty($std->giin)) {
439
            $body .= "<sped:GINN>$std->giin</sped:GINN>";
440
        }
441
        if (!empty($std->numeroidentificacao)) {
442
            $body .= "<sped:NumeroIdentificacao>$std->numeroidentificacao</sped:NumeroIdentificacao>";
443
        }
444
        $body .= "</sped:$method>";
445
        return $this->sendRequest($body, $method, $this->urls->consulta);
446
    }
447
448
    /**
449
     * This method consults "Informacoes Rerct"
450
     * @param stdClass $std
451
     * @return string
452
     * @throws NFePHP\eFinanc\Exception\ConsultException
453
     */
454
    protected function consultarInformacoesRerct(stdClass $std):string
455
    {
456
        $possible = [
457
            'ideventorerct',
458
            'situacaoinformacao',
459
            'numerorecibo',
460
            'cnpjdeclarante',
461
            'tipoinscricaodeclarado',
462
            'inscricaodeclarado',
463
            'tipoinscricaotitular',
464
            'inscricaotitular',
465
            'cpfbeneficiariofinal'
466
        ];
467
        $std = $this->equilizeParameters($std, $possible);
468
        if (empty($std->cnpjdeclarante) && !preg_match("/^[0-9]{14}/", $std->cnpjdeclarante)) {
469
            throw ConsultException::wrongArgument(
470
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
471
            );
472
        }
473 View Code Duplication
        if (!is_numeric($std->ideventorerct)
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...
474
                || !($std->ideventorerct == 1 || $std->ideventorerct == 2)
475
        ) {
476
            throw ConsultException::wrongArgument(
477
                'A Identificação do Evento RERCT deve ser informada.'
478
            );
479
        }
480 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...
481
                || !($std->situacaoinformacao >=0 && $std->situacaoinformacao<=3)
482
        ) {
483
            throw ConsultException::wrongArgument(
484
                'A situação deve ser informada: 0-Todas, 1-Ativo, 2-Retificado,3-Excluído.'
485
            );
486
        }
487
        $method = 'ConsultarInformacoesRerct';
488
        $body = "<sped:$method><sped:idEventoRerct>$std->ideventorerct</sped:idEventoRerct>"
489
            . "<sped:situacaoInformacao>$std->situacaoinformacao</sped:situacaoInformacao>";
490
        
491
        if (preg_match("/^([0-9]{1,18}[-][0-9]{2}[-][0-9]{3}[-][0-9]{4}[-][0-9]{1,18})$/", $std->numerorecibo)) {
492
            $body .= "<sped:numeroRecibo>$std->numerorecibo</sped:numeroRecibo>";
493
        }
494
        $body .= "<sped:cnpjDeclarante>$std->cnpjdeclarante</sped:cnpjDeclarante>";
495
        if (preg_match('/[0-9]{11,14}/', $std->inscricaodeclarado)) {
496
            $body .= "<sped:tipoInscricaoDeclarado>$std->tipoinscricaodeclarado</sped:tipoInscricaoDeclarado>"
497
                . "<sped:inscricaoDeclarado>$std->inscricaodeclarado</sped:inscricaoDeclarado>";
498
        }
499
        if (preg_match('/[0-9]{11,14}/', $std->inscricaotitular)) {
500
            $body .= "<sped:tipoInscricaoTitular>$std->tipoinscricaotitular</sped:tipoInscricaoTitular>"
501
                . "<sped:inscricaoTitular>$std->inscricaotitular</sped:inscricaoTitular>";
502
        }
503
        if (preg_match('/[0-9]{11}/', $std->cpfbeneficiariofinal)) {
504
            $body .= "<sped:cpfBeneficiarioFinal>$std->cpfbeneficiariofinal</sped:cpfBeneficiarioFinal>";
505
        }
506
        $body .= "</sped:$method>";
507
        return $this->sendRequest($body, $method, $this->urls->consulta);
508
    }
509
510
    /**
511
     * This method consults "Lista EFinanceira"
512
     * @param stdClass $std
513
     * @return string
514
     * @throws NFePHP\eFinanc\Exception\ConsultException
515
     */
516
    protected function consultarListaEFinanceira(stdClass $std):string
517
    {
518
        $possible = [
519
            'cnpj',
520
            'situacaoefinanceira',
521
            'datainicio',
522
            'dataFim'
523
        ];
524
        $std = $this->equilizeParameters($std, $possible);
525
        if (empty($std->cnpj) && !preg_match("/^[0-9]{14}/", $std->cnpj)) {
526
            throw ConsultException::wrongArgument(
527
                'O CNPJ da empresa declarante deve ser informado para essa consulta.'
528
            );
529
        }
530 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...
531
                || !($std->situacaoefinanceira >=0 && $std->situacaoefinanceira<=4)
532
        ) {
533
            throw ConsultException::wrongArgument(
534
                'A situação deve ser informada: 0-Todas,1-Em Andamento,2-Ativa,'
535
                    . '3-Retificada,4-Excluída.'
536
            );
537
        }
538
        $method = 'ConsultarListaEFinanceira';
539
        $body = "<sped:$method><sped:cnpj>$std->cnpj</sped:cnpj>"
540
            . "<sped:situacaoEFinanceira>$std->situacaoefinanceira</sped:situacaoEFinanceira>";
541
        if (!empty($std->datainicio)) {
542
            $body .= "<sped:dataInicio>$std->datainicio</sped:dataInicio>";
543
        }
544
        if (!empty($std->datafim)) {
545
            $body .= "<sped:dataFim>$std->datafim</sped:dataFim>";
546
        }
547
        $body .= "</sped:$method>";
548
        return $this->sendRequest($body, $method, $this->urls->consulta);
549
    }
550
    
551
    /**
552
     * Verify the availability of a digital certificate.
553
     * If available, place it where it is needed
554
     * @param FactoryInterface $evento
555
     * @throws RuntimeException
556
     */
557
    protected function checkCertificate(FactoryInterface $evento)
558
    {
559
        //try to get certificate from event
560
        $certificate = $evento->getCertificate();
561
        if (empty($certificate)) {
562
            $evento->setCertificate($this->certificate);
563
        }
564
    }
565
}
566