Test Failed
Push — master ( ac6f10...746f45 )
by Francimar
07:32
created

Estatico::getNotasTarefas()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
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\Database;
29
30
use NFe\Common\Util;
31
use NFe\Core\Nota;
32
33
class Estatico extends Banco
34
{
35
36
    private $ibpt;
37
    private $uf_codes;
38
    private $mun_codes;
39
    private $servicos;
40
    private $data_dir;
41
42 103
    public function __construct($estatico = [])
43
    {
44 103
        parent::__construct($estatico);
45 103
        $this->data_dir = __DIR__ . '/data';
46 103
        $this->load();
47 103
    }
48
49 103
    public function load()
50
    {
51 103
        $json = file_get_contents($this->data_dir . '/uf_ibge_code.json');
52 103
        $this->uf_codes = json_decode($json, true);
53 103
        if ($this->uf_codes === false || is_null($this->uf_codes)) {
54
            throw new \Exception('Falha ao carregar os códigos das unidades federadas', json_last_error());
55
        }
56 103
        $json = file_get_contents($this->data_dir . '/municipio_ibge_code.json');
57 103
        $this->mun_codes = json_decode($json, true);
58 103
        if ($this->mun_codes === false || is_null($this->mun_codes)) {
59
            throw new \Exception('Falha ao carregar os códigos dos municípios', json_last_error());
60
        }
61 103
        $json = file_get_contents($this->data_dir . '/servicos.json');
62 103
        $this->servicos = json_decode($json, true);
63 103
        if ($this->servicos === false || is_null($this->servicos)) {
64
            throw new \Exception('Falha ao carregar serviços da SEFAZ', json_last_error());
65
        }
66 103
    }
67
68 38
    public function getIBPT()
69
    {
70 38
        return $this->ibpt;
71
    }
72
73 103
    public function setIBPT($ibpt)
74
    {
75 103
        $this->ibpt = $ibpt;
76 103
        return $this;
77
    }
78
79
    /**
80
     * Obtém o código IBGE do estado
81
     */
82 47
    public function getCodigoEstado($uf)
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...
83
    {
84 47
        if (!isset($this->uf_codes['estados'][strtoupper($uf)])) {
85 2
            throw new \Exception(
86 2
                sprintf('Não foi encontrado o código do IBGE para o estado "%s"', $uf),
87 2
                404
88
            );
89
        }
90 46
        $codigo = $this->uf_codes['estados'][strtoupper($uf)];
91 46
        return intval($codigo);
92
    }
93
94
    /**
95
     * Obtém o código do orgão por estado
96
     */
97 5
    public function getCodigoOrgao($uf)
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...
98
    {
99 5
        if (!isset($this->uf_codes['orgaos'][strtoupper($uf)])) {
100 1
            throw new \Exception(
101 1
                sprintf('Não foi encontrado o código do orgão para o estado "%s"', $uf),
102 1
                404
103
            );
104
        }
105 5
        $codigo = $this->uf_codes['orgaos'][strtoupper($uf)];
106 5
        return intval($codigo);
107
    }
108
109
    /**
110
     * Obtém a aliquota do imposto de acordo com o tipo
111
     */
112 36
    public function getImpostoAliquota($ncm, $uf, $ex = null, $cnpj = null, $token = null)
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...
Comprehensibility introduced by
Avoid variables with short names like $ex. 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...
113
    {
114 36
        return $this->getIBPT()->getImposto($cnpj, $token, $ncm, $uf, $ex);
115
    }
116
117
    /**
118
     * Obtém o código IBGE do município
119
     */
120 14
    public function getCodigoMunicipio($municipio, $uf)
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...
121
    {
122 14
        if (!isset($this->mun_codes['municipios'][strtoupper($uf)])) {
123 1
            throw new \Exception(
124 1
                sprintf('Não exite municípios para o estado "%s"', $uf),
125 1
                404
126
            );
127
        }
128 13
        $array = $this->mun_codes['municipios'][strtoupper($uf)];
129 13
        $elem = ['nome' => $municipio];
130 13
        $o = Util::binarySearch($elem, $array, function ($o1, $o2) {
0 ignored issues
show
Documentation introduced by
function ($o1, $o2) { ...strcasecmp($n1, $n2); } is of type object<Closure>, but the function expects a object<NFe\Common\function>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Comprehensibility introduced by
Avoid variables with short names like $o. 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...
131 13
            $n1 = Util::removeAccent($o1['nome']);
132 13
            $n2 = Util::removeAccent($o2['nome']);
133 13
            return strcasecmp($n1, $n2);
134 13
        });
135 13
        if ($o === false) {
136 1
            throw new \Exception(
137 1
                sprintf('Não foi encontrado o código do IBGE para o município "%s" do estado "%s"', $municipio, $uf),
138 1
                404
139
            );
140
        }
141 13
        return $o['codigo'];
142
    }
143
144
    /**
145
     * Obtém as notas pendentes de envio, em contingência e corrigidas após
146
     * rejeitadas
147
     */
148 2
    public function getNotasAbertas($inicio = null, $quantidade = null)
149
    {
150 2
        return []; // TODO implementar
151
    }
152
153
    /**
154
     * Obtém as notas em processamento para consulta e possível protocolação
155
     */
156 2
    public function getNotasPendentes($inicio = null, $quantidade = null)
157
    {
158 2
        return []; // TODO implementar
159
    }
160
161
    /**
162
     * Obtém as tarefas de inutilização, cancelamento e consulta de notas
163
     * pendentes que entraram em contingência
164
     */
165 2
    public function getNotasTarefas($inicio = null, $quantidade = null)
166
    {
167 2
        return []; // TODO implementar
168
    }
169
170 42
    public function getInformacaoServico($emissao, $uf, $modelo = null, $ambiente = null)
0 ignored issues
show
Complexity introduced by
This operation has 13824 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...
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...
171
    {
172
        switch ($emissao) {
173 42
            case '1':
174 1
                $emissao = Nota::EMISSAO_NORMAL;
175 1
                break;
176 42
            case '9':
177 1
                $emissao = Nota::EMISSAO_CONTINGENCIA;
178 1
                break;
179
        }
180
        switch ($modelo) {
181 42
            case '55':
182 1
                $modelo = Nota::MODELO_NFE;
183 1
                break;
184 42
            case '65':
185 1
                $modelo = Nota::MODELO_NFCE;
186 1
                break;
187
        }
188 42
        if ($modelo == Nota::MODELO_NFCE) {
189 40
            $emissao = Nota::EMISSAO_NORMAL; // NFCe envia contingência pelo webservice normal
190
        }
191 42
        if (!isset($this->servicos[$emissao])) {
192 1
            throw new \Exception(
193 1
                sprintf('Falha ao obter o serviço da SEFAZ para o tipo de emissão "%s"', $emissao),
194 1
                404
195
            );
196
        }
197 41
        $array = $this->servicos[$emissao];
198 41
        if (!isset($array[strtoupper($uf)])) {
199 1
            throw new \Exception(
200 1
                sprintf('Falha ao obter o serviço da SEFAZ para a UF "%s"', $uf),
201 1
                404
202
            );
203
        }
204 41
        $array = $array[strtoupper($uf)];
205 41
        if (!is_array($array)) {
206
            $array = $this->getInformacaoServico($emissao, $array);
207
        }
208 41
        $_modelos = [Nota::MODELO_NFE, Nota::MODELO_NFCE];
209 41
        foreach ($_modelos as $_modelo) {
210 41
            if (!isset($array[$_modelo])) {
211 1
                continue;
212
            }
213 41
            $node = $array[$_modelo];
214 41
            if (!is_array($node)) {
215
                $node = $this->getInformacaoServico($emissao, $node, $_modelo);
216
            }
217 41
            if (isset($node['base'])) {
218 4
                $base = $this->getInformacaoServico($emissao, $node['base'], $_modelo);
219 4
                $node = array_replace_recursive($node, $base);
220
            }
221 41
            $array[$_modelo] = $node;
222
        }
223 41
        if (!is_null($modelo)) {
224 41
            if (!isset($array[$modelo])) {
225 1
                throw new \Exception(
226 1
                    sprintf('Falha ao obter o serviço da SEFAZ para o modelo de nota "%s"', $modelo),
227 1
                    404
228
                );
229
            }
230 41
            $array = $array[$modelo];
231
        }
232
        switch ($ambiente) {
233 41
            case '1':
234 1
                $ambiente = Nota::AMBIENTE_PRODUCAO;
235 1
                break;
236 41
            case '2':
237 1
                $ambiente = Nota::AMBIENTE_HOMOLOGACAO;
238 1
                break;
239
        }
240 41
        if (!is_null($modelo) && !is_null($ambiente)) {
241 39
            if (!isset($array[$ambiente])) {
242 1
                throw new \Exception(
243 1
                    sprintf('Falha ao obter o serviço da SEFAZ para o ambiente "%s"', $ambiente),
244 1
                    404
245
                );
246
            }
247 38
            $array = $array[$ambiente];
248
        }
249 41
        return $array;
250
    }
251
252 3
    public function toArray($recursive = false)
253
    {
254 3
        $estatico = parent::toArray($recursive);
255 3
        $estatico['ibpt'] = $this->getIBPT();
256 3
        return $estatico;
257
    }
258
259 103
    public function fromArray($estatico = [])
260
    {
261 103
        if ($estatico instanceof Estatico) {
262 3
            $estatico = $estatico->toArray();
263 103
        } elseif (!is_array($estatico)) {
264 2
            return $this;
265
        }
266 103
        parent::fromArray($estatico);
267 103
        $this->setIBPT(new IBPT(isset($estatico['ibpt']) ? $estatico['ibpt'] : []));
0 ignored issues
show
Unused Code introduced by
The call to IBPT::__construct() has too many arguments starting with isset($estatico['ibpt'])...atico['ibpt'] : array().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
268 103
        return $this;
269
    }
270
}
271