Passed
Push — master ( c1d1cf...f48ccd )
by Francimar
03:58
created

Situacao   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 89.19%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 5
dl 0
loc 182
ccs 99
cts 111
cp 0.8919
rs 9.6
c 0
b 0
f 0

12 Methods

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