Test Failed
Push — master ( e53a66...43458c )
by Francimar
16:26
created

Situacao::validar()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 8.3354

Importance

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