Completed
Push — master ( 9654f6...5e67fa )
by Roberto
14:40
created

Tools   C

Complexity

Total Complexity 75

Size/Duplication

Total Lines 500
Duplicated Lines 7.6 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 1.12%

Importance

Changes 0
Metric Value
wmc 75
c 0
b 0
f 0
lcom 1
cbo 7
dl 38
loc 500
rs 5.5056
ccs 2
cts 178
cp 0.0112

12 Methods

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