Completed
Push — master ( c523cc...f6da78 )
by Francimar
05:08
created

Situacao::validar()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 0
cts 18
cp 0
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 17
nc 4
nop 1
crap 20
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\Exception\ValidationException;
32
33
class Situacao extends Retorno
34
{
35
36
    private $chave;
37
    private $modelo;
38
39 1
    public function __construct($situacao = array())
40
    {
41 1
        parent::__construct($situacao);
42 1
    }
43
44
    /**
45
     * Chaves de acesso da NF-e, compostas por: UF do emitente, AAMM da emissão
46
     * da NFe, CNPJ do emitente, modelo, série e número da NF-e e código
47
     * numérico+DV.
48
     */
49
    public function getChave($normalize = false)
50
    {
51
        if (!$normalize) {
52
            return $this->chave;
53
        }
54
        return $this->chave;
55
    }
56
57 1
    public function setChave($chave)
58
    {
59 1
        $this->chave = $chave;
60 1
        return $this;
61
    }
62
63
    /**
64
     * Código do modelo do Documento Fiscal. 55 = NF-e; 65 = NFC-e.
65
     */
66
    public function getModelo($normalize = false)
67
    {
68
        if (!$normalize) {
69
            return $this->modelo;
70
        }
71
        return $this->modelo;
72
    }
73
74 1
    public function setModelo($modelo)
75
    {
76 1
        $this->modelo = $modelo;
77 1
        return $this;
78
    }
79
80
    public function toArray()
81
    {
82
        $situacao = parent::toArray();
83
        $situacao['chave'] = $this->getChave();
84
        $situacao['modelo'] = $this->getModelo();
85
        return $situacao;
86
    }
87
88 1
    public function fromArray($situacao = array())
89
    {
90 1
        if ($situacao instanceof Situacao) {
91
            $situacao = $situacao->toArray();
92 1
        } elseif (!is_array($situacao)) {
93
            return $this;
94
        }
95 1
        parent::fromArray($situacao);
96 1
        if (isset($situacao['chave'])) {
97
            $this->setChave($situacao['chave']);
98
        } else {
99 1
            $this->setChave(null);
100
        }
101 1
        if (isset($situacao['modelo'])) {
102
            $this->setModelo($situacao['modelo']);
103
        } else {
104 1
            $this->setModelo(null);
105
        }
106 1
        return $this;
107
    }
108
109
    public function envia($dom)
110
    {
111
        $envio = new Envio();
112
        $envio->setServico(Envio::SERVICO_PROTOCOLO);
113
        $envio->setAmbiente($this->getAmbiente());
114
        $envio->setModelo($this->getModelo());
115
        $envio->setEmissao(Nota::EMISSAO_NORMAL);
116
        $envio->setConteudo($dom);
117
        $resp = $envio->envia();
118
        $this->loadNode($resp);
119
        if ($this->isAutorizado()) {
120
            $protocolo = new Protocolo();
121
            $protocolo->loadNode($resp);
122
            return $protocolo;
123
        }
124
        return $this;
125
    }
126
127
    public function consulta($nota = null)
128
    {
129
        if (!is_null($nota)) {
130
            $this->setChave($nota->getID());
131
            $this->setAmbiente($nota->getAmbiente());
132
            $this->setModelo($nota->getModelo());
133
        }
134
        $dom = $this->getNode()->ownerDocument;
135
        $dom = $this->validar($dom);
136
        $retorno = $this->envia($dom);
137
        if ($retorno instanceof Protocolo && $retorno->isAutorizado() && !is_null($nota)) {
138
            $nota->setProtocolo($retorno);
139
        }
140
        return $retorno;
141
    }
142
143
    public function getNode($name = null)
144
    {
145
        $dom = new \DOMDocument('1.0', 'UTF-8');
146
        $element = $dom->createElement(is_null($name)?'consSitNFe':$name);
147
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
148
        $versao = $dom->createAttribute('versao');
149
        $versao->value = Nota::VERSAO;
150
        $element->appendChild($versao);
151
152
        $element->appendChild($dom->createElement('tpAmb', $this->getAmbiente(true)));
153
        $element->appendChild($dom->createElement('xServ', 'CONSULTAR'));
154
        $element->appendChild($dom->createElement('chNFe', $this->getChave(true)));
155
        $dom->appendChild($element);
156
        return $element;
157
    }
158
159
    public function loadNode($element, $name = null)
160
    {
161
        $name = is_null($name)?'retConsSitNFe':$name;
162
        $element = parent::loadNode($element, $name);
163
        $chave = null;
164
        $_fields = $element->getElementsByTagName('chNFe');
165
        if ($_fields->length > 0) {
166
            $chave = $_fields->item(0)->nodeValue;
167
        }
168
        $this->setChave($chave);
169
        return $element;
170
    }
171
172
    /**
173
     * Valida o documento após assinar
174
     */
175
    public function validar($dom)
176
    {
177
        $dom->loadXML($dom->saveXML());
178
        $xsd_path = dirname(__DIR__) . '/Core/schema';
179
        $xsd_file = $xsd_path . '/consSitNFe_v3.10.xsd';
180
        if (!file_exists($xsd_file)) {
181
            throw new \Exception('O arquivo "'.$xsd_file.'" de esquema XSD não existe!', 404);
182
        }
183
        // Enable user error handling
184
        $save = libxml_use_internal_errors(true);
185
        if ($dom->schemaValidate($xsd_file)) {
186
            libxml_use_internal_errors($save);
187
            return $dom;
188
        }
189
        $msg = array();
190
        $errors = libxml_get_errors();
191
        foreach ($errors as $error) {
192
            $msg[] = 'Não foi possível validar o XML: '.$error->message;
193
        }
194
        libxml_clear_errors();
195
        libxml_use_internal_errors($save);
196
        throw new ValidationException($msg);
197
    }
198
}
199