Completed
Push — master ( dc5f67...84520a )
by Francimar
11:49 queued 07:55
created

Situacao   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 89.66%

Importance

Changes 0
Metric Value
wmc 33
lcom 1
cbo 6
dl 0
loc 189
ccs 104
cts 116
cp 0.8966
rs 9.3999
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getChave() 0 7 2
A setChave() 0 5 1
A getModelo() 0 13 4
A setModelo() 0 13 3
A toArray() 0 7 1
B fromArray() 0 20 5
A envia() 0 22 3
B consulta() 0 15 5
A getNode() 0 15 2
A loadNode() 0 7 2
B validar() 0 23 4
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 7
    public function __construct($situacao = array())
43
    {
44 7
        parent::__construct($situacao);
45 7
    }
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 6
    public function getChave($normalize = false)
53
    {
54 6
        if (!$normalize) {
55 2
            return $this->chave;
56
        }
57 6
        return $this->chave;
58
    }
59
60 7
    public function setChave($chave)
61
    {
62 7
        $this->chave = $chave;
63 7
        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 5
    public function getModelo($normalize = false)
72
    {
73 5
        if (!$normalize) {
74 5
            return $this->modelo;
75
        }
76
        switch ($this->modelo) {
77
            case Nota::MODELO_NFE:
78
                return '55';
79
            case Nota::MODELO_NFCE:
80
                return '65';
81
        }
82
        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 7
    public function setModelo($modelo)
91
    {
92
        switch ($modelo) {
93 7
            case '55':
94
                $modelo = Nota::MODELO_NFE;
95
                break;
96 7
            case '65':
97
                $modelo = Nota::MODELO_NFCE;
98
                break;
99
        }
100 7
        $this->modelo = $modelo;
101 7
        return $this;
102
    }
103
104 2
    public function toArray($recursive = false)
105
    {
106 2
        $situacao = parent::toArray($recursive);
107 2
        $situacao['chave'] = $this->getChave();
108 2
        $situacao['modelo'] = $this->getModelo();
109 2
        return $situacao;
110
    }
111
112 7
    public function fromArray($situacao = array())
113
    {
114 7
        if ($situacao instanceof Situacao) {
115 1
            $situacao = $situacao->toArray();
116 7
        } elseif (!is_array($situacao)) {
117 1
            return $this;
118
        }
119 7
        parent::fromArray($situacao);
120 7
        if (isset($situacao['chave'])) {
121 1
            $this->setChave($situacao['chave']);
122 1
        } else {
123 7
            $this->setChave(null);
124
        }
125 7
        if (isset($situacao['modelo'])) {
126 1
            $this->setModelo($situacao['modelo']);
127 1
        } else {
128 7
            $this->setModelo(null);
129
        }
130 7
        return $this;
131
    }
132
133 5
    public function envia($dom)
134
    {
135 5
        $envio = new Envio();
136 5
        $envio->setServico(Envio::SERVICO_PROTOCOLO);
137 5
        $envio->setAmbiente($this->getAmbiente());
138 5
        $envio->setModelo($this->getModelo());
139 5
        $envio->setEmissao(Nota::EMISSAO_NORMAL);
140 5
        $envio->setConteudo($dom);
141 5
        $resp = $envio->envia();
142 5
        $this->loadNode($resp);
143 5
        if ($this->isAutorizado()) {
144 2
            $protocolo = new Protocolo();
145 2
            $protocolo->loadNode($resp);
146 2
            return $protocolo;
147 3
        } elseif ($this->isCancelado()) {
148 2
            $evento = new Evento();
149 2
            $evento->loadStatusNode($resp, self::TAG_RETORNO);
150 2
            $evento->loadNode($resp);
151 2
            return $evento;
152
        }
153 1
        return $this;
154
    }
155
156 6
    public function consulta($nota = null)
157
    {
158 6
        if (!is_null($nota)) {
159 6
            $this->setChave($nota->getID());
160 6
            $this->setAmbiente($nota->getAmbiente());
161 6
            $this->setModelo($nota->getModelo());
162 6
        }
163 6
        $dom = $this->getNode()->ownerDocument;
164 6
        $dom = $this->validar($dom);
165 5
        $retorno = $this->envia($dom);
166 5
        if ($retorno instanceof Protocolo && $retorno->isAutorizado() && !is_null($nota)) {
167 2
            $nota->setProtocolo($retorno);
168 2
        }
169 5
        return $retorno;
170
    }
171
172 6
    public function getNode($name = null)
173
    {
174 6
        $dom = new \DOMDocument('1.0', 'UTF-8');
175 6
        $element = $dom->createElement(is_null($name)?'consSitNFe':$name);
176 6
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
177 6
        $versao = $dom->createAttribute('versao');
178 6
        $versao->value = Nota::VERSAO;
179 6
        $element->appendChild($versao);
180
181 6
        Util::appendNode($element, 'tpAmb', $this->getAmbiente(true));
182 6
        Util::appendNode($element, 'xServ', 'CONSULTAR');
183 6
        Util::appendNode($element, 'chNFe', $this->getChave(true));
184 6
        $dom->appendChild($element);
185 6
        return $element;
186
    }
187
188 5
    public function loadNode($element, $name = null)
189
    {
190 5
        $name = is_null($name)?self::TAG_RETORNO:$name;
191 5
        $element = parent::loadNode($element, $name);
192 5
        $this->setChave(Util::loadNode($element, 'chNFe'));
193 5
        return $element;
194
    }
195
196
    /**
197
     * Valida o documento após assinar
198
     */
199 6
    public function validar($dom)
200
    {
201 6
        $dom->loadXML($dom->saveXML());
202 6
        $xsd_path = dirname(__DIR__) . '/Core/schema';
203 6
        $xsd_file = $xsd_path . '/consSitNFe_v3.10.xsd';
204 6
        if (!file_exists($xsd_file)) {
205
            throw new \Exception('O arquivo "'.$xsd_file.'" de esquema XSD não existe!', 404);
206
        }
207
        // Enable user error handling
208 6
        $save = libxml_use_internal_errors(true);
209 6
        if ($dom->schemaValidate($xsd_file)) {
210 5
            libxml_use_internal_errors($save);
211 5
            return $dom;
212
        }
213 1
        $msg = array();
214 1
        $errors = libxml_get_errors();
215 1
        foreach ($errors as $error) {
216 1
            $msg[] = 'Não foi possível validar o XML: '.$error->message;
217 1
        }
218 1
        libxml_clear_errors();
219 1
        libxml_use_internal_errors($save);
220 1
        throw new ValidationException($msg);
221
    }
222
}
223