Passed
Push — master ( 86bb06...22a4bb )
by Francimar
08:25
created

NFCe::checkQRCode()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3.0017

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 16
cts 17
cp 0.9412
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 15
nc 3
nop 1
crap 3.0017
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 7
    public function __construct($nfce = array())
54
    {
55 7
        parent::__construct($nfce);
56 7
        $this->setModelo(self::MODELO_NFCE);
57 7
        $this->setFormato(self::FORMATO_CONSUMIDOR);
58 7
    }
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 4
    public function getQRCodeURL($normalize = false)
66
    {
67 4
        if (!$normalize) {
68 2
            return $this->qrcode_url;
69
        }
70 3
        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 7
    public function setQRCodeURL($qrcode_url)
79
    {
80 7
        $this->qrcode_url = $qrcode_url;
81 7
        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
        return $info['consulta'];
103
    }
104
105
    /**
106
     * Converte a instância da classe para um array de campos com valores
107
     * @return array Array contendo todos os campos e valores da instância
108
     */
109 2
    public function toArray()
110
    {
111 2
        $nfce = parent::toArray();
112 2
        $nfce['qrcode_url'] = $this->getQRCodeURL();
113 2
        return $nfce;
114
    }
115
116
    /**
117
     * Atribui os valores do array para a instância atual
118
     * @param mixed $nfce Array ou instância de NFCe, para copiar os valores
119
     * @return NFCe A própria instância da classe
120
     */
121 7
    public function fromArray($nfce = array())
122
    {
123 7
        if ($nfce instanceof NFCe) {
124 2
            $nfce = $nfce->toArray();
125 7
        } elseif (!is_array($nfce)) {
126 2
            return $this;
127
        }
128 7
        parent::fromArray($nfce);
129 7
        if (!isset($nfce['qrcode_url'])) {
130 7
            $this->setQRCodeURL(null);
131 7
        } else {
132
            $this->setQRCodeURL($nfce['qrcode_url']);
133
        }
134 7
        return $this;
135
    }
136
137 3
    private function gerarQRCodeInfo(&$dom)
138
    {
139 3
        $config = SEFAZ::getInstance()->getConfiguracao();
140 3
        $totais = $this->getTotais();
141 3
        $digest = $dom->getElementsByTagName('DigestValue')->item(0);
142
        // if($this->getEmissao() == self::EMISSAO_NORMAL)
143 3
            $dig_val = $digest->nodeValue;
144
        // else
145
        // 	$dig_val = base64_encode(sha1($dom->saveXML(), true));
146
        $params = array(
147 3
            'chNFe' => $this->getID(),
148 3
            'nVersao' => self::QRCODE_VERSAO,
149 3
            'tpAmb' => $this->getAmbiente(true),
150 3
            'cDest' => null,
151 3
            'dhEmi' => Util::toHex($this->getDataEmissao(true)),
152 3
            'vNF' => Util::toCurrency($totais['nota']),
153 3
            'vICMS' => Util::toCurrency($totais[Imposto::GRUPO_ICMS]),
154 3
            'digVal' => Util::toHex($dig_val),
155 3
            'cIdToken' => Util::padDigit($config->getToken(), 6),
156
            'cHashQRCode' => null
157 3
        );
158 3
        if (!is_null($this->getDestinatario())) {
159 3
            $params['cDest'] = $this->getDestinatario()->getID(true);
160 3
        } else {
161
            unset($params['cDest']);
162
        }
163 3
        $_params = $params;
164 3
        unset($_params['cHashQRCode']);
165 3
        $query = http_build_query($_params);
166 3
        $params['cHashQRCode'] = sha1($query.$config->getCSC());
167 3
        return $params;
168
    }
169
170 3
    private function checkQRCode(&$dom)
171
    {
172 3
        $estado = $this->getEmitente()->getEndereco()->getMunicipio()->getEstado();
173 3
        $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...
174 3
        $params = $this->gerarQRCodeInfo($dom);
175 3
        $query = http_build_query($params);
176 3
        $info = $db->getInformacaoServico(
177 3
            $this->getEmissao(),
178 3
            $estado->getUF(),
179 3
            $this->getModelo(),
180 3
            $this->getAmbiente()
181 3
        );
182 3
        if (!isset($info['qrcode'])) {
183
            throw new \Exception('Não existe URL de consulta de QRCode para o estado "'.$estado->getUF().'"', 404);
184
        }
185 3
        $url = $info['qrcode'];
186 3
        $url .= (strpos($url, '?') === false?'?':'&').$query;
187 3
        $this->setQRCodeURL($url);
188 3
    }
189
190 3
    private function getNodeSuplementar(&$dom)
191
    {
192 3
        $this->checkQRCode($dom);
193 3
        $element = $dom->createElement('infNFeSupl');
194 3
        $qrcode = $dom->createElement('qrCode');
195 3
        $data = $dom->createCDATASection($this->getQRCodeURL(true));
196 3
        $qrcode->appendChild($data);
197 3
        $element->appendChild($qrcode);
198 3
        return $element;
199
    }
200
201
    /**
202
     * Carrega as informações do nó e preenche a instância da classe
203
     * @param  DOMElement $element Nó do xml com todos as tags dos campos
204
     * @param  string $name        Nome do nó que será carregado
205
     * @return DOMElement          Instância do nó que foi carregado
206
     */
207 3
    public function loadNode($element, $name = null)
208
    {
209 3
        $element = parent::loadNode($element, $name);
210 3
        $_fields = $element->getElementsByTagName('qrCode');
211 3
        $_sig_fields = $element->getElementsByTagName('Signature');
212 3
        $qrcode_url = null;
213 3
        if ($_fields->length > 0) {
214 2
            $qrcode_url = $_fields->item(0)->nodeValue;
215 3
        } elseif ($_sig_fields->length > 0) {
216
            throw new \Exception('Tag "qrCode" não encontrada', 404);
217
        }
218 3
        $this->setQRCodeURL($qrcode_url);
219 3
        return $element;
220
    }
221
222
    /**
223
     * Assina e adiciona informações suplementares da nota
224
     */
225 3
    public function assinar($dom = null)
226
    {
227 3
        $dom = parent::assinar($dom);
228 3
        $suplementar = $this->getNodeSuplementar($dom);
229 3
        $signature = $dom->getElementsByTagName('Signature')->item(0);
230 3
        $signature->parentNode->insertBefore($suplementar, $signature);
231 3
        return $dom;
232
    }
233
}
234