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

Autorizacao::getConteudo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 14
cts 14
cp 1
rs 9.3142
c 0
b 0
f 0
cc 1
eloc 14
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\Util;
33
use NFe\Exception\ValidationException;
34
35
class Autorizacao extends Retorno
36
{
37
38 8
    public function __construct($autorizacao = [])
39
    {
40 8
        parent::__construct($autorizacao);
41 8
    }
42
43 2
    public function toArray($recursive = false)
44
    {
45 2
        $autorizacao = parent::toArray($recursive);
46 2
        return $autorizacao;
47
    }
48
49 8
    public function fromArray($autorizacao = [])
50
    {
51 8
        if ($autorizacao instanceof Autorizacao) {
52 1
            $autorizacao = $autorizacao->toArray();
53 8
        } elseif (!is_array($autorizacao)) {
54 1
            return $this;
55
        }
56 8
        parent::fromArray($autorizacao);
57 8
        return $this;
58
    }
59
60 5
    private function getConteudo($dom)
61
    {
62 5
        $config = SEFAZ::getInstance()->getConfiguracao();
63 5
        $dob = new \DOMDocument('1.0', 'UTF-8');
64 5
        $envio = $dob->createElement('enviNFe');
65 5
        $envio->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
66 5
        $versao = $dob->createAttribute('versao');
67 5
        $versao->value = Nota::VERSAO;
68 5
        $envio->appendChild($versao);
69 5
        Util::appendNode($envio, 'idLote', self::genLote());
70 5
        Util::appendNode($envio, 'indSinc', $config->getSincrono(true));
71
        // Corrige xmlns:default
72
        // $data = $dob->importNode($dom->documentElement, true);
73
        // $envio->appendChild($data);
74 5
        Util::appendNode($envio, 'NFe', 0);
75 5
        $dob->appendChild($envio);
76
        // Corrige xmlns:default
77
        // return $dob;
78 5
        $xml = $dob->saveXML($dob->documentElement);
79 5
        return str_replace('<NFe>0</NFe>', $dom->saveXML($dom->documentElement), $xml);
80
    }
81
82 5
    public function envia($nota, $dom)
83
    {
84 5
        $envio = new Envio();
85 5
        $envio->setServico(Envio::SERVICO_AUTORIZACAO);
86 5
        $envio->setAmbiente($nota->getAmbiente());
87 5
        $envio->setModelo($nota->getModelo());
88 5
        $envio->setEmissao($nota->getEmissao());
89 5
        $this->setVersao($envio->getVersao());
90 5
        $xml_content = $this->getConteudo($dom);
91 5
        $dom_lote = $this->validar($xml_content);
92 5
        $envio->setConteudo($dom_lote);
93 5
        $resp = $envio->envia();
94 4
        $this->loadNode($resp);
95 4
        if ($this->isProcessado()) {
96 2
            $protocolo = new Protocolo();
97 2
            $protocolo->loadNode($resp);
98 2
            if ($protocolo->isAutorizado()) {
99 2
                $nota->setProtocolo($protocolo);
100
            }
101 2
            return $protocolo;
102 2
        } elseif ($this->isRecebido()) {
103 1
            $recibo = new Recibo($this->toArray());
104 1
            $recibo->setModelo($nota->getModelo());
105 1
            $recibo->loadNode($resp, Recibo::INFO_TAGNAME);
106 1
            return $recibo;
107 1
        } elseif ($this->isParalisado()) {
108
            $config = SEFAZ::getInstance()->getConfiguracao();
109
            $config->setOffline(time());
110
            throw new \NFe\Exception\NetworkException('Serviço paralisado ou em manutenção', $this->getStatus());
111
        }
112 1
        return $this;
113
    }
114
115 4
    public function loadNode($element, $name = null)
116
    {
117 4
        $tag = is_null($name)?'retEnviNFe':$name;
118 4
        $element = parent::loadNode($element, $tag);
119 4
        return $element;
120
    }
121
122
    /**
123
     * Valida o XML em lote
124
     */
125 7
    public function validar($xml_content)
126
    {
127 7
        $dom = new \DOMDocument('1.0', 'UTF-8');
128 7
        $dom->loadXML($xml_content);
129 7
        $xsd_path = dirname(__DIR__) . '/Core/schema';
130 7
        $xsd_file = $xsd_path . '/enviNFe_v'.$this->getVersao().'.xsd';
131 7
        if (!file_exists($xsd_file)) {
132 1
            throw new \Exception(sprintf('O arquivo "%s" de esquema XSD não existe!', $xsd_file), 404);
133
        }
134
        // Enable user error handling
135 6
        $save = libxml_use_internal_errors(true);
136 6
        if ($dom->schemaValidate($xsd_file)) {
137 5
            libxml_use_internal_errors($save);
138 5
            return $dom;
139
        }
140 1
        $msg = [];
141 1
        $errors = libxml_get_errors();
142 1
        foreach ($errors as $error) {
143 1
            $msg[] = 'Não foi possível validar o XML: '.$error->message;
144
        }
145 1
        libxml_clear_errors();
146 1
        libxml_use_internal_errors($save);
147 1
        throw new ValidationException($msg);
148
    }
149
}
150