Completed
Push — master ( 0882ab...f5ef34 )
by Roberto
05:21 queued 02:33
created

Tools   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 620
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 3
dl 0
loc 620
ccs 0
cts 438
cp 0
rs 9.98
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 27 2
A loadSoapClass() 0 4 1
A consultarLoteEventos() 0 45 2
B consultarEventosEmpregador() 0 56 2
B consultarEventosTabela() 0 58 2
B consultarEventosTrabalhador() 0 57 2
B downloadEventosPorId() 0 55 2
B downloadEventosPorNrRecibo() 0 55 2
A sendRequest() 0 29 3
B enviarLoteEventos() 0 79 6
A checkCertificate() 0 17 4
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\eSocial\Common\FactoryInterface;
21
use NFePHP\eSocial\Common\Soap\SoapCurl;
22
use NFePHP\eSocial\Common\Soap\SoapInterface;
23
use NFePHP\eSocial\Common\Tools as ToolsBase;
24
use RuntimeException;
25
26
class Tools extends ToolsBase
27
{
28
    /**
29
     * @var string
30
     */
31
    public $lastRequest;
32
    /**
33
     * @var string
34
     */
35
    public $lastResponse;
36
    /**
37
     * @var \NFePHP\Common\Soap\SoapInterface
38
     */
39
    protected $soap;
40
    /**
41
     * @var array
42
     */
43
    protected $soapnamespaces = [
44
        'xmlns:xsi'  => "http://www.w3.org/2001/XMLSchema-instance",
45
        'xmlns:xsd'  => "http://www.w3.org/2001/XMLSchema",
46
        'xmlns:soap' => "http://www.w3.org/2003/05/soap-envelope",
47
    ];
48
    /**
49
     * @var \SoapHeader
50
     */
51
    protected $objHeader;
52
    /**
53
     * @var string
54
     */
55
    protected $xmlns;
56
    /**
57
     * @var string
58
     */
59
    protected $uri;
60
    /**
61
     * @var string
62
     */
63
    protected $action;
64
    /**
65
     * @var string
66
     */
67
    protected $method;
68
    /**
69
     * @var array
70
     */
71
    protected $parameters;
72
    /**
73
     * @var array
74
     */
75
    protected $envelopeXmlns;
76
    /**
77
     * @var array
78
     */
79
    protected $urlbase;
80
    /**
81
     * @var string
82
     */
83
    protected $namespace = 'http://www.esocial.gov.br/servicos';
84
85
86
    /**
87
     * Constructor
88
     * @param string $config
89
     * @param Certificate $certificate
90
     */
91
    public function __construct($config, Certificate $certificate)
92
    {
93
        parent::__construct($config, $certificate);
94
        //define o ambiente a ser usado
95
        $this->urlbase = [
96
            'consulta' =>  'https://webservices.producaorestrita.esocial.gov.br/'
97
            . 'servicos/empregador/consultarloteeventos/WsConsultarLoteEventos.svc',
98
            'envio' => 'https://webservices.producaorestrita.esocial.gov.br/'
99
            . 'servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc',
100
            'identificadores' => 'https://webservices.producaorestrita.esocial.gov.br/'
101
            . 'servicos/empregador/dwlcirurgico/WsConsultarIdentificadoresEventos.svc',
102
            'downloads' => 'https://webservices.producaorestrita.esocial.gov.br/'
103
            . 'servicos/empregador/dwlcirurgico/WsSolicitarDownloadEventos.svc'
104
        ];
105
        if ($this->tpAmb == 1) {
106
            $this->urlbase = [
107
                'consulta' =>  'https://webservices.consulta.esocial.gov.br/'
108
                . 'servicos/empregador/consultarloteeventos/WsConsultarLoteEventos.svc',
109
                'envio' => 'https://webservices.envio.esocial.gov.br/'
110
                . 'servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc',
111
                'identificadores' => 'https://webservices.download.esocial.gov.br/'
112
                . 'servicos/empregador/dwlcirurgico/WsConsultarIdentificadoresEventos.svc',
113
                'downloads' => 'https://webservices.download.esocial.gov.br/'
114
                . 'servicos/empregador/dwlcirurgico/WsSolicitarDownloadEventos.svc'
115
            ];
116
        }
117
    }
118
119
    /**
120
     * SOAP communication dependency injection
121
     * @param SoapInterface $soap
122
     */
123
    public function loadSoapClass(SoapInterface $soap)
124
    {
125
        $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...
126
    }
127
128
    /**
129
     * Event batch query
130
     * @param  string $protocolo
131
     * @return string
132
     */
133
    public function consultarLoteEventos($protocolo)
134
    {
135
        $operationVersion = $this->serviceXsd['ConsultaLoteEventos']['version'];
136
        if (empty($operationVersion)) {
137
            throw new \InvalidArgumentException(
138
                'Schemas não localizados, verifique de passou as versões '
139
                    . 'corretamente no config.'
140
            );
141
        }
142
        $verWsdl = $this->serviceXsd['WsConsultarLoteEventos']['version'];
143
        $this->action = "{$this->namespace}/empregador/lote"
144
            ."/eventos/envio/consulta/retornoProcessamento/$verWsdl"
145
            ."/ServicoConsultarLoteEventos/ConsultarLoteEventos";
146
        
147
        $this->method = "ConsultarLoteEventos";
148
        $this->uri = $this->urlbase['consulta'];
149
        $this->envelopeXmlns = [
150
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
151
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/lote"
152
                ."/eventos/envio/consulta/retornoProcessamento/$verWsdl",
153
        ];
154
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/lote"
155
            ."/eventos/envio/consulta/retornoProcessamento/"
156
            . $operationVersion . "\" "
157
            ."xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
158
            ."<consultaLoteEventos>"
159
            ."<protocoloEnvio>$protocolo</protocoloEnvio>"
160
            ."</consultaLoteEventos>"
161
            ."</eSocial>";
162
        //validar a requisição conforme o seu respectivo XSD
163
        Validator::isValid(
164
            $request,
165
            $this->path
166
            ."schemes/comunicacao/$this->serviceStr/"
167
            ."ConsultaLoteEventos-$operationVersion.xsd"
168
        );
169
        $body = "<v1:ConsultarLoteEventos>"
170
            ."<v1:consulta>"
171
            .$request
172
            ."</v1:consulta>"
173
            ."</v1:ConsultarLoteEventos>";
174
        $this->lastRequest  = $body;
175
        $this->lastResponse = $this->sendRequest($body);
176
        return $this->lastResponse;
177
    }
178
    
179
    /**
180
     * Events Identification employer query
181
     * @param string $tpEvt
182
     * @param string $perapur
183
     * @return string
184
     * @throws InvalidArgumentException
185
     */
186
    public function consultarEventosEmpregador($tpEvt, $perapur)
187
    {
188
        $operationVersion = $this->serviceXsd['ConsultaIdentificadoresEventosEmpregador']['version'];
189
        if (empty($operationVersion)) {
190
            throw new \InvalidArgumentException(
191
                'Schemas não localizados, verifique de passou as versões '
192
                    . 'corretamente no config.'
193
            );
194
        }
195
        $this->method = 'ConsultarIdentificadoresEventosEmpregador';
196
        $verWsdl = $this->serviceXsd['WsConsultarIdentificadoresEventos']['version'];
197
        $this->action = "{$this->namespace}/empregador/consulta/identificadores-eventos/"
198
        . "$verWsdl/ServicoConsultarIdentificadoresEventos/{$this->method}";
199
        
200
        $this->uri = $this->urlbase['identificadores'];
201
        
202
        $this->envelopeXmlns = [
203
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
204
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
205
            . "consulta/identificadores-eventos/$verWsdl",
206
        ];
207
        
208
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/consulta/"
209
            . "identificadores-eventos/empregador/"
210
            . $operationVersion . "\" "
211
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
212
            . "<consultaIdentificadoresEvts>"
213
            . "<ideEmpregador>"
214
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
215
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
216
            . "</ideEmpregador>"
217
            . "<consultaEvtsEmpregador>"
218
            . "<tpEvt>$tpEvt</tpEvt>"
219
            . "<perApur>$perapur</perApur>"
220
            . "</consultaEvtsEmpregador>"
221
            . "</consultaIdentificadoresEvts>"
222
            . "</eSocial>";
223
            
224
        //validar a requisição conforme o seu respectivo XSD
225
        Validator::isValid(
226
            $request,
227
            $this->path
228
            ."schemes/comunicacao/$this->serviceStr/"
229
            ."ConsultaIdentificadoresEventosEmpregador-$operationVersion.xsd"
230
        );
231
        
232
        $body = "<v1:{$this->method}>"
233
            ."<v1:consultaEventosEmpregador>"
234
            .$request
235
            ."</v1:consultaEventosEmpregador>"
236
            ."</v1:{$this->method}>";
237
            
238
        $this->lastRequest  = $body;
239
        $this->lastResponse = $this->sendRequest($body);
240
        return $this->lastResponse;
241
    }
242
    
243
    /**
244
     * Events Identification tables query
245
     * @param string $tpEvt
246
     * @param string $chEvt
247
     * @param string $dtIni
248
     * @param string $dtFim
249
     * @return string
250
     * @throws InvalidArgumentException
251
     */
252
    public function consultarEventosTabela($tpEvt, $chEvt, $dtIni, $dtFim)
253
    {
254
        $operationVersion = $this->serviceXsd['ConsultaIdentificadoresEventosTabela']['version'];
255
        if (empty($operationVersion)) {
256
            throw new \InvalidArgumentException(
257
                'Schemas não localizados, verifique de passou as versões '
258
                    . 'corretamente no config.'
259
            );
260
        }
261
        $this->method = 'ConsultarIdentificadoresEventosTabela';
262
        $verWsdl = $this->serviceXsd['WsConsultarIdentificadoresEventos']['version'];
263
        $this->action = "{$this->namespace}/empregador/consulta/identificadores-eventos/"
264
        . "$verWsdl/ServicoConsultarIdentificadoresEventos/{$this->method}";
265
266
        $this->uri = $this->urlbase['identificadores'];
267
        
268
        $this->envelopeXmlns = [
269
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
270
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
271
            . "consulta/identificadores-eventos/$verWsdl",
272
        ];
273
        
274
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/consulta/"
275
            . "identificadores-eventos/empregador/"
276
            . $operationVersion . "\" "
277
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
278
            . "<consultaIdentificadoresEvts>"
279
            . "<ideEmpregador>"
280
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
281
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
282
            . "</ideEmpregador>"
283
            . "<consultaEvtsTabela>"
284
            . "<tpEvt>$tpEvt</tpEvt>"
285
            . "<chEvt>$chEvt</chEvt>"
286
            . "<dtIni>$dtIni</dtIni>"
287
            . "<dtFim>$dtFim</dtFim>"
288
            . "</consultaEvtsTabela>"
289
            . "</consultaIdentificadoresEvts>"
290
            . "</eSocial>";
291
            
292
        //validar a requisição conforme o seu respectivo XSD
293
        Validator::isValid(
294
            $request,
295
            $this->path
296
            ."schemes/comunicacao/$this->serviceStr/"
297
            ."ConsultaIdentificadoresEventosTabela-$operationVersion.xsd"
298
        );
299
        
300
        $body = "<v1:{$this->method}>"
301
            ."<v1:consultaEventosTabela>"
302
            .$request
303
            ."</v1:consultaEventosTabela>"
304
            ."</v1:{$this->method}>";
305
            
306
        $this->lastRequest  = $body;
307
        $this->lastResponse = $this->sendRequest($body);
308
        return $this->lastResponse;
309
    }
310
    
311
    /**
312
     * Events Identification employee query
313
     * @param string $cpfTrab
314
     * @param string $dtIni
315
     * @param string $dtFim
316
     * @return string
317
     * @throws InvalidArgumentException
318
     */
319
    public function consultarEventosTrabalhador($cpfTrab, $dtIni, $dtFim)
320
    {
321
        $operationVersion = $this->serviceXsd['ConsultaIdentificadoresEventosTrabalhador']['version'];
322
        if (empty($operationVersion)) {
323
            throw new \InvalidArgumentException(
324
                'Schemas não localizados, verifique de passou as versões '
325
                    . 'corretamente no config.'
326
            );
327
        }
328
        $this->method = 'ConsultarIdentificadoresEventosTrabalhador';
329
        $verWsdl = $this->serviceXsd['WsConsultarIdentificadoresEventos']['version'];
330
        $this->action = "{$this->namespace}/empregador/consulta/identificadores-eventos/"
331
        . "$verWsdl/ServicoConsultarIdentificadoresEventos/{$this->method}";
332
333
        $this->uri = $this->urlbase['identificadores'];
334
        
335
        $this->envelopeXmlns = [
336
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
337
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
338
            . "consulta/identificadores-eventos/$verWsdl",
339
        ];
340
        
341
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/consulta/"
342
            . "identificadores-eventos/empregador/"
343
            . $operationVersion . "\" "
344
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
345
            . "<consultaIdentificadoresEvts>"
346
            . "<ideEmpregador>"
347
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
348
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
349
            . "</ideEmpregador>"
350
            . "<consultaEvtsTrabalhador>"
351
            . "<cpfTrab>$cpfTrab</cpfTrab>"
352
            . "<dtIni>$dtIni</dtIni>"
353
            . "<dtFim>$dtFim</dtFim>"
354
            . "</consultaEvtsTrabalhador>"
355
            . "</consultaIdentificadoresEvts>"
356
            . "</eSocial>";
357
            
358
        //validar a requisição conforme o seu respectivo XSD
359
        Validator::isValid(
360
            $request,
361
            $this->path
362
            ."schemes/comunicacao/$this->serviceStr/"
363
            ."ConsultaIdentificadoresEventosTrabalhador-$operationVersion.xsd"
364
        );
365
        
366
        $body = "<v1:{$this->method}>"
367
            ."<v1:consultaEventosTabela>"
368
            .$request
369
            ."</v1:consultaEventosTabela>"
370
            ."</v1:{$this->method}>";
371
            
372
        $this->lastRequest  = $body;
373
        $this->lastResponse = $this->sendRequest($body);
374
        return $this->lastResponse;
375
    }
376
    
377
    /**
378
     * Download Event by Id
379
     * @param string $id
380
     * @return string
381
     * @throws InvalidArgumentException
382
     */
383
    public function downloadEventosPorId($id)
384
    {
385
        $operationVersion = $this->serviceXsd['SolicitacaoDownloadEventosPorId']['version'];
386
        if (empty($operationVersion)) {
387
            throw new \InvalidArgumentException(
388
                'Schemas não localizados, verifique de passou as versões '
389
                    . 'corretamente no config.'
390
            );
391
        }
392
393
        $this->method = 'SolicitarDownloadEventosPorId';
394
        $verWsdl = $this->serviceXsd['WsSolicitarDownloadEventos']['version'];
395
        $this->action = "{$this->namespace}/empregador/download/"
396
        . "solicitacao/$verWsdl/ServicoSolicitarDownloadEventos/{$this->method}";
397
        
398
        $this->uri = $this->urlbase['downloads'];
399
        
400
        $this->envelopeXmlns = [
401
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
402
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
403
            . "download/solicitacao/$verWsdl",
404
        ];
405
        
406
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/download/"
407
            . "solicitacao/id/$operationVersion \" "
408
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
409
            . "<download>"
410
            . "<ideEmpregador>"
411
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
412
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
413
            . "</ideEmpregador>"
414
            . "<solicDownloadEvtsPorId>"
415
            . "<id>$id</id>"
416
            . "</solicDownloadEvtsPorId>"
417
            . "</download>"
418
            . "</eSocial>";
419
        
420
        //validar a requisição conforme o seu respectivo XSD
421
        Validator::isValid(
422
            $request,
423
            $this->path
424
            ."schemes/comunicacao/$this->serviceStr/"
425
            ."SolicitacaoDownloadEventosPorId-$operationVersion.xsd"
426
        );
427
        
428
        $body = "<v1:{$this->method}>"
429
            ."<v1:solicitacao>"
430
            .$request
431
            ."</v1:solicitacao>"
432
            ."</v1:{$this->method}>";
433
            
434
        $this->lastRequest  = $body;
435
        $this->lastResponse = $this->sendRequest($body);
436
        return $this->lastResponse;
437
    }
438
    
439
    /**
440
     * Download Event by receipt number
441
     * @param string $nrRec
442
     * @return string
443
     * @throws InvalidArgumentException
444
     */
445
    public function downloadEventosPorNrRecibo($nrRec)
446
    {
447
        $operationVersion = $this->serviceXsd['SolicitacaoDownloadEventosPorNrRecibo']['version'];
448
        if (empty($operationVersion)) {
449
            throw new \InvalidArgumentException(
450
                'Schemas não localizados, verifique de passou as versões '
451
                    . 'corretamente no config.'
452
            );
453
        }
454
455
        $this->method = 'SolicitarDownloadEventosPorNrRecibo';
456
        $verWsdl = $this->serviceXsd['WsSolicitarDownloadEventos']['version'];
457
        $this->action = "{$this->namespace}/empregador/download/"
458
        . "solicitacao/$verWsdl/ServicoSolicitarDownloadEventos/{$this->method}";
459
        
460
        $this->uri = $this->urlbase['downloads'];
461
        
462
        $this->envelopeXmlns = [
463
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
464
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador/"
465
            . "download/solicitacao/$verWsdl",
466
        ];
467
        
468
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/download/"
469
            . "solicitacao/nrRecibo/$operationVersion \" "
470
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
471
            . "<download>"
472
            . "<ideEmpregador>"
473
            . "<tpInsc>{$this->tpInsc}</tpInsc>"
474
            . "<nrInsc>{$this->nrInsc}</nrInsc>"
475
            . "</ideEmpregador>"
476
            . "<solicDownloadEventosPorNrRecibo>"
477
            . "<nrRec>$nrRec</nrRec>"
478
            . "</solicDownloadEventosPorNrRecibo>"
479
            . "</download>"
480
            . "</eSocial>";
481
        
482
        //validar a requisição conforme o seu respectivo XSD
483
        Validator::isValid(
484
            $request,
485
            $this->path
486
            ."schemes/comunicacao/$this->serviceStr/"
487
            ."SolicitacaoDownloadEventosPorId-$operationVersion.xsd"
488
        );
489
        
490
        $body = "<v1:{$this->method}>"
491
            ."<v1:solicitacao>"
492
            .$request
493
            ."</v1:solicitacao>"
494
            ."</v1:{$this->method}>";
495
            
496
        $this->lastRequest  = $body;
497
        $this->lastResponse = $this->sendRequest($body);
498
        return $this->lastResponse;
499
    }
500
501
    /**
502
     * Send request to webservice
503
     * @param  string $request
504
     * @return string
505
     */
506
    protected function sendRequest($request)
507
    {
508
        if (empty($this->soap)) {
509
            $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...
510
        }
511
        $envelope = "<soapenv:Envelope ";
512
        foreach ($this->envelopeXmlns as $key => $xmlns) {
513
            $envelope .= "$key = \"$xmlns\" ";
514
        }
515
        $envelope .= ">"
516
            ."<soapenv:Header/>"
517
            ."<soapenv:Body>"
518
            .$request
519
            ."</soapenv:Body>"
520
            ."</soapenv:Envelope>";
521
        $msgSize    = strlen($envelope);
522
        $parameters = [
523
            "Content-Type: text/xml;charset=UTF-8",
524
            "SOAPAction: \"$this->action\"",
525
            "Content-length: $msgSize",
526
        ];
527
        return (string) $this->soap->send(
528
            $this->method,
529
            $this->uri,
530
            $this->action,
531
            $envelope,
532
            $parameters
533
        );
534
    }
535
536
    /**
537
     * Send batch of events
538
     * @param  integer $grupo
539
     * @param  array $eventos
540
     * @return string
541
     */
542
    public function enviarLoteEventos($grupo, $eventos = [])
543
    {
544
        if (empty($eventos)) {
545
            return '';
546
        }
547
        $xml  = "";
548
        $nEvt = count($eventos);
549
        if ($nEvt > 50) {
550
            throw new InvalidArgumentException(
551
                "O numero máximo de eventos em um lote é 50, "
552
                ."você está tentando enviar $nEvt eventos !"
553
            );
554
        }
555
        foreach ($eventos as $evt) {
556
            //verifica se o evento pertence ao grupo indicado
557
            if (! in_array($evt->alias(), $this->grupos[$grupo])) {
558
                throw new RuntimeException(
559
                    'O evento ' . $evt->alias() . ' não pertence a este grupo [ '
560
                    . $this->eventGroup[$grupo] . ' ].'
561
                );
562
            }
563
            $this->checkCertificate($evt);
564
            $xml .= "<evento Id=\"$evt->evtid\">";
565
            $xml .= $evt->toXML();
566
            $xml .= "</evento>";
567
        }
568
        $operationVersion = $this->serviceXsd['EnvioLoteEventos']['version'];
569
        if (empty($operationVersion)) {
570
            throw new \InvalidArgumentException(
571
                'Schemas não localizados, verifique de passou as versões '
572
                    . 'corretamente no config.'
573
            );
574
        }
575
        $verWsdl = $this->serviceXsd['WsEnviarLoteEventos']['version'];
576
        $this->method = "EnviarLoteEventos";
577
        $this->action = "http://www.esocial.gov.br/servicos/empregador/lote"
578
            . "/eventos/envio/"
579
            . $verWsdl
580
            . "/ServicoEnviarLoteEventos"
581
            . "/EnviarLoteEventos";
582
        $this->uri = $this->urlbase['envio'];
583
        $this->envelopeXmlns = [
584
            'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
585
            'xmlns:v1'      => "http://www.esocial.gov.br/servicos/empregador"
586
                . "/lote/eventos/envio/$verWsdl",
587
        ];
588
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/lote"
589
            . "/eventos/envio/$operationVersion\" "
590
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
591
            . "<envioLoteEventos grupo=\"$grupo\">"
592
            . "<ideEmpregador>"
593
            . "<tpInsc>$this->tpInsc</tpInsc>"
594
            . "<nrInsc>$this->nrInsc</nrInsc>"
595
            . "</ideEmpregador>"
596
            . "<ideTransmissor>"
597
            . "<tpInsc>$this->transmissortpInsc</tpInsc>"
598
            . "<nrInsc>$this->transmissornrInsc</nrInsc>"
599
            . "</ideTransmissor>"
600
            . "<eventos>"
601
            . "$xml"
602
            . "</eventos>"
603
            . "</envioLoteEventos>"
604
            . "</eSocial>";
605
        //validar a requisição conforme o seu respectivo XSD
606
        Validator::isValid(
607
            $request,
608
            $this->path
609
            . "schemes/comunicacao/$this->serviceStr/"
610
            . "EnvioLoteEventos-$operationVersion.xsd"
611
        );
612
        $body = "<v1:EnviarLoteEventos>"
613
            . "<v1:loteEventos>"
614
            . $request
615
            . "</v1:loteEventos>"
616
            . "</v1:EnviarLoteEventos>";
617
        $this->lastRequest  = $body;
618
        $this->lastResponse = $this->sendRequest($body);
619
        return $this->lastResponse;
620
    }
621
622
    /**
623
     * Verify the availability of a digital certificate.
624
     * If available, place it where it is needed
625
     * @param  FactoryInterface $evento
626
     * @throws RuntimeException
627
     */
628
    protected function checkCertificate(FactoryInterface $evento)
629
    {
630
        if (empty($this->certificate)) {
631
            //try to get certificate from event
632
            $certificate = $evento->getCertificate();
633
            if (empty($certificate)) {
634
                //oops no certificate avaiable
635
                throw new \RuntimeException("Não temos um certificado disponível!");
636
            }
637
            $this->certificate = $certificate;
638
        } else {
639
            $certificate = $evento->getCertificate();
640
            if (empty($certificate)) {
641
                $evento->setCertificate($this->certificate);
642
            }
643
        }
644
    }
645
}
646