Passed
Push — master ( 43458c...ac6f10 )
by Francimar
03:09
created

Envio::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * MIT License
4
 *
5
 * Copyright (c) 2016 MZ Desenvolvimento de Sistemas LTDA
6
 *
7
 * @author Francimar Alves <[email protected]>
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
namespace NFe\Task;
29
30
use NFe\Core\Nota;
31
use NFe\Core\SEFAZ;
32
use NFe\Common\Node;
33
use NFe\Common\Util;
34
use NFe\Common\CurlSoap;
35
36
/**
37
 * Envia requisições para os servidores da SEFAZ
38
 */
39
class Envio
0 ignored issues
show
Complexity introduced by
This class has a complexity of 50 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
40
{
41
42
    /**
43
     * Tipo de serviço a ser executado
44
     */
45
    const SERVICO_INUTILIZACAO = 'inutilizacao';
46
    const SERVICO_PROTOCOLO = 'protocolo';
47
    const SERVICO_STATUS = 'status';
48
    const SERVICO_CADASTRO = 'cadastro';
49
    const SERVICO_AUTORIZACAO = 'autorizacao';
50
    const SERVICO_RETORNO = 'retorno';
51
    const SERVICO_RECEPCAO = 'recepcao';
52
    const SERVICO_CONFIRMACAO = 'confirmacao';
53
    const SERVICO_EVENTO = 'evento';
54
    const SERVICO_DESTINADAS = 'destinadas';
55
    const SERVICO_DOWNLOAD = 'download';
56
    const SERVICO_DISTRIBUICAO = 'distribuicao';
57
58
    /**
59
     * Tipo de serviço a ser executado
60
     */
61
    private $servico;
62
    /**
63
     * Identificação do Ambiente:
64
     * 1 - Produção
65
     * 2 - Homologação
66
     */
67
    private $ambiente;
68
    /**
69
     * Código do modelo do Documento Fiscal. 55 = NF-e; 65 = NFC-e.
70
     */
71
    private $modelo;
72
    /**
73
     * Forma de emissão da NF-e
74
     */
75
    private $emissao;
76
    /**
77
     * Conteudo a ser enviado
78
     */
79
    private $conteudo;
80
81
    /**
82
     * Constroi uma instância de Envio vazia
83
     * @param  array $envio Array contendo dados do Envio
84
     */
85 30
    public function __construct($envio = [])
86
    {
87 30
        $this->fromArray($envio);
88 30
    }
89
90
    /**
91
     * Tipo de serviço a ser executado
92
     * @param boolean $normalize informa se o servico deve estar no formato do XML
93
     * @return mixed servico do Envio
94
     */
95 28
    public function getServico($normalize = false)
96
    {
97 28
        if (!$normalize) {
98 28
            return $this->servico;
99
        }
100 24
        $url = $this->getServiceInfo();
101 23
        if (is_array($url) && isset($url['servico'])) {
102 22
            return Nota::PORTAL.'/wsdl/'.$url['servico'];
103
        }
104 1
        throw new \Exception('A ação do serviço "'.$this->getServico().'" não foi configurada', 404);
105
    }
106
107
    /**
108
     * Altera o valor do Servico para o informado no parâmetro
109
     * @param mixed $servico novo valor para Servico
110
     * @return Envio A própria instância da classe
111
     */
112 30
    public function setServico($servico)
113
    {
114 30
        $this->servico = $servico;
115 30
        return $this;
116
    }
117
118
    /**
119
     * Identificação do Ambiente:
120
     * 1 - Produção
121
     * 2 - Homologação
122
     * @param boolean $normalize informa se o ambiente deve estar no formato do XML
123
     * @return mixed ambiente do Envio
124
     */
125 29
    public function getAmbiente($normalize = false)
126
    {
127 29
        if (!$normalize) {
128 29
            return $this->ambiente;
129
        }
130 1
        switch ($this->ambiente) {
131 1
            case Nota::AMBIENTE_PRODUCAO:
132 1
                return '1';
133 1
            case Nota::AMBIENTE_HOMOLOGACAO:
134 1
                return '2';
135
        }
136 1
        return $this->ambiente;
137
    }
138
139
    /**
140
     * Altera o valor do Ambiente para o informado no parâmetro
141
     * @param mixed $ambiente novo valor para Ambiente
142
     * @return Envio A própria instância da classe
143
     */
144 30
    public function setAmbiente($ambiente)
145
    {
146
        switch ($ambiente) {
147 30
            case '1':
148 1
                $ambiente = Nota::AMBIENTE_PRODUCAO;
149 1
                break;
150 30
            case '2':
151 1
                $ambiente = Nota::AMBIENTE_HOMOLOGACAO;
152 1
                break;
153
        }
154 30
        $this->ambiente = $ambiente;
155 30
        return $this;
156
    }
157
158
    /**
159
     * Código do modelo do Documento Fiscal. 55 = NF-e; 65 = NFC-e.
160
     * @param boolean $normalize informa se o modelo deve estar no formato do XML
161
     * @return mixed modelo do Envio
162
     */
163 29
    public function getModelo($normalize = false)
164
    {
165 29
        if (!$normalize) {
166 29
            return $this->modelo;
167
        }
168 1
        switch ($this->modelo) {
169 1
            case Nota::MODELO_NFE:
170 1
                return '55';
171 1
            case Nota::MODELO_NFCE:
172 1
                return '65';
173
        }
174 1
        return $this->modelo;
175
    }
176
177
    /**
178
     * Altera o valor do Modelo para o informado no parâmetro
179
     * @param mixed $modelo novo valor para Modelo
180
     * @return Envio A própria instância da classe
181
     */
182 30
    public function setModelo($modelo)
183
    {
184
        switch ($modelo) {
185 30
            case '55':
186 1
                $modelo = Nota::MODELO_NFE;
187 1
                break;
188 30
            case '65':
189 1
                $modelo = Nota::MODELO_NFCE;
190 1
                break;
191
        }
192 30
        $this->modelo = $modelo;
193 30
        return $this;
194
    }
195
196
    /**
197
     * Forma de emissão da NF-e
198
     * @param boolean $normalize informa se o emissao deve estar no formato do XML
199
     * @return mixed emissao do Envio
200
     */
201 29
    public function getEmissao($normalize = false)
202
    {
203 29
        if (!$normalize) {
204 29
            return $this->emissao;
205
        }
206 1
        switch ($this->emissao) {
207 1
            case Nota::EMISSAO_NORMAL:
208 1
                return '1';
209 1
            case Nota::EMISSAO_CONTINGENCIA:
210 1
                return '9';
211
        }
212 1
        return $this->emissao;
213
    }
214
215
    /**
216
     * Altera o valor do Emissao para o informado no parâmetro
217
     * @param mixed $emissao novo valor para Emissao
218
     * @return Envio A própria instância da classe
219
     */
220 30
    public function setEmissao($emissao)
221
    {
222
        switch ($emissao) {
223 30
            case '1':
224 1
                $emissao = Nota::EMISSAO_NORMAL;
225 1
                break;
226 30
            case '9':
227 1
                $emissao = Nota::EMISSAO_CONTINGENCIA;
228 1
                break;
229
        }
230 30
        $this->emissao = $emissao;
231 30
        return $this;
232
    }
233
234
    /**
235
     * Conteudo a ser enviado
236
     * @return mixed conteudo do Envio
237
     */
238 23
    public function getConteudo()
239
    {
240 23
        return $this->conteudo;
241
    }
242
243
    /**
244
     * Altera o valor do Conteudo para o informado no parâmetro
245
     * @param mixed $conteudo novo valor para Conteudo
246
     * @return Envio A própria instância da classe
247
     */
248 30
    public function setConteudo($conteudo)
249
    {
250 30
        $this->conteudo = $conteudo;
251 30
        return $this;
252
    }
253
254
    /**
255
     * Obtém a versão do serviço a ser utilizado
256
     * @return string Versão do serviço
257
     */
258 24
    public function getVersao()
259
    {
260 24
        $url = $this->getServiceInfo();
261 24
        if (is_array($url) && isset($url['versao'])) {
262 1
            return $url['versao'];
263
        }
264 23
        return Nota::VERSAO;
265
    }
266
267
    /**
268
     * Devolve um array com as informações de serviço (URL, Versão, Serviço)
269
     * @return array Informações de serviço
270
     */
271 28
    private function getServiceInfo()
272
    {
273 28
        $config = SEFAZ::getInstance()->getConfiguracao();
274 28
        $db = $config->getBanco();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $db. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
275 28
        $estado = $config->getEmitente()->getEndereco()->getMunicipio()->getEstado();
276 28
        $info = $db->getInformacaoServico(
277 28
            $this->getEmissao(),
278 28
            $estado->getUF(),
279 28
            $this->getModelo(),
280 28
            $this->getAmbiente()
281
        );
282 28
        if (!isset($info[$this->getServico()])) {
283 1
            throw new \Exception('O serviço "'.$this->getServico().
284 1
                '" não está disponível para o estado "'.$estado->getUF().'"', 404);
285
        }
286 27
        return $info[$this->getServico()];
287
    }
288
289
    /**
290
     * Converte a instância da classe para um array de campos com valores
291
     * @return array Array contendo todos os campos e valores da instância
292
     */
293 1
    public function toArray($recursive = false)
0 ignored issues
show
Unused Code introduced by
The parameter $recursive is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
294
    {
295 1
        $envio = [];
296 1
        $envio['servico'] = $this->getServico();
297 1
        $envio['ambiente'] = $this->getAmbiente();
298 1
        $envio['modelo'] = $this->getModelo();
299 1
        $envio['emissao'] = $this->getEmissao();
300 1
        $envio['conteudo'] = $this->getConteudo();
301 1
        return $envio;
302
    }
303
304
    /**
305
     * Atribui os valores do array para a instância atual
306
     * @param mixed $envio Array ou instância de Envio, para copiar os valores
307
     * @return Envio A própria instância da classe
308
     */
309 30
    public function fromArray($envio = [])
310
    {
311 30
        if ($envio instanceof Envio) {
312 1
            $envio = $envio->toArray();
313 30
        } elseif (!is_array($envio)) {
314 1
            return $this;
315
        }
316 30
        if (isset($envio['servico'])) {
317 1
            $this->setServico($envio['servico']);
318
        } else {
319 30
            $this->setServico(null);
320
        }
321 30
        if (isset($envio['ambiente'])) {
322 1
            $this->setAmbiente($envio['ambiente']);
323
        } else {
324 30
            $this->setAmbiente(null);
325
        }
326 30
        if (isset($envio['modelo'])) {
327 1
            $this->setModelo($envio['modelo']);
328
        } else {
329 30
            $this->setModelo(null);
330
        }
331 30
        if (isset($envio['emissao'])) {
332 1
            $this->setEmissao($envio['emissao']);
333
        } else {
334 30
            $this->setEmissao(null);
335
        }
336 30
        if (isset($envio['conteudo'])) {
337 1
            $this->setConteudo($envio['conteudo']);
338
        } else {
339 30
            $this->setConteudo(null);
340
        }
341 30
        return $this;
342
    }
343
344
    /**
345
     * Cria um nó XML do envio de acordo com o leiaute da NFe
346
     * @param  string $name Nome do nó que será criado
347
     * @return DOMElement   Nó que contém todos os campos da classe
348
     */
349 22
    public function getNode($name = null)
350
    {
351 22
        $dom = new \DOMDocument('1.0', 'UTF-8');
352 22
        $element = $dom->createElement(is_null($name)?'nfeDadosMsg':$name);
353 22
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', $this->getServico(true));
354
        // Corrige xmlns:default
355
        // $data = $dom->importNode($this->getConteudo()->documentElement, true);
356
        // $element->appendChild($data);
357 22
        Util::appendNode($element, 'Conteudo', 0);
358
359 22
        $dom->appendChild($element);
360
361
        // Corrige xmlns:default
362
        // return $dom;
363 22
        if ($this->getConteudo() instanceof \DOMDocument) {
364 19
            $xml = $this->getConteudo()->saveXML($this->getConteudo()->documentElement);
365
        } else {
366 3
            $xml = $this->getConteudo();
367
        }
368 22
        $xml = str_replace('<Conteudo>0</Conteudo>', $xml, $dom->saveXML($dom->documentElement));
369 22
        $dom->loadXML($xml);
370 22
        return $dom;
371
    }
372
373
    /**
374
     * Envia o conteúdo para o serviço da SEFAZ informado
375
     * @return DOMDocument Documento XML da resposta da SEFAZ
376
     */
377 23
    public function envia()
378
    {
379 23
        $config = SEFAZ::getInstance()->getConfiguracao();
380 23
        $url = $this->getServiceInfo();
381 23
        if (is_array($url)) {
382 23
            $url = $url['url'];
383
        }
384 23
        if ($config->isOffline()) {
385 1
            throw new \NFe\Exception\NetworkException('Operação offline, sem conexão com a internet', 7);
386
        }
387 22
        $config->verificaValidadeCertificado();
388 22
        $soap = new CurlSoap();
389 22
        $soap->setConnectTimeout(intval($config->getTempoLimite()));
390 22
        $soap->setTimeout(ceil($config->getTempoLimite() * 1.5));
391 22
        $soap->setCertificate($config->getArquivoChavePublica());
392 22
        $soap->setPrivateKey($config->getArquivoChavePrivada());
393 22
        $dom = $this->getNode();
394
        try {
395 22
            $response = $soap->send($url, $dom);
396 20
            return $response;
397 2
        } catch (\NFe\Exception\NetworkException $e) {
398 2
            $config->setOffline(time());
399 2
            throw $e;
400
        }
401
    }
402
}
403