Test Setup Failed
Push — master ( 9c6627...8f1eb9 )
by Roberto
02:19
created

Tools::sendRequest()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 36
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 0
cts 17
cp 0
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 28
nc 8
nop 1
crap 20
1
<?php
2
3
namespace NFePHP\EFDReinf;
4
5
/**
6
 * Classe Tools, performs communication with the EFDReinf webservice
7
 *
8
 * @category  API
9
 * @package   NFePHP\EFDReinf\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-efdreinf for the canonical source repository
16
 */
17
use NFePHP\Common\Certificate;
18
use NFePHP\Common\Validator;
19
use NFePHP\EFDReinf\Common\Tools as ToolsBase;
20
use NFePHP\EFDReinf\Common\FactoryInterface;
21
use NFePHP\EFDReinf\Common\Soap\SoapCurl;
22
use NFePHP\EFDReinf\Common\Soap\SoapInterface;
23
use NFePHP\EFDReinf\Exception\ProcessException;
24
25
class Tools extends ToolsBase
26
{
27
    /**
28
     * @var string
29
     */
30
    public $lastRequest;
31
    /**
32
     * @var string
33
     */
34
    public $lastResponse;
35
    /**
36
     * @var SoapInterface
37
     */
38
    protected $soap;
39
    /**
40
     * @var array
41
     */
42
    protected $soapnamespaces = [
43
        'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
44
        'xmlns:sped'=> "http://sped.fazenda.gov.br/"
45
    ];
46
    /**
47
     * @var array
48
     */
49
    protected $uri = [
50
        '1' => '',
51
        '2' => 'https://preprodefdreinf.receita.fazenda.gov.br/RecepcaoLoteReinf.svc',
52
        '3' => 'https://preprodefdreinf.receita.fazenda.gov.br/RecepcaoLoteReinf.svc'
53
    ];
54
    /**
55
     *
56
     * @var array
57
     */
58
    protected $uriconsulta = [
59
        '1' => '',
60
        '2' => 'https://preprodefdreinf.receita.fazenda.gov.br/ConsultasReinf.svc',
61
        '3' => 'https://preprodefdreinf.receita.fazenda.gov.br/ConsultasReinf.svc'
62
    ];
63
    /**
64
     * @var string
65
     */
66
    protected $action;
67
    /**
68
     * @var string
69
     */
70
    protected $method;
71
    
72
    /**
73
     * Constructor
74
     * @param string $config
75
     * @param Certificate $certificate
76
     */
77
    public function __construct($config, Certificate $certificate)
78
    {
79
        parent::__construct($config, $certificate);
80
    }
81
    
82
    /**
83
     * SOAP communication dependency injection
84
     * @param SoapInterface $soap
85
     */
86
    public function loadSoapClass(SoapInterface $soap)
87
    {
88
        $this->soap = $soap;
89
    }
90
    
91
    /**
92
     * Event batch query
93
     * @param string $recibofechamento
94
     * @return string
95
     */
96
    public function consultar($recibofechamento)
97
    {
98
        if (empty($recibofechamento)) {
99
            return '';
100
        }
101
        $this->method = "ConsultaInformacoesConsolidadas";
102
        $this->action = "http://sped.fazenda.gov.br/ConsultasReinf/".$this->method;
103
        $request = "<sped:tipoInscricaoContribuinte>$this->tpInsc</sped:tipoInscricaoContribuinte>";
104
        $request .= "<sped:numeroInscricaoContribuinte>$this->nrInsc</sped:numeroInscricaoContribuinte>";
105
        $request .= "<sped:numeroReciboFechamento>$recibofechamento</sped:numeroReciboFechamento>";
106
        $body = "<sped:ConsultaInformacoesConsolidadas>"
107
            . $request
108
            . "</sped:ConsultaInformacoesConsolidadas>";
109
        
110
        $this->lastResponse = $this->sendRequest($body);
111
        return $this->lastResponse;
112
    }
113
    
114
    /**
115
     * Send batch of events
116
     * @param array $eventos
117
     * @return string
118
     */
119
    public function enviarLoteEventos($eventos = [])
120
    {
121
        if (empty($eventos)) {
122
            return '';
123
        }
124
        //check number of events
125
        $nEvt = count($eventos);
126
        if ($nEvt > 100) {
127
            throw ProcessException::wrongArgument(2000, $nEvt);
128
        }
129
        $this->method = "ReceberLoteEventos";
130
        $this->action = "http://sped.fazenda.gov.br/RecepcaoLoteReinf/ReceberLoteEventos";
131
        $xml = "";
132
        foreach ($eventos as $evt) {
133
            if (!is_a($evt, '\NFePHP\EFDReinf\Common\FactoryInterface')) {
134
                throw ProcessException::wrongArgument(2002, '');
135
            }
136
            $this->checkCertificate($evt);
137
            $xml .= "<evento id=\"".$evt->getId()."\">";
138
            $xml .= $evt->toXML();
139
            $xml .= "</evento>";
140
        }
141
        //build request
142
        $request = "<Reinf xmlns=\"http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v"
143
            . $this->serviceVersion."\" >"
144
            . "<loteEventos>"
145
            . $xml
146
            . "</loteEventos>"
147
            . "</Reinf>";
148
        //validate requisition with XSD
149
        $xsd = $this->path
150
            . "schemes/comunicacao/v$this->serviceVersion/"
151
            . $this->serviceXsd['EnvioLoteEventos']['name'];
152
        Validator::isValid($request, $xsd);
153
        //build soap body
154
        $body = "<sped:ReceberLoteEventos>"
155
            . "<sped:loteEventos>"
156
            . $request
157
            . "</sped:loteEventos>"
158
            . "</sped:ReceberLoteEventos>";
159
        $this->lastResponse = $this->sendRequest($body);
160
        return $this->lastResponse;
161
    }
162
    
163
    /**
164
     * Send request to webservice
165
     * @param string $request
166
     * @return string
167
     */
168
    protected function sendRequest($request)
169
    {
170
        if (empty($this->soap)) {
171
            $this->soap = new SoapCurl($this->certificate);
172
        }
173
        $envelope = "<soapenv:Envelope ";
174
        foreach ($this->soapnamespaces as $key => $xmlns) {
175
            $envelope .= "$key = \"$xmlns\" ";
176
        }
177
        $envelope .= ">"
178
            . "<soapenv:Header/>"
179
            . "<soapenv:Body>"
180
            . $request
181
            . "</soapenv:Body>"
182
            . "</soapenv:Envelope>";
183
        
184
        $msgSize = strlen($envelope);
185
        $parameters = [
186
            "Content-Type: text/xml;charset=UTF-8",
187
            "SOAPAction: \"$this->action\"",
188
            "Content-length: $msgSize"
189
        ];
190
        if ($this->method == 'ReceberLoteEventos') {
191
            $url = $this->uri[$this->tpAmb];
192
        } else {
193
            $url = $this->uriconsulta[$this->tpAmb];
194
        }
195
        $this->lastRequest = $envelope;
196
        return (string) $this->soap->send(
197
            $this->method,
198
            $url,
199
            $this->action,
200
            $envelope,
201
            $parameters
202
        );
203
    }
204
205
    /**
206
     * Verify the availability of a digital certificate.
207
     * If available, place it where it is needed
208
     * @param FactoryInterface $evento
209
     * @throws RuntimeException
210
     */
211
    protected function checkCertificate(FactoryInterface $evento)
212
    {
213
        //try to get certificate from event
214
        $certificate = $evento->getCertificate();
215
        if (empty($certificate)) {
216
            $evento->setCertificate($this->certificate);
217
        }
218
    }
219
}
220