Completed
Pull Request — master (#210)
by Roberto
03:06
created

Tools::consultarEventosTrabalhador()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 59
ccs 0
cts 51
cp 0
rs 8.8945
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 6

How to fix   Long Method   

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:

1
<?php
2
3
namespace NFePHP\eSocial;
4
5
/**
6
 * Classe Tools, performs communication with the e-Social webservice
7
 *
8
 * @category  library
9
 * @package   NFePHP\eSocial
10
 * @copyright Copyright (c) 2017
11
 * @license   https://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3
12
 * @license   https://www.gnu.org/licenses/gpl-3.0.txt GPLv3
13
 * @license   https://opensource.org/licenses/mit-license.php MIT
14
 * @author    Roberto L. Machado <linux.rlm at gmail dot com>
15
 * @link      http://github.com/nfephp-org/sped-esocial for the canonical source repository
16
 */
17
use InvalidArgumentException;
18
use NFePHP\Common\Certificate;
19
use NFePHP\Common\Validator;
20
use NFePHP\Common\Signer;
21
use NFePHP\eSocial\Common\FactoryInterface;
22
use NFePHP\eSocial\Common\Soap\SoapCurl;
23
use NFePHP\eSocial\Common\Soap\SoapInterface;
24
use NFePHP\eSocial\Common\Tools as ToolsBase;
25
use RuntimeException;
26
27
class Tools extends ToolsBase
28
{
29
    /**
30
     * @var string
31
     */
32
    public $lastRequest;
33
    /**
34
     * @var string
35
     */
36
    public $lastResponse;
37
    /**
38
     * @var \NFePHP\Common\Soap\SoapInterface
39
     */
40
    protected $soap;
41
    /**
42
     * @var array
43
     */
44
    protected $soapnamespaces = [
45
        'xmlns:xsi'  => "http://www.w3.org/2001/XMLSchema-instance",
46
        'xmlns:xsd'  => "http://www.w3.org/2001/XMLSchema",
47
        'xmlns:soap' => "http://www.w3.org/2003/05/soap-envelope",
48
    ];
49
    /**
50
     * @var \SoapHeader
51
     */
52
    protected $objHeader;
53
    /**
54
     * @var string
55
     */
56
    protected $xmlns;
57
    /**
58
     * @var string
59
     */
60
    protected $uri;
61
    /**
62
     * @var string
63
     */
64
    protected $action;
65
    /**
66
     * @var string
67
     */
68
    protected $method;
69
    /**
70
     * @var array
71
     */
72
    protected $parameters;
73
    /**
74
     * @var array
75
     */
76
    protected $envelopeXmlns;
77
    /**
78
     * @var array
79
     */
80
    protected $urlbase;
81
    /**
82
     * @var string
83
     */
84
    protected $namespace = 'http://www.esocial.gov.br/servicos';
85
86
87
    /**
88
     * Constructor
89
     * @param string $config
90
     * @param Certificate $certificate
91
     */
92
    public function __construct($config, Certificate $certificate)
93
    {
94
        parent::__construct($config, $certificate);
95
        //define o ambiente a ser usado
96
        $this->urlbase = [
97
            'consulta' =>  'https://webservices.producaorestrita.esocial.gov.br/'
98
            . 'servicos/empregador/consultarloteeventos/WsConsultarLoteEventos.svc',
99
            'envio' => 'https://webservices.producaorestrita.esocial.gov.br/'
100
            . 'servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc',
101
            'identificadores' => 'https://webservices.producaorestrita.esocial.gov.br/'
102
            . 'servicos/empregador/dwlcirurgico/WsConsultarIdentificadoresEventos.svc',
103
            'downloads' => 'https://webservices.producaorestrita.esocial.gov.br/'
104
            . 'servicos/empregador/dwlcirurgico/WsSolicitarDownloadEventos.svc'
105
        ];
106
        if ($this->tpAmb == 1) {
107
            $this->urlbase = [
108
                'consulta' =>  'https://webservices.consulta.esocial.gov.br/'
109
                . 'servicos/empregador/consultarloteeventos/WsConsultarLoteEventos.svc',
110
                'envio' => 'https://webservices.envio.esocial.gov.br/'
111
                . 'servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc',
112
                'identificadores' => 'https://webservices.download.esocial.gov.br/'
113
                . 'servicos/empregador/dwlcirurgico/WsConsultarIdentificadoresEventos.svc',
114
                'downloads' => 'https://webservices.download.esocial.gov.br/'
115
                . 'servicos/empregador/dwlcirurgico/WsSolicitarDownloadEventos.svc'
116
            ];
117
        }
118
    }
119
120
    /**
121
     * SOAP communication dependency injection
122
     * @param SoapInterface $soap
123
     */
124
    public function loadSoapClass(SoapInterface $soap)
125
    {
126
        $this->soap = $soap;
0 ignored issues
show
Documentation Bug introduced by
It seems like $soap of type object<NFePHP\eSocial\Common\Soap\SoapInterface> is incompatible with the declared type object<NFePHP\Common\Soap\SoapInterface> of property $soap.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
127
    }
128
129
    /**
130
     * Event batch query
131
     * @param  string $protocolo
132
     * @return string
133
     */
134
    public function consultarLoteEventos($protocolo)
135
    {
136
        $operationVersion = $this->serviceXsd['ConsultaLoteEventos']['version'];
137
        if (empty($operationVersion)) {
138
            throw new \InvalidArgumentException(
139
                'Schemas não localizados, verifique de passou as versões '
140
                    . 'corretamente no config.'
141
            );
142
        }
143
        $verWsdl = $this->serviceXsd['WsConsultarLoteEventos']['version'];
144
        $this->action = "{$this->namespace}/empregador/lote"
145
            ."/eventos/envio/consulta/retornoProcessamento/$verWsdl"
146
            ."/ServicoConsultarLoteEventos/ConsultarLoteEventos";
147
        
148
        $this->method = "ConsultarLoteEventos";
149
        $this->uri = $this->urlbase['consulta'];
150
        $this->envelopeXmlns = [
151
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
152
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/lote"
153
                ."/eventos/envio/consulta/retornoProcessamento/$verWsdl",
154
        ];
155
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/lote"
156
            ."/eventos/envio/consulta/retornoProcessamento/"
157
            . $operationVersion . "\" "
158
            ."xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
159
            ."<consultaLoteEventos>"
160
            ."<protocoloEnvio>$protocolo</protocoloEnvio>"
161
            ."</consultaLoteEventos>"
162
            ."</eSocial>";
163
        
164
        //validar a requisição conforme o seu respectivo XSD
165
        Validator::isValid(
166
            $request,
167
            $this->path
168
            ."schemes/comunicacao/$this->serviceStr/"
169
            ."ConsultaLoteEventos-$operationVersion.xsd"
170
        );
171
        $body = "<v1:ConsultarLoteEventos>"
172
            ."<v1:consulta>"
173
            .$request
174
            ."</v1:consulta>"
175
            ."</v1:ConsultarLoteEventos>";
176
        $this->lastRequest  = $body;
177
        $this->lastResponse = $this->sendRequest($body);
178
        return $this->lastResponse;
179
    }
180
    
181
    /**
182
     * Events Identification employer query
183
     * @param string $tpEvt
184
     * @param string $perapur
185
     * @return string
186
     * @throws InvalidArgumentException
187
     */
188
    public function consultarEventosEmpregador($tpEvt, $perapur)
189
    {
190
        $operationVersion = $this->serviceXsd['ConsultaIdentificadoresEventosEmpregador']['version'];
191
        if (empty($operationVersion)) {
192
            throw new \InvalidArgumentException(
193
                'Schemas não localizados, verifique de passou as versões '
194
                    . 'corretamente no config.'
195
            );
196
        }
197
        $this->method = 'ConsultarIdentificadoresEventosEmpregador';
198
        $verWsdl = $this->serviceXsd['WsConsultarIdentificadoresEventos']['version'];
199
        $this->action = "{$this->namespace}/empregador/consulta/identificadores-eventos/"
200
        . "$verWsdl/ServicoConsultarIdentificadoresEventos/{$this->method}";
201
        
202
        $this->uri = $this->urlbase['identificadores'];
203
        
204
        $this->envelopeXmlns = [
205
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
206
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
207
            . "consulta/identificadores-eventos/$verWsdl",
208
        ];
209
        
210
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/consulta/"
211
            . "identificadores-eventos/empregador/"
212
            . $operationVersion . "\" "
213
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
214
            . "<consultaIdentificadoresEvts>"
215
            . "<ideEmpregador>"
216
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
217
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
218
            . "</ideEmpregador>"
219
            . "<consultaEvtsEmpregador>"
220
            . "<tpEvt>$tpEvt</tpEvt>"
221
            . "<perApur>$perapur</perApur>"
222
            . "</consultaEvtsEmpregador>"
223
            . "</consultaIdentificadoresEvts>"
224
            . "</eSocial>";
225
        
226
        $request = $this->sign($request);
227
        
228
        //validar a requisição conforme o seu respectivo XSD
229
        Validator::isValid(
230
            $request,
231
            $this->path
232
            ."schemes/comunicacao/$this->serviceStr/"
233
            ."ConsultaIdentificadoresEventosEmpregador-$operationVersion.xsd"
234
        );
235
        
236
        $body = "<v1:{$this->method}>"
237
            . "<v1:consultaEventosEmpregador>"
238
            . $request
239
            . "</v1:consultaEventosEmpregador>"
240
            . "</v1:{$this->method}>";
241
        
242
        $this->lastRequest  = $body;
243
        $this->lastResponse = $this->sendRequest($body);
244
        return $this->lastResponse;
245
    }
246
    
247
    /**
248
     * Events Identification tables query
249
     * @param string $tpEvt
250
     * @param string $chEvt
251
     * @param string $dtIni
252
     * @param string $dtFim
253
     * @return string
254
     * @throws InvalidArgumentException
255
     */
256
    public function consultarEventosTabela($tpEvt, $chEvt = null, $dtIni = null, $dtFim = null)
257
    {
258
        $operationVersion = $this->serviceXsd['ConsultaIdentificadoresEventosTabela']['version'];
259
        if (empty($operationVersion)) {
260
            throw new \InvalidArgumentException(
261
                'Schemas não localizados, verifique de passou as versões '
262
                    . 'corretamente no config.'
263
            );
264
        }
265
        $this->method = 'ConsultarIdentificadoresEventosTabela';
266
        $verWsdl = $this->serviceXsd['WsConsultarIdentificadoresEventos']['version'];
267
        $this->action = "{$this->namespace}/empregador/consulta/identificadores-eventos/"
268
        . "$verWsdl/ServicoConsultarIdentificadoresEventos/{$this->method}";
269
270
        $this->uri = $this->urlbase['identificadores'];
271
        
272
        $this->envelopeXmlns = [
273
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
274
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
275
            . "consulta/identificadores-eventos/$verWsdl",
276
        ];
277
        
278
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/consulta/"
279
            . "identificadores-eventos/tabela/"
280
            . $operationVersion . "\" "
281
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
282
            . "<consultaIdentificadoresEvts>"
283
            . "<ideEmpregador>"
284
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
285
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
286
            . "</ideEmpregador>"
287
            . "<consultaEvtsTabela>"
288
            . "<tpEvt>$tpEvt</tpEvt>";
289
        
290
        $request .= !empty($chEvt) ? "<chEvt>$chEvt</chEvt>" : "";
291
        $request .= !empty($dtIni) ? "<dtIni>$dtIni</dtIni>" : "";
292
        $request .= !empty($dtFim) ? "<dtFim>$dtFim</dtFim>" : "";
293
        
294
        $request .= "</consultaEvtsTabela>"
295
            . "</consultaIdentificadoresEvts>"
296
            . "</eSocial>";
297
        
298
        $request = $this->sign($request);
299
        
300
        //validar a requisição conforme o seu respectivo XSD
301
        Validator::isValid(
302
            $request,
303
            $this->path
304
            ."schemes/comunicacao/$this->serviceStr/"
305
            ."ConsultaIdentificadoresEventosTabela-$operationVersion.xsd"
306
        );
307
        
308
        $body = "<v1:{$this->method}>"
309
            ."<v1:consultaEventosTabela>"
310
            .$request
311
            ."</v1:consultaEventosTabela>"
312
            ."</v1:{$this->method}>";
313
            
314
        $this->lastRequest  = $body;
315
        $this->lastResponse = $this->sendRequest($body);
316
        return $this->lastResponse;
317
    }
318
    
319
    /**
320
     * Events Identification employee query
321
     * @param string $cpfTrab
322
     * @param string $dtIni
323
     * @param string $dtFim
324
     * @return string
325
     * @throws InvalidArgumentException
326
     */
327
    public function consultarEventosTrabalhador($cpfTrab, $dtIni, $dtFim)
328
    {
329
        $operationVersion = $this->serviceXsd['ConsultaIdentificadoresEventosTrabalhador']['version'];
330
        if (empty($operationVersion)) {
331
            throw new \InvalidArgumentException(
332
                'Schemas não localizados, verifique de passou as versões '
333
                    . 'corretamente no config.'
334
            );
335
        }
336
        $this->method = 'ConsultarIdentificadoresEventosTrabalhador';
337
        $verWsdl = $this->serviceXsd['WsConsultarIdentificadoresEventos']['version'];
338
        $this->action = "{$this->namespace}/empregador/consulta/identificadores-eventos/"
339
        . "$verWsdl/ServicoConsultarIdentificadoresEventos/{$this->method}";
340
341
        $this->uri = $this->urlbase['identificadores'];
342
        
343
        $this->envelopeXmlns = [
344
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
345
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
346
            . "consulta/identificadores-eventos/$verWsdl",
347
        ];
348
        
349
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/consulta/"
350
            . "identificadores-eventos/trabalhador/"
351
            . $operationVersion . "\" "
352
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
353
            . "<consultaIdentificadoresEvts>"
354
            . "<ideEmpregador>"
355
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
356
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
357
            . "</ideEmpregador>"
358
            . "<consultaEvtsTrabalhador>"
359
            . "<cpfTrab>$cpfTrab</cpfTrab>"
360
            . "<dtIni>$dtIni</dtIni>"
361
            . "<dtFim>$dtFim</dtFim>"
362
            . "</consultaEvtsTrabalhador>"
363
            . "</consultaIdentificadoresEvts>"
364
            . "</eSocial>";
365
366
        $request = $this->sign($request);
367
        
368
        //validar a requisição conforme o seu respectivo XSD
369
        Validator::isValid(
370
            $request,
371
            $this->path
372
            ."schemes/comunicacao/$this->serviceStr/"
373
            ."ConsultaIdentificadoresEventosTrabalhador-$operationVersion.xsd"
374
        );
375
        
376
        $body = "<v1:{$this->method}>"
377
            ."<v1:consultaEventosTabela>"
378
            .$request
379
            ."</v1:consultaEventosTabela>"
380
            ."</v1:{$this->method}>";
381
            
382
        $this->lastRequest  = $body;
383
        $this->lastResponse = $this->sendRequest($body);
384
        return $this->lastResponse;
385
    }
386
    
387
    /**
388
     * Download Event by Id
389
     * @param array $ids
390
     * @return string
391
     * @throws InvalidArgumentException
392
     */
393
    public function downloadEventosPorId($ids)
394
    {
395
        $operationVersion = $this->serviceXsd['SolicitacaoDownloadEventosPorId']['version'];
396
        if (empty($operationVersion)) {
397
            throw new \InvalidArgumentException(
398
                'Schemas não localizados, verifique de passou as versões '
399
                    . 'corretamente no config.'
400
            );
401
        }
402
403
        $this->method = 'SolicitarDownloadEventosPorId';
404
        $verWsdl = $this->serviceXsd['WsSolicitarDownloadEventos']['version'];
405
        $this->action = "{$this->namespace}/empregador/download/"
406
        . "solicitacao/$verWsdl/ServicoSolicitarDownloadEventos/{$this->method}";
407
        
408
        $this->uri = $this->urlbase['downloads'];
409
        
410
        $this->envelopeXmlns = [
411
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
412
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
413
            . "download/solicitacao/$verWsdl",
414
        ];
415
        
416
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/download/"
417
            . "solicitacao/id/$operationVersion\" "
418
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
419
            . "<download>"
420
            . "<ideEmpregador>"
421
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
422
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
423
            . "</ideEmpregador>"
424
            . "<solicDownloadEvtsPorId>";
425
        foreach ($ids as $id) {
426
            $request .= "<id>$id</id>";
427
        }
428
        $request .= "</solicDownloadEvtsPorId>"
429
            . "</download>"
430
            . "</eSocial>";
431
        
432
        $request = $this->sign($request);
433
        
434
        //validar a requisição conforme o seu respectivo XSD
435
        Validator::isValid(
436
            $request,
437
            $this->path
438
            ."schemes/comunicacao/$this->serviceStr/"
439
            ."SolicitacaoDownloadEventosPorId-$operationVersion.xsd"
440
        );
441
        
442
        $body = "<v1:{$this->method}>"
443
            ."<v1:solicitacao>"
444
            .$request
445
            ."</v1:solicitacao>"
446
            ."</v1:{$this->method}>";
447
            
448
        $this->lastRequest  = $body;
449
        $this->lastResponse = $this->sendRequest($body);
450
        return $this->lastResponse;
451
    }
452
    
453
    /**
454
     * Download Event by receipt number
455
     * @param array $nrRecs
456
     * @return string
457
     * @throws InvalidArgumentException
458
     */
459
    public function downloadEventosPorNrRecibo($nrRecs)
460
    {
461
        $operationVersion = $this->serviceXsd['SolicitacaoDownloadEventosPorNrRecibo']['version'];
462
        if (empty($operationVersion)) {
463
            throw new \InvalidArgumentException(
464
                'Schemas não localizados, verifique de passou as versões '
465
                    . 'corretamente no config.'
466
            );
467
        }
468
469
        $this->method = 'SolicitarDownloadEventosPorNrRecibo';
470
        $verWsdl = $this->serviceXsd['WsSolicitarDownloadEventos']['version'];
471
        $this->action = "{$this->namespace}/empregador/download/"
472
        . "solicitacao/$verWsdl/ServicoSolicitarDownloadEventos/{$this->method}";
473
        
474
        $this->uri = $this->urlbase['downloads'];
475
        
476
        $this->envelopeXmlns = [
477
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
478
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
479
            . "download/solicitacao/$verWsdl",
480
        ];
481
        
482
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/download/"
483
            . "solicitacao/nrRecibo/$operationVersion\" "
484
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
485
            . "<download>"
486
            . "<ideEmpregador>"
487
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
488
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
489
            . "</ideEmpregador>"
490
            . "<solicDownloadEventosPorNrRecibo>";
491
        
492
        foreach ($nrRecs as $nrRec) {
493
            $request .= "<nrRec>$nrRec</nrRec>";
494
        }
495
        
496
        $request .= "</solicDownloadEventosPorNrRecibo>"
497
            . "</download>"
498
            . "</eSocial>";
499
        
500
        $request = $this->sign($request);
501
        
502
        //validar a requisição conforme o seu respectivo XSD
503
        Validator::isValid(
504
            $request,
505
            $this->path
506
            ."schemes/comunicacao/$this->serviceStr/"
507
            ."SolicitacaoDownloadEventosPorNrRecibo-$operationVersion.xsd"
508
        );
509
        
510
        $body = "<v1:{$this->method}>"
511
            ."<v1:solicitacao>"
512
            .$request
513
            ."</v1:solicitacao>"
514
            ."</v1:{$this->method}>";
515
            
516
        $this->lastRequest  = $body;
517
        $this->lastResponse = $this->sendRequest($body);
518
        return $this->lastResponse;
519
    }
520
521
    /**
522
     * Send request to webservice
523
     * @param  string $request
524
     * @return string
525
     */
526
    protected function sendRequest($request)
527
    {
528
        if (empty($this->soap)) {
529
            $this->soap = new SoapCurl($this->certificate);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \NFePHP\eSocial\Comm...url($this->certificate) of type object<NFePHP\eSocial\Common\Soap\SoapCurl> is incompatible with the declared type object<NFePHP\Common\Soap\SoapInterface> of property $soap.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
530
        }
531
        $envelope = "<soapenv:Envelope ";
532
        foreach ($this->envelopeXmlns as $key => $xmlns) {
533
            $envelope .= "$key = \"$xmlns\" ";
534
        }
535
        $envelope .= ">"
536
            ."<soapenv:Header/>"
537
            ."<soapenv:Body>"
538
            .$request
539
            ."</soapenv:Body>"
540
            ."</soapenv:Envelope>";
541
        
542
        $msgSize    = strlen($envelope);
543
        $parameters = [
544
            "Content-Type: text/xml;charset=UTF-8",
545
            "SOAPAction: \"$this->action\"",
546
            "Content-length: $msgSize",
547
        ];
548
        return (string) $this->soap->send(
549
            $this->method,
550
            $this->uri,
551
            $this->action,
552
            $envelope,
553
            $parameters
554
        );
555
    }
556
557
    /**
558
     * Send batch of events
559
     * @param  integer $grupo
560
     * @param  array $eventos
561
     * @return string
562
     */
563
    public function enviarLoteEventos($grupo, $eventos = [])
564
    {
565
        if (empty($eventos)) {
566
            return '';
567
        }
568
        $xml  = "";
569
        $nEvt = count($eventos);
570
        if ($nEvt > 50) {
571
            throw new InvalidArgumentException(
572
                "O numero máximo de eventos em um lote é 50, "
573
                ."você está tentando enviar $nEvt eventos !"
574
            );
575
        }
576
        foreach ($eventos as $evt) {
577
            //verifica se o evento pertence ao grupo indicado
578
            if (! in_array($evt->alias(), $this->grupos[$grupo])) {
579
                throw new RuntimeException(
580
                    'O evento ' . $evt->alias() . ' não pertence a este grupo [ '
581
                    . $this->eventGroup[$grupo] . ' ].'
582
                );
583
            }
584
            $this->checkCertificate($evt);
585
            $xml .= "<evento Id=\"$evt->evtid\">";
586
            $xml .= $evt->toXML();
587
            $xml .= "</evento>";
588
        }
589
        $operationVersion = $this->serviceXsd['EnvioLoteEventos']['version'];
590
        if (empty($operationVersion)) {
591
            throw new \InvalidArgumentException(
592
                'Schemas não localizados, verifique de passou as versões '
593
                    . 'corretamente no config.'
594
            );
595
        }
596
        $verWsdl = $this->serviceXsd['WsEnviarLoteEventos']['version'];
597
        $this->method = "EnviarLoteEventos";
598
        $this->action = "http://www.esocial.gov.br/servicos/empregador/lote"
599
            . "/eventos/envio/"
600
            . $verWsdl
601
            . "/ServicoEnviarLoteEventos"
602
            . "/EnviarLoteEventos";
603
        $this->uri = $this->urlbase['envio'];
604
        $this->envelopeXmlns = [
605
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
606
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador"
607
                . "/lote/eventos/envio/$verWsdl",
608
        ];
609
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/lote"
610
            . "/eventos/envio/$operationVersion\" "
611
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
612
            . "<envioLoteEventos grupo=\"$grupo\">"
613
            . "<ideEmpregador>"
614
            . "<tpInsc>$this->tpInsc</tpInsc>"
615
            . "<nrInsc>$this->nrInsc</nrInsc>"
616
            . "</ideEmpregador>"
617
            . "<ideTransmissor>"
618
            . "<tpInsc>$this->transmissortpInsc</tpInsc>"
619
            . "<nrInsc>$this->transmissornrInsc</nrInsc>"
620
            . "</ideTransmissor>"
621
            . "<eventos>"
622
            . "$xml"
623
            . "</eventos>"
624
            . "</envioLoteEventos>"
625
            . "</eSocial>";
626
        //validar a requisição conforme o seu respectivo XSD
627
        Validator::isValid(
628
            $request,
629
            $this->path
630
            . "schemes/comunicacao/$this->serviceStr/"
631
            . "EnvioLoteEventos-$operationVersion.xsd"
632
        );
633
        $body = "<v1:EnviarLoteEventos>"
634
            . "<v1:loteEventos>"
635
            . $request
636
            . "</v1:loteEventos>"
637
            . "</v1:EnviarLoteEventos>";
638
        $this->lastRequest  = $body;
639
        $this->lastResponse = $this->sendRequest($body);
640
        return $this->lastResponse;
641
    }
642
643
    /**
644
     * Verify the availability of a digital certificate.
645
     * If available, place it where it is needed
646
     * @param  FactoryInterface $evento
647
     * @throws RuntimeException
648
     */
649
    protected function checkCertificate(FactoryInterface $evento)
650
    {
651
        if (empty($this->certificate)) {
652
            //try to get certificate from event
653
            $certificate = $evento->getCertificate();
654
            if (empty($certificate)) {
655
                //oops no certificate avaiable
656
                throw new \RuntimeException("Não temos um certificado disponível!");
657
            }
658
            $this->certificate = $certificate;
659
        } else {
660
            $certificate = $evento->getCertificate();
661
            if (empty($certificate)) {
662
                $evento->setCertificate($this->certificate);
663
            }
664
        }
665
    }
666
    
667
    protected function sign($request)
668
    {
669
        $sign = Signer::sign(
670
            $this->certificate,
671
            $request,
672
            'eSocial',
673
            '',
674
            OPENSSL_ALGO_SHA256,
675
            [true, false, null, null]
676
        );
677
        return str_replace(
678
            '<?xml version="1.0" encoding="UTF-8"?>',
679
            '',
680
            $sign
681
        );
682
    }
683
}
684