Passed
Push — master ( e67ebd...38ca54 )
by Roberto
02:37
created

Tools::consultarLoteEventos()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 47
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 0
cts 36
cp 0
rs 9.0303
c 0
b 0
f 0
cc 1
eloc 33
nc 1
nop 1
crap 2
1
<?php
2
3
namespace NFePHP\eSocial;
4
5
/**
6
 * Classe Tools, performs communication with the e-Social webservice
7
 *
8
 * @category  NFePHP
9
 * @package   NFePHP\eSocial\Tools
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 NFePHP\Common\Certificate;
18
use NFePHP\eSocial\Common\Tools as ToolsBase;
19
use NFePHP\eSocial\Common\FactoryInterface;
20
use NFePHP\eSocial\Common\Soap\SoapCurl;
21
use NFePHP\eSocial\Common\Soap\SoapInterface;
22
use NFePHP\Common\Validator;
23
use RuntimeException;
24
use InvalidArgumentException;
25
26
class Tools extends ToolsBase
27
{
28
    public $lastRequest;
29
    public $lastResponse;
30
    
31
    /**
32
     * @var NFePHP\Common\Soap\SoapInterface
33
     */
34
    protected $soap;
35
    protected $soapnamespaces = [
36
        'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
37
        'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema",
38
        'xmlns:soap' => "http://www.w3.org/2003/05/soap-envelope"
39
    ];
40
    protected $objHeader;
41
    protected $xmlns;
42
    protected $uri;
43
    protected $action;
44
    protected $method;
45
    protected $parameters;
46
    protected $envelopeXmlns;
47
48
49
50
    public function __construct($config, Certificate $certificate = null)
51
    {
52
        parent::__construct($config, $certificate);
53
    }
54
    
55
    /**
56
     * SOAP communication dependency injection
57
     * @param SoapInterface $soap
58
     */
59
    public function loadSoapClass(SoapInterface $soap)
60
    {
61
        $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\eSocial\NF...mon\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...
62
    }
63
    
64
    /**
65
     * Event batch query
66
     * @param string $protocolo
67
     * @return string
68
     */
69
    public function consultarLoteEventos($protocolo)
70
    {
71
        $operationVersion = $this->serviceXsd['ConsultaLoteEventos']['version'];
72
        
73
        $xmlns = "http://www.esocial.gov.br/servicos/empregador/lote/eventos"
0 ignored issues
show
Unused Code introduced by
$xmlns 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...
74
            . "/envio/consulta/retornoProcessamento/$operationVersion";
75
        
76
        $this->action = "http://www.esocial.gov.br/servicos/empregador/lote"
77
            . "/eventos/envio/consulta/retornoProcessamento/$operationVersion"
78
            . "/ServicoConsultarLoteEventos/ConsultarLoteEventos";
79
        
80
        $this->method = "ConsultarLoteEventos";
81
        
82
        $this->uri = "https://webservices.producaorestrita.esocial.gov.br"
83
            . "/servicos/empregador/consultarloteeventos"
84
            . "/WsConsultarLoteEventos.svc";
85
        
86
        $this->envelopeXmlns = [
87
            'xmlns:soapenv'=> "http://schemas.xmlsoap.org/soap/envelope/",
88
            'xmlns:v1'=> "http://www.esocial.gov.br/servicos/empregador/lote"
89
                . "/eventos/envio/consulta/retornoProcessamento/$operationVersion"
90
        ];
91
        
92
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/lote"
93
            . "/eventos/envio/consulta/retornoProcessamento/$operationVersion\" "
94
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
95
            . "<consultaLoteEventos>"
96
            . "<protocoloEnvio>$protocolo</protocoloEnvio>"
97
            . "</consultaLoteEventos>"
98
            . "</eSocial>";
99
        
100
        
101
        //validar a requisição conforme o seu respectivo XSD
102
        Validator::isValid($request, $this->path
103
            . "schemes/comunicacao/$this->serviceStr/"
104
            . "ConsultaLoteEventos-$operationVersion.xsd");
105
        
106
        $body = "<v1:ConsultarLoteEventos>"
107
            . "<v1:consulta>"
108
            . $request
109
            . "</v1:consulta>"
110
            . "</v1:ConsultarLoteEventos>";
111
        
112
        $this->lastRequest = $body;
113
        $this->lastResponse = $this->sendRequest($body);
114
        return $this->lastResponse;
115
    }
116
    
117
    /**
118
     * Send batch of events
119
     * @param integer $grupo
120
     * @param array $eventos
121
     * @return string
122
     */
123
    public function enviarLoteEventos($grupo, $eventos = [])
124
    {
125
        if (empty($eventos)) {
126
            return '';
127
        }
128
        $xml = "";
129
        $nEvt = count($eventos);
130
        if ($nEvt > 50) {
131
            throw new InvalidArgumentException(
132
                "O numero máximo de eventos em um lote é 50, "
133
                . "você está tentando enviar $nEvt eventos !"
134
            );
135
        }
136
        foreach ($eventos as $evt) {
137
            //verifica se o evento pertence ao grupo indicado
138
            if (!in_array($evt->alias(), $this->grupos[$grupo])) {
139
                throw new RuntimeException(
140
                    'O evento '. $evt->alias() . ' não pertence a este grupo [ '
141
                    . $this->eventGroup[$grupo] . ' ].'
142
                );
143
            }
144
            $this->checkCertificate($evt);
145
            $xml .= "<evento Id=\"$evt->evtid\">";
146
            $xml .= $evt->toXML();
147
            $xml .= "</evento>";
148
        }
149
        
150
        $operationVersion = $this->serviceXsd['EnvioLoteEventos']['version'];
151
        
152
        $xmlns = "http://www.esocial.gov.br/servicos/empregador/lote/eventos"
0 ignored issues
show
Unused Code introduced by
$xmlns 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...
153
            . "/envio/$operationVersion";
154
        
155
        $this->method = "EnviarLoteEventos";
156
        
157
        $this->action = "http://www.esocial.gov.br/servicos/empregador/lote"
158
            . "/eventos/envio/v1_1_0/ServicoEnviarLoteEventos"
159
            . "/EnviarLoteEventos";
160
        
161
        $this->uri = "https://webservices.producaorestrita.esocial.gov.br"
162
            . "/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc";
163
        
164
        $this->envelopeXmlns = [
165
            'xmlns:soapenv'=> "http://schemas.xmlsoap.org/soap/envelope/",
166
            'xmlns:v1'=> "http://www.esocial.gov.br/servicos/empregador"
167
                . "/lote/eventos/envio/$operationVersion"
168
        ];
169
        
170
        $request = "<eSocial xmlns=\"http://www.esocial.gov.br/schema/lote"
171
            . "/eventos/envio/$operationVersion\" "
172
            . "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
173
            . "<envioLoteEventos grupo=\"$grupo\">"
174
            . "<ideEmpregador>"
175
            . "<tpInsc>$this->tpInsc</tpInsc>"
176
            . "<nrInsc>$this->nrInsc</nrInsc>"
177
            . "</ideEmpregador>"
178
            . "<ideTransmissor>"
179
            . "<tpInsc>$this->transmissortpInsc</tpInsc>"
180
            . "<nrInsc>$this->transmissornrInsc</nrInsc>"
181
            . "</ideTransmissor>"
182
            . "<eventos>"
183
            . "$xml"
184
            . "</eventos>"
185
            . "</envioLoteEventos>"
186
            . "</eSocial>";
187
188
        //validar a requisição conforme o seu respectivo XSD
189
        Validator::isValid($request, $this->path
190
            . "schemes/comunicacao/$this->serviceStr/"
191
            . "EnvioLoteEventos-$operationVersion.xsd");
192
        
193
        $body = "<v1:EnviarLoteEventos>"
194
            . "<v1:loteEventos>"
195
            . $request
196
            . "</v1:loteEventos>"
197
            . "</v1:EnviarLoteEventos>";
198
        
199
        $this->lastRequest = $body;
200
        $this->lastResponse = $this->sendRequest($body);
201
        return $this->lastResponse;
202
    }
203
    
204
    /**
205
     * Send request to webservice
206
     * @param string $request
207
     * @return string
208
     */
209
    protected function sendRequest($request)
210
    {
211
        if (empty($this->soap)) {
212
            $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\eSocial\NF...mon\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...
213
        }
214
        
215
        $envelope = "<soapenv:Envelope ";
216
        foreach ($this->envelopeXmlns as $key => $xmlns) {
217
            $envelope .= "$key = \"$xmlns\" ";
218
        }
219
        $envelope .= ">"
220
            . "<soapenv:Header/>"
221
            . "<soapenv:Body>"
222
            . $request
223
            . "</soapenv:Body>"
224
            . "</soapenv:Envelope>";
225
        
226
        $msgSize = strlen($envelope);
227
        $parameters = [
228
            "Content-Type: text/xml;charset=UTF-8",
229
            "SOAPAction: \"$this->action\"",
230
            "Content-length: $msgSize"
231
        ];
232
        
233
        //return $envelope;
234
        return (string) $this->soap->send(
235
            $this->method,
236
            $this->uri,
237
            $this->action,
238
            $envelope,
239
            $parameters
240
        );
241
    }
242
243
244
    /**
245
     * Verify the availability of a digital certificate.
246
     * If available, place it where it is needed
247
     * @param FactoryInterface $evento
248
     * @throws RuntimeException
249
     */
250
    protected function checkCertificate(FactoryInterface $evento)
251
    {
252
        if (empty($this->certificate)) {
253
            //try to get certificate from event
254
            $certificate = $evento->getCertificate();
255
            if (empty($certificate)) {
256
                //oops no certificate avaiable
257
                throw new \RuntimeException("Não temos um certificado disponível!");
258
            }
259
            $this->certificate = $certificate;
260
        } else {
261
            $certificate = $evento->getCertificate();
262
            if (empty($certificate)) {
263
                $evento->setCertificate($this->certificate);
264
            }
265
        }
266
    }
267
}
268