Passed
Push — master ( 84520a...e53a66 )
by Francimar
03:44
created

Inutilizacao::setInicio()   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\Core\SEFAZ;
32
use NFe\Common\Util;
33
use NFe\Exception\ValidationException;
34
use FR3D\XmlDSig\Adapter\AdapterInterface;
35
use FR3D\XmlDSig\Adapter\XmlseclibsAdapter;
36
37
class Inutilizacao extends Retorno
0 ignored issues
show
Complexity introduced by
This class has a complexity of 65 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
38
{
39
40
    private $id;
41
    private $ano;
42
    private $cnpj;
43
    private $modelo;
44
    private $serie;
45
    private $inicio;
46
    private $final;
47
    private $justificativa;
48
    private $numero;
49
50 6
    public function __construct($inutilizacao = array())
51
    {
52 6
        parent::__construct($inutilizacao);
53 6
    }
54
55
    /**
56
     * Formado por:
57
     * ID = Literal
58
     * 43 = Código Estado
59
     * 15 = Ano
60
     *
61
     * 00000000000000 = CNPJ
62
     * 55 = Modelo
63
     * 001 = Série
64
     * 000000411 =
65
     * Número Inicial
66
     * 000000411 = Número Final
67
     */
68 4
    public function getID($normalize = false)
69
    {
70 4
        if (!$normalize) {
71 1
            return $this->id;
72
        }
73 4
        return 'ID'.$this->id;
74
    }
75
76 6
    public function setID($id)
77
    {
78 6
        $this->id = $id;
79 6
        return $this;
80
    }
81
82 4
    public function getAno($normalize = false)
83
    {
84 4
        if (!$normalize) {
85 1
            return $this->ano;
86
        }
87 4
        return $this->ano % 100;
88
    }
89
90 6
    public function setAno($ano)
91
    {
92 6
        $this->ano = $ano;
93 6
        return $this;
94
    }
95
96 4
    public function getCNPJ($normalize = false)
97
    {
98 4
        if (!$normalize) {
99 1
            return $this->cnpj;
100
        }
101 4
        return $this->cnpj;
102
    }
103
104 6
    public function setCNPJ($cnpj)
105
    {
106 6
        $this->cnpj = $cnpj;
107 6
        return $this;
108
    }
109
110
    /**
111
     * Código do modelo do Documento Fiscal. 55 = NF-e; 65 = NFC-e.
112
     * @param boolean $normalize informa se o modelo deve estar no formato do XML
113
     * @return mixed modelo do Envio
114
     */
115 4
    public function getModelo($normalize = false)
116
    {
117 4
        if (!$normalize) {
118 3
            return $this->modelo;
119
        }
120 4
        switch ($this->modelo) {
121 4
            case Nota::MODELO_NFE:
122
                return '55';
123 4
            case Nota::MODELO_NFCE:
124 3
                return '65';
125
        }
126 1
        return $this->modelo;
127
    }
128
129
    /**
130
     * Altera o valor do Modelo para o informado no parâmetro
131
     * @param mixed $modelo novo valor para Modelo
132
     * @return Envio A própria instância da classe
133
     */
134 6
    public function setModelo($modelo)
135
    {
136
        switch ($modelo) {
137 6
            case '55':
138
                $modelo = Nota::MODELO_NFE;
139
                break;
140 6
            case '65':
141 4
                $modelo = Nota::MODELO_NFCE;
142 4
                break;
143
        }
144 6
        $this->modelo = $modelo;
145 6
        return $this;
146
    }
147
148 4
    public function getSerie($normalize = false)
149
    {
150 4
        if (!$normalize) {
151 1
            return $this->serie;
152
        }
153 4
        return $this->serie;
154
    }
155
156 6
    public function setSerie($serie)
157
    {
158 6
        $this->serie = $serie;
159 6
        return $this;
160
    }
161
162 4
    public function getInicio($normalize = false)
163
    {
164 4
        if (!$normalize) {
165 3
            return $this->inicio;
166
        }
167 4
        return $this->inicio;
168
    }
169
170 6
    public function setInicio($inicio)
171
    {
172 6
        $this->inicio = $inicio;
173 6
        return $this;
174
    }
175
176 4
    public function getFinal($normalize = false)
177
    {
178 4
        if (!$normalize) {
179 1
            return $this->final;
180
        }
181 4
        return $this->final;
182
    }
183
184 6
    public function setFinal($final)
185
    {
186 6
        $this->final = $final;
187 6
        return $this;
188
    }
189
190 4
    public function getJustificativa($normalize = false)
191
    {
192 4
        if (!$normalize) {
193 1
            return $this->justificativa;
194
        }
195 4
        return $this->justificativa;
196
    }
197
198 6
    public function setJustificativa($justificativa)
199
    {
200 6
        $this->justificativa = $justificativa;
201 6
        return $this;
202
    }
203
204 2
    public function getNumero($normalize = false)
205
    {
206 2
        if (!$normalize) {
207 2
            return $this->numero;
208
        }
209 2
        return $this->numero;
210
    }
211
212 6
    public function setNumero($numero)
213
    {
214 6
        $this->numero = $numero;
215 6
        return $this;
216
    }
217
218
    /**
219
     * Informa se os números foram inutilizados
220
     */
221 3
    public function isInutilizado()
222
    {
223 3
        return $this->getStatus() == '102';
224
    }
225
226 1
    public function toArray($recursive = false)
227
    {
228 1
        $inutilizacao = parent::toArray($recursive);
229 1
        $inutilizacao['id'] = $this->getID();
230 1
        $inutilizacao['ano'] = $this->getAno();
231 1
        $inutilizacao['cnpj'] = $this->getCNPJ();
232 1
        $inutilizacao['modelo'] = $this->getModelo();
233 1
        $inutilizacao['serie'] = $this->getSerie();
234 1
        $inutilizacao['inicio'] = $this->getInicio();
235 1
        $inutilizacao['final'] = $this->getFinal();
236 1
        $inutilizacao['justificativa'] = $this->getJustificativa();
237 1
        $inutilizacao['numero'] = $this->getNumero();
238 1
        return $inutilizacao;
239
    }
240
241 6
    public function fromArray($inutilizacao = array())
0 ignored issues
show
Complexity introduced by
This operation has 1536 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
242
    {
243 6
        if ($inutilizacao instanceof Inutilizacao) {
244 1
            $inutilizacao = $inutilizacao->toArray();
245 6
        } elseif (!is_array($inutilizacao)) {
246 1
            return $this;
247
        }
248 6
        parent::fromArray($inutilizacao);
249 6
        if (isset($inutilizacao['id'])) {
250 1
            $this->setID($inutilizacao['id']);
251
        } else {
252 6
            $this->setID(null);
253
        }
254 6
        if (isset($inutilizacao['ano'])) {
255 1
            $this->setAno($inutilizacao['ano']);
256
        } else {
257 6
            $this->setAno(null);
258
        }
259 6
        if (isset($inutilizacao['cnpj'])) {
260 1
            $this->setCNPJ($inutilizacao['cnpj']);
261
        } else {
262 6
            $this->setCNPJ(null);
263
        }
264 6
        if (isset($inutilizacao['modelo'])) {
265 1
            $this->setModelo($inutilizacao['modelo']);
266
        } else {
267 6
            $this->setModelo(null);
268
        }
269 6
        if (isset($inutilizacao['serie'])) {
270 1
            $this->setSerie($inutilizacao['serie']);
271
        } else {
272 6
            $this->setSerie(null);
273
        }
274 6
        if (isset($inutilizacao['inicio'])) {
275 1
            $this->setInicio($inutilizacao['inicio']);
276
        } else {
277 6
            $this->setInicio(null);
278
        }
279 6
        if (isset($inutilizacao['final'])) {
280 1
            $this->setFinal($inutilizacao['final']);
281
        } else {
282 6
            $this->setFinal(null);
283
        }
284 6
        if (isset($inutilizacao['justificativa'])) {
285 1
            $this->setJustificativa($inutilizacao['justificativa']);
286
        } else {
287 6
            $this->setJustificativa(null);
288
        }
289 6
        if (isset($inutilizacao['numero'])) {
290 1
            $this->setNumero($inutilizacao['numero']);
291
        } else {
292 6
            $this->setNumero(null);
293
        }
294 6
        return $this;
295
    }
296
297 4
    public function gerarID()
298
    {
299 4
        $id = sprintf(
300 4
            '%02d%02d%s%02d%03d%09d%09d',
301 4
            $this->getUF(true),
302 4
            $this->getAno(true), // 2 dígitos
303 4
            $this->getCNPJ(true),
304 4
            $this->getModelo(true),
305 4
            $this->getSerie(true),
306 4
            $this->getInicio(true),
307 4
            $this->getFinal(true)
308
        );
309 4
        return $id;
310
    }
311
312 4
    public function getNode($name = null)
313
    {
314 4
        $this->setID($this->gerarID());
315
316 4
        $dom = new \DOMDocument('1.0', 'UTF-8');
317 4
        $element = $dom->createElement(is_null($name)?'inutNFe':$name);
318 4
        $element->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', Nota::PORTAL);
319 4
        $versao = $dom->createAttribute('versao');
320 4
        $versao->value = Nota::VERSAO;
321 4
        $element->appendChild($versao);
322
323 4
        $info = $dom->createElement('infInut');
324 4
        $id = $dom->createAttribute('Id');
325 4
        $id->value = $this->getID(true);
326 4
        $info->appendChild($id);
327
328 4
        Util::appendNode($info, 'tpAmb', $this->getAmbiente(true));
329 4
        Util::appendNode($info, 'xServ', 'INUTILIZAR');
330 4
        Util::appendNode($info, 'cUF', $this->getUF(true));
331 4
        Util::appendNode($info, 'ano', $this->getAno(true));
332 4
        Util::appendNode($info, 'CNPJ', $this->getCNPJ(true));
333 4
        Util::appendNode($info, 'mod', $this->getModelo(true));
334 4
        Util::appendNode($info, 'serie', $this->getSerie(true));
335 4
        Util::appendNode($info, 'nNFIni', $this->getInicio(true));
336 4
        Util::appendNode($info, 'nNFFin', $this->getFinal(true));
337 4
        Util::appendNode($info, 'xJust', $this->getJustificativa(true));
338 4
        $element->appendChild($info);
339 4
        $dom->appendChild($element);
340 4
        return $element;
341
    }
342
343 2
    public function getReturnNode()
344
    {
345 2
        $outros = parent::getNode('infInut');
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getNode() instead of getReturnNode()). Are you sure this is correct? If so, you might want to change this to $this->getNode().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
346 2
        $element = $this->getNode('retInutNFe');
347 2
        $dom = $element->ownerDocument;
348 2
        $info = $dom->getElementsByTagName('infInut')->item(0);
349 2
        $info->removeAttribute('Id');
350 2
        $removeTags = array('tpAmb', 'xServ', 'xJust');
0 ignored issues
show
Coding Style introduced by
$removeTags does not seem to conform to the naming convention (^[a-z_][a-z0-9_]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
351 2
        foreach ($removeTags as $key) {
0 ignored issues
show
Coding Style introduced by
$removeTags does not seem to conform to the naming convention (^[a-z_][a-z0-9_]*$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
352 2
            $node = $info->getElementsByTagName($key)->item(0);
353 2
            $info->removeChild($node);
354
        }
355 2
        $uf = $info->getElementsByTagName('cUF')->item(0);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $uf. 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...
356 2
        foreach ($outros->childNodes as $node) {
357 2
            $node = $dom->importNode($node, true);
358 2
            $list = $info->getElementsByTagName($node->nodeName);
359 2
            if ($list->length == 1) {
360 2
                continue;
361
            }
362 2
            switch ($node->nodeName) {
363 2
                case 'dhRecbto':
364 2
                    $info->appendChild($node);
365 2
                    break;
366
                default:
367 2
                    $info->insertBefore($node, $uf);
368
            }
369
        }
370 2
        Util::appendNode($info, 'nProt', $this->getNumero(true));
371 2
        return $element;
372
    }
373
374 3
    public function loadNode($element, $name = null)
375
    {
376 3
        $name = is_null($name)?'infInut':$name;
377 3
        $element = parent::loadNode($element, $name);
378 3
        if (!$this->isInutilizado()) {
379 1
            return $element;
380
        }
381 2
        $this->setAno(Util::loadNode($element, 'ano'));
382 2
        $this->setCNPJ(Util::loadNode($element, 'CNPJ'));
383 2
        $this->setModelo(Util::loadNode($element, 'mod'));
384 2
        $this->setSerie(Util::loadNode($element, 'serie'));
385 2
        $this->setInicio(Util::loadNode($element, 'nNFIni'));
386 2
        $this->setFinal(Util::loadNode($element, 'nNFFin'));
387 2
        $this->setNumero(Util::loadNode($element, 'nProt'));
388 2
        return $element;
389
    }
390
391 3
    public function envia($dom)
392
    {
393 3
        $envio = new Envio();
394 3
        $envio->setServico(Envio::SERVICO_INUTILIZACAO);
395 3
        $envio->setAmbiente($this->getAmbiente());
396 3
        $envio->setModelo($this->getModelo());
397 3
        $envio->setEmissao(Nota::EMISSAO_NORMAL);
398 3
        $envio->setConteudo($dom);
399 3
        $resp = $envio->envia();
400 3
        $this->loadNode($resp);
401 3
        if (!$this->isInutilizado()) {
402 1
            throw new \Exception($this->getMotivo(), $this->getStatus());
403
        }
404 2
        return $this->getReturnNode()->ownerDocument;
405
    }
406
407
    /**
408
     * Assina o XML com a assinatura eletrônica do tipo A1
409
     */
410 4
    public function assinar($dom = null)
411
    {
412 4
        if (is_null($dom)) {
413 2
            $xml = $this->getNode();
414 2
            $dom = $xml->ownerDocument;
415
        }
416 4
        $config = SEFAZ::getInstance()->getConfiguracao();
417 4
        $config->verificaValidadeCertificado();
418
419 4
        $adapter = new XmlseclibsAdapter();
420 4
        $adapter->setPrivateKey($config->getChavePrivada());
421 4
        $adapter->setPublicKey($config->getChavePublica());
422 4
        $adapter->addTransform(AdapterInterface::ENVELOPED);
423 4
        $adapter->addTransform(AdapterInterface::XML_C14N);
424 4
        $adapter->sign($dom, 'infInut');
425 4
        return $dom;
426
    }
427
428
    /**
429
     * Valida o documento após assinar
430
     */
431 4
    public function validar($dom)
432
    {
433 4
        $dom->loadXML($dom->saveXML());
434 4
        $xsd_path = dirname(__DIR__) . '/Core/schema';
435 4
        $xsd_file = $xsd_path . '/inutNFe_v3.10.xsd';
436 4
        if (!file_exists($xsd_file)) {
437
            throw new \Exception('O arquivo "'.$xsd_file.'" de esquema XSD não existe!', 404);
438
        }
439
        // Enable user error handling
440 4
        $save = libxml_use_internal_errors(true);
441 4
        if ($dom->schemaValidate($xsd_file)) {
442 3
            libxml_use_internal_errors($save);
443 3
            return $dom;
444
        }
445 1
        $msg = array();
446 1
        $errors = libxml_get_errors();
447 1
        foreach ($errors as $error) {
448 1
            $msg[] = 'Não foi possível validar o XML: '.$error->message;
449
        }
450 1
        libxml_clear_errors();
451 1
        libxml_use_internal_errors($save);
452 1
        throw new ValidationException($msg);
453
    }
454
}
455