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

NFCe::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
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\Core;
29
30
use NFe\Common\Util;
31
use NFe\Entity\Imposto;
32
33
/**
34
 * Classe para validação da nota fiscal eletrônica do consumidor
35
 */
36
class NFCe extends Nota
37
{
38
39
    /**
40
     * Versão do QRCode
41
     */
42
    const QRCODE_VERSAO = '100';
43
44
    /**
45
     * Texto com o QR-Code impresso no DANFE NFC-e
46
     */
47
    private $qrcode_url;
48
49
    /**
50
     * Constroi uma instância de NFCe vazia
51
     * @param  array $nfce Array contendo dados do NFCe
52
     */
53 27
    public function __construct($nfce = array())
54
    {
55 27
        parent::__construct($nfce);
56 27
        $this->setModelo(self::MODELO_NFCE);
57 27
        $this->setFormato(self::FORMATO_CONSUMIDOR);
58 27
    }
59
60
    /**
61
     * Texto com o QR-Code impresso no DANFE NFC-e
62
     * @param boolean $normalize informa se a qrcode_url deve estar no formato do XML
63
     * @return mixed qrcode_url do NFCe
64
     */
65 24
    public function getQRCodeURL($normalize = false)
66
    {
67 24
        if (!$normalize) {
68 3
            return $this->qrcode_url;
69
        }
70 23
        return $this->qrcode_url;
71
    }
72
    
73
    /**
74
     * Altera o valor da QrcodeURL para o informado no parâmetro
75
     * @param mixed $qrcode_url novo valor para QrcodeURL
76
     * @return NFCe A própria instância da classe
77
     */
78 27
    public function setQRCodeURL($qrcode_url)
79
    {
80 27
        $this->qrcode_url = $qrcode_url;
81 27
        return $this;
82
    }
83
84
    /**
85
     * URL da página de consulta da nota fiscal
86
     * @param boolean $normalize informa se a URL de consulta deve estar no formato do XML
87
     * @return string URL de consulta da NFCe
88
     */
89
    public function getConsultaURL($normalize = false)
0 ignored issues
show
Unused Code introduced by
The parameter $normalize is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
90
    {
91
        $estado = $this->getEmitente()->getEndereco()->getMunicipio()->getEstado();
92
        $db = SEFAZ::getInstance()->getConfiguracao()->getBanco();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $db. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
93
        $info = $db->getInformacaoServico(
94
            $this->getEmissao(),
95
            $estado->getUF(),
96
            $this->getModelo(),
97
            $this->getAmbiente()
98
        );
99
        if (!isset($info['consulta'])) {
100
            throw new \Exception('Não existe URL de consulta da nota para o estado "'.$estado->getUF().'"', 404);
101
        }
102
        $url = $info['consulta'];
103
        if (is_array($url)) {
104
            $url = $url['url'];
105
        }
106
        return $url;
107
    }
108
109
    /**
110
     * Converte a instância da classe para um array de campos com valores
111
     * @return array Array contendo todos os campos e valores da instância
112
     */
113 3
    public function toArray($recursive = false)
114
    {
115 3
        $nfce = parent::toArray($recursive);
116 3
        $nfce['qrcode_url'] = $this->getQRCodeURL();
117 3
        return $nfce;
118
    }
119
120
    /**
121
     * Atribui os valores do array para a instância atual
122
     * @param mixed $nfce Array ou instância de NFCe, para copiar os valores
123
     * @return NFCe A própria instância da classe
124
     */
125 27
    public function fromArray($nfce = array())
126
    {
127 27
        if ($nfce instanceof NFCe) {
128 2
            $nfce = $nfce->toArray();
129 27
        } elseif (!is_array($nfce)) {
130 2
            return $this;
131
        }
132 27
        parent::fromArray($nfce);
133 27
        if (!isset($nfce['qrcode_url'])) {
134 27
            $this->setQRCodeURL(null);
135 27
        } else {
136
            $this->setQRCodeURL($nfce['qrcode_url']);
137
        }
138 27
        return $this;
139
    }
140
141 23
    private function gerarQRCodeInfo(&$dom)
142
    {
143 23
        $config = SEFAZ::getInstance()->getConfiguracao();
144 23
        $totais = $this->getTotais();
145
        // if ($this->getEmissao() == self::EMISSAO_NORMAL) {
146 23
            $dig_val = Util::loadNode($dom, 'DigestValue', 'Tag "DigestValue" não encontrada na NFCe');
147
        // } else {
148
        //     $dig_val = base64_encode(sha1($dom->saveXML(), true));
149
        // }
150
        $params = array(
151 23
            'chNFe' => $this->getID(),
152 23
            'nVersao' => self::QRCODE_VERSAO,
153 23
            'tpAmb' => $this->getAmbiente(true),
154 23
            'cDest' => null,
155 23
            'dhEmi' => Util::toHex($this->getDataEmissao(true)),
156 23
            'vNF' => Util::toCurrency($totais['nota']),
157 23
            'vICMS' => Util::toCurrency($totais[Imposto::GRUPO_ICMS]),
158 23
            'digVal' => Util::toHex($dig_val),
159 23
            'cIdToken' => Util::padDigit($config->getToken(), 6),
160
            'cHashQRCode' => null
161 23
        );
162 23
        if (!is_null($this->getDestinatario())) {
163 23
            $params['cDest'] = $this->getDestinatario()->getID(true);
164 23
        } else {
165
            unset($params['cDest']);
166
        }
167 23
        $_params = $params;
168 23
        unset($_params['cHashQRCode']);
169 23
        $query = http_build_query($_params);
170 23
        $params['cHashQRCode'] = sha1($query.$config->getCSC());
171 23
        return $params;
172
    }
173
174 23
    private function checkQRCode(&$dom)
175
    {
176 23
        $estado = $this->getEmitente()->getEndereco()->getMunicipio()->getEstado();
177 23
        $db = SEFAZ::getInstance()->getConfiguracao()->getBanco();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $db. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
178 23
        $params = $this->gerarQRCodeInfo($dom);
179 23
        $query = http_build_query($params);
180 23
        $info = $db->getInformacaoServico(
181 23
            $this->getEmissao(),
182 23
            $estado->getUF(),
183 23
            $this->getModelo(),
184 23
            $this->getAmbiente()
185 23
        );
186 23
        if (!isset($info['qrcode'])) {
187
            throw new \Exception('Não existe URL de consulta de QRCode para o estado "'.$estado->getUF().'"', 404);
188
        }
189 23
        $url = $info['qrcode'];
190 23
        if (is_array($url)) {
191
            $url = $url['url'];
192
        }
193 23
        $url .= (strpos($url, '?') === false?'?':'&').$query;
194 23
        $this->setQRCodeURL($url);
195 23
    }
196
197 23
    private function getNodeSuplementar(&$dom)
198
    {
199 23
        $this->checkQRCode($dom);
200 23
        $element = $dom->createElement('infNFeSupl');
201 23
        $qrcode = $dom->createElement('qrCode');
202 23
        $data = $dom->createCDATASection($this->getQRCodeURL(true));
203 23
        $qrcode->appendChild($data);
204 23
        $element->appendChild($qrcode);
205 23
        return $element;
206
    }
207
208
    /**
209
     * Carrega as informações do nó e preenche a instância da classe
210
     * @param  DOMElement $element Nó do xml com todos as tags dos campos
211
     * @param  string $name        Nome do nó que será carregado
212
     * @return DOMElement          Instância do nó que foi carregado
213
     */
214 23
    public function loadNode($element, $name = null)
215
    {
216 23
        $element = parent::loadNode($element, $name);
217 23
        $qrcode_url = Util::loadNode($element, 'qrCode');
218 23
        if (Util::nodeExists($element, 'Signature') && is_null($qrcode_url)) {
219
            throw new \Exception('Tag "qrCode" não encontrada na NFCe', 404);
220
        }
221 23
        $this->setQRCodeURL($qrcode_url);
222 23
        return $element;
223
    }
224
225
    /**
226
     * Assina e adiciona informações suplementares da nota
227
     */
228 23
    public function assinar($dom = null)
229
    {
230 23
        $dom = parent::assinar($dom);
231 23
        $suplementar = $this->getNodeSuplementar($dom);
232 23
        $signature = $dom->getElementsByTagName('Signature')->item(0);
233 23
        $signature->parentNode->insertBefore($suplementar, $signature);
234 23
        return $dom;
235
    }
236
}
237