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

Recibo::setMensagem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
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\Common\Util;
32
use NFe\Exception\ValidationException;
33
34
class Recibo extends Retorno
35
{
36
37
    const INFO_TAGNAME = 'infRec';
38
39
    private $numero;
40
    private $tempo_medio;
41
    private $codigo;
42
    private $mensagem;
43
    private $modelo;
44
45 12
    public function __construct($recibo = [])
46
    {
47 12
        parent::__construct($recibo);
48 12
    }
49
50
    /**
51
     * Número do Recibo
52
     */
53 5
    public function getNumero($normalize = false)
54
    {
55 5
        if (!$normalize) {
56 1
            return $this->numero;
57
        }
58 5
        return $this->numero;
59
    }
60
61 12
    public function setNumero($numero)
62
    {
63 12
        $this->numero = $numero;
64 12
        return $this;
65
    }
66
67
    /**
68
     * Tempo médio de resposta do serviço (em segundos) dos últimos 5 minutos
69
     */
70 2
    public function getTempoMedio($normalize = false)
71
    {
72 2
        if (!$normalize) {
73 1
            return $this->tempo_medio;
74
        }
75 1
        return $this->tempo_medio;
76
    }
77
78 12
    public function setTempoMedio($tempo_medio)
79
    {
80 12
        $this->tempo_medio = $tempo_medio;
81 12
        return $this;
82
    }
83
84
    /**
85
     * Código da Mensagem (v2.0) alterado para tamanho variavel 1-4.
86
     * (NT2011/004)
87
     */
88 2
    public function getCodigo($normalize = false)
89
    {
90 2
        if (!$normalize) {
91 1
            return $this->codigo;
92
        }
93 1
        return $this->codigo;
94
    }
95
96 12
    public function setCodigo($codigo)
97
    {
98 12
        $this->codigo = $codigo;
99 12
        return $this;
100
    }
101
102
    /**
103
     * Mensagem da SEFAZ para o emissor. (v2.0)
104
     */
105 2
    public function getMensagem($normalize = false)
106
    {
107 2
        if (!$normalize) {
108 1
            return $this->mensagem;
109
        }
110 1
        return $this->mensagem;
111
    }
112
113 12
    public function setMensagem($mensagem)
114
    {
115 12
        $this->mensagem = $mensagem;
116 12
        return $this;
117
    }
118
119
    /**
120
     * Código do modelo do Documento Fiscal. 55 = NF-e; 65 = NFC-e.
121
     * @param boolean $normalize informa se o modelo deve estar no formato do XML
122
     * @return mixed modelo do Envio
123
     */
124 6
    public function getModelo($normalize = false)
125
    {
126 6
        if (!$normalize) {
127 6
            return $this->modelo;
128
        }
129 1
        switch ($this->modelo) {
130 1
            case Nota::MODELO_NFE:
131 1
                return '55';
132 1
            case Nota::MODELO_NFCE:
133 1
                return '65';
134
        }
135 1
        return $this->modelo;
136
    }
137
138
    /**
139
     * Altera o valor do Modelo para o informado no parâmetro
140
     * @param mixed $modelo novo valor para Modelo
141
     * @return Envio A própria instância da classe
142
     */
143 12
    public function setModelo($modelo)
144
    {
145
        switch ($modelo) {
146 12
            case '55':
147 1
                $modelo = Nota::MODELO_NFE;
148 1
                break;
149 12
            case '65':
150 1
                $modelo = Nota::MODELO_NFCE;
151 1
                break;
152
        }
153 12
        $this->modelo = $modelo;
154 12
        return $this;
155
    }
156
157 1
    public function toArray($recursive = false)
158
    {
159 1
        $recibo = parent::toArray($recursive);
160 1
        $recibo['numero'] = $this->getNumero();
161 1
        $recibo['tempo_medio'] = $this->getTempoMedio();
162 1
        $recibo['codigo'] = $this->getCodigo();
163 1
        $recibo['mensagem'] = $this->getMensagem();
164 1
        $recibo['modelo'] = $this->getModelo();
165 1
        return $recibo;
166
    }
167
168 12
    public function fromArray($recibo = [])
169
    {
170 12
        if ($recibo instanceof Recibo) {
171 1
            $recibo = $recibo->toArray();
172 12
        } elseif (!is_array($recibo)) {
173 1
            return $this;
174
        }
175 12
        parent::fromArray($recibo);
176 12
        if (isset($recibo['numero'])) {
177 1
            $this->setNumero($recibo['numero']);
178
        } else {
179 12
            $this->setNumero(null);
180
        }
181 12
        if (isset($recibo['tempo_medio'])) {
182 1
            $this->setTempoMedio($recibo['tempo_medio']);
183
        } else {
184 12
            $this->setTempoMedio(null);
185
        }
186 12
        if (isset($recibo['codigo'])) {
187 1
            $this->setCodigo($recibo['codigo']);
188
        } else {
189 12
            $this->setCodigo(null);
190
        }
191 12
        if (isset($recibo['mensagem'])) {
192 1
            $this->setMensagem($recibo['mensagem']);
193
        } else {
194 12
            $this->setMensagem(null);
195
        }
196 12
        if (isset($recibo['modelo'])) {
197 1
            $this->setModelo($recibo['modelo']);
198
        } else {
199 12
            $this->setModelo(null);
200
        }
201 12
        return $this;
202
    }
203
204 5
    public function envia($dom)
205
    {
206 5
        $envio = new Envio();
207 5
        $envio->setServico(Envio::SERVICO_RETORNO);
208 5
        $envio->setAmbiente($this->getAmbiente());
209 5
        $envio->setModelo($this->getModelo());
210 5
        $envio->setEmissao(Nota::EMISSAO_NORMAL);
211 5
        $this->setVersao($envio->getVersao());
212 5
        $dom = $this->validar($dom);
213 4
        $envio->setConteudo($dom);
214 4
        $resp = $envio->envia();
215 4
        $this->loadNode($resp);
216 4
        if (!$this->isProcessado()) {
217 1
            return $this;
218
        }
219 3
        $protocolo = new Protocolo();
220 3
        $protocolo->loadNode($resp);
221 3
        return $protocolo;
222
    }
223
224 5
    public function consulta($nota = null)
225
    {
226 5
        if (!is_null($nota)) {
227 5
            $this->setAmbiente($nota->getAmbiente());
228 5
            $this->setModelo($nota->getModelo());
229
        }
230 5
        $dom = $this->getNode()->ownerDocument;
231 5
        $retorno = $this->envia($dom);
232 4
        if ($retorno->isAutorizado() && !is_null($nota)) {
233 2
            $nota->setProtocolo($retorno);
234
        }
235 4
        return $retorno;
236
    }
237
238 5
    public function getNode($name = null)
239
    {
240 5
        $dom = new \DOMDocument('1.0', 'UTF-8');
241 5
        $element = $dom->createElement(is_null($name)?'consReciNFe':$name);
242 5
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
243 5
        $versao = $dom->createAttribute('versao');
244 5
        $versao->value = Nota::VERSAO;
245 5
        $element->appendChild($versao);
246
247 5
        Util::appendNode($element, 'tpAmb', $this->getAmbiente(true));
248 5
        Util::appendNode($element, 'nRec', $this->getNumero(true));
249 5
        $dom->appendChild($element);
250 5
        return $element;
251
    }
252
253 6
    public function loadNode($element, $name = null)
254
    {
255 6
        $name = is_null($name)?'retConsReciNFe':$name;
256 6
        if ($name == self::INFO_TAGNAME) {
257 2
            $_fields = $element->getElementsByTagName($name);
258 2
            if ($_fields->length == 0) {
259 1
                throw new \Exception('Tag "'.$name.'" não encontrada', 404);
260
            }
261 1
            $element = $_fields->item(0);
262
        } else {
263 4
            $element = parent::loadNode($element, $name);
264
        }
265 5
        $this->setNumero(
266 5
            Util::loadNode(
267 5
                $element,
268 5
                'nRec',
269 5
                'Tag "nRec" do campo "Numero" não encontrada'
270
            )
271
        );
272 5
        $this->setTempoMedio(Util::loadNode($element, 'tMed'));
273 5
        $this->setCodigo(Util::loadNode($element, 'cMsg'));
274 5
        $this->setMensagem(Util::loadNode($element, 'xMsg'));
275 5
        return $element;
276
    }
277
278
    /**
279
     * Valida o documento após assinar
280
     */
281 6
    public function validar($dom)
282
    {
283 6
        $dom->loadXML($dom->saveXML());
284 6
        $xsd_path = dirname(__DIR__) . '/Core/schema';
285 6
        $xsd_file = $xsd_path . '/consReciNFe_v'.$this->getVersao().'.xsd';
286 6
        if (!file_exists($xsd_file)) {
287 1
            throw new \Exception(sprintf('O arquivo "%s" de esquema XSD não existe!', $xsd_file), 404);
288
        }
289
        // Enable user error handling
290 5
        $save = libxml_use_internal_errors(true);
291 5
        if ($dom->schemaValidate($xsd_file)) {
292 4
            libxml_use_internal_errors($save);
293 4
            return $dom;
294
        }
295 1
        $msg = [];
296 1
        $errors = libxml_get_errors();
297 1
        foreach ($errors as $error) {
298 1
            $msg[] = 'Não foi possível validar o XML: '.$error->message;
299
        }
300 1
        libxml_clear_errors();
301 1
        libxml_use_internal_errors($save);
302 1
        throw new ValidationException($msg);
303
    }
304
}
305