Completed
Push — master ( f47b5a...e55be9 )
by Roberto
15:23 queued 13:17
created

Tools   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 294
Duplicated Lines 33.33 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 9.77%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 32
c 7
b 0
f 0
lcom 2
cbo 2
dl 98
loc 294
ccs 13
cts 133
cp 0.0977
rs 9.6

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setCompetencia() 0 11 4
A getCompetencia() 0 4 1
D token() 61 128 18
A obterTokenIniciarTransferencia() 0 11 4
A servidor() 10 10 1
A situacaoServidorFolhaPagamento() 9 9 1
A componentesFolhaPagamento() 9 9 1
A folhaPagamento() 9 9 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace NFePHP\Esfinge;
4
5
use InvalidArgumentException;
6
use RuntimeException;
7
use NFePHP\Esfinge\Response;
8
use NFePHP\Esfinge\Base;
9
10
class Tools extends Base
11
{
12
    const TK_Obtem = 'O';
13
    const TK_Inicia = 'I';
14
    const TK_Finaliza = 'F';
15
    const TK_Cancela = 'C';
16
    const TK_Status = 'S';
17
    
18
    /**
19
     * Endereços principais dos webservices
20
     * @var array
21
     */
22
    protected $url = [
23
        '1' => 'https://esfingews.tce.sc.gov.br',
24
        '2' => 'https://desenv2.tce.sc.gov.br:7443',
25
    ];
26
    /**
27
     * Competência bimestral no formato: AAAABB, onde:
28
     * AAAA = ano a ser enviado os dados
29
     * BB = bimestre de 01 até 06
30
     * @var string
31
     */
32
    protected $competencia;
33
    /**
34
     * Token de segurança e queue
35
     * hash com 36 caracteres aleatórios
36
     * @var string
37
     */
38
    protected $tokenid;
39
    /**
40
     * Flag iniciar tranferencia
41
     * @var bool
42
     */
43
    protected $flagIniciar = false;
44
    /**
45
     * Datahora da ultima solicitação da situação do token
46
     * @var timestramp
47
     */
48
    protected $tsLastSitToken;
49
    
50
51 6
    public function __construct($configJson = '')
52
    {
53 6
        parent::__construct($configJson);
54 3
    }
55
    
56
    /**
57
     * Define o período de competência das informações
58
     * formado AAAABB sendo BB o bimestre de 01 até 06
59
     * @param string $valor
0 ignored issues
show
Bug introduced by
There is no parameter named $valor. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
60
     */
61 9
    public function setCompetencia($aaaabb)
62
    {
63 9
        if (!is_numeric($aaaabb)) {
64 3
            throw new InvalidArgumentException('O periodo de competência é uma informação APENAS numérica.');
65
        }
66 6
        $bm = intval(substr($aaaabb, -2));
67 6
        if ($bm > 6 || $bm <= 0) {
68 3
            throw new InvalidArgumentException('O bimestre pode ser de 01 até 06 APENAS.');
69
        }
70 3
        $this->competencia = $aaaabb;
0 ignored issues
show
Documentation Bug introduced by
It seems like $aaaabb can also be of type integer or double. However, the property $competencia is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
71 3
    }
72
    
73
    /**
74
     * Retorna o período de competência informado
75
     * @return string
76
     */
77 3
    public function getCompetencia()
78
    {
79 3
        return $this->competencia;
80
    }
81
    
82
    /**
83
     * Operações com token
84
     * O método pode ser:
85
     *   C - cancela a transferencia
86
     *   F - finaliza a transferencia
87
     *   I - inica a transferencia
88
     *   O - Obtem o token para realizar as operações
89
     *   S - Verifica a situação do token
90
     * @param string $method
91
     */
92
    public function token($method = self::TK_Obtem)
93
    {
94
        $uri = $this->url[$this->tpAmb].'/esfinge/services/tokenWS';
95
        $namespace = 'http://token.ws.tce.sc.gov.br/';
96
        
97
        switch ($method) {
98 View Code Duplication
            case self::TK_Cancela:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
99
                //cancela as operações realizadas com um determinado token
100
                //se OK o token é removido e todas as operações com ele
101
                //realizadas são descartadas
102
                if ($this->flagIniciar === false) {
103
                    //não está iniciada a tranferencia então não dá para cancelar
104
                    throw new RuntimeException('A tranferencia não foi iniciada, então não pode ser cancelada');
105
                }
106
                $x = 'http://token.ws.tce.sc.gov.br/FilaAcesso/cancelarTransferencia';
0 ignored issues
show
Unused Code introduced by
$x is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
107
                $met = 'cancelarTransferencia';
108
                $body = "<svc:cancelarTransferencia>"
109
                    . "<chaveToken>$this->tokenid</chaveToken>"
110
                    . "</svc:cancelarTransferencia>";
111
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
112
                $resp =  Response::readReturn($met, $retorno);
113
                if ($resp['bStat']) {
114
                    $this->tokenid = '';
115
                    $this->flagIniciar = false;
116
                }
117
                break;
118 View Code Duplication
            case self::TK_Finaliza:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
119
                //Ao final da transferência caso queria confirmar todos os elementos inseridos
120
                //(que não retornaram erro) nesta sessão, ou seja todos os elementos ligados a
121
                //determinado token passado para o serviço. Uma vez executado este serviço
122
                //o token atual será descartado.
123
                if ($this->flagIniciar === false) {
124
                    //não está iniciada a tranferencia então não dá para finalizar
125
                    throw new RuntimeException('A tranferencia não foi iniciada, então não pode ser finalizada');
126
                }
127
                $met = 'finalizarTransferencia';
128
                $body = "<svc:finalizarTransferencia>"
129
                    . "<chaveToken>$this->tokenid</chaveToken>"
130
                    . "</svc:finalizarTransferencia>";
131
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
132
                $resp =  Response::readReturn($met, $retorno);
133
                if ($resp['bStat']) {
134
                    $this->tokenid = '';
135
                    $this->flagIniciar = false;
136
                }
137
                break;
138
            case self::TK_Inicia:
139
                //Antes de iniciar a transferência dos dados propriamente dita, será necessário executar
140
                //o serviço iniciarTransferencia
141
                if ($this->tokenid == '') {
142
                    //não é possivel iniciar sem um token valido
143
                    throw new RuntimeException('Não é possivel iniciar a tranferência sem um token valido');
144
                    //$this->token(self::TK_O);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
145
                }
146
                if ($this->flagIniciar === true) {
147
                    $resp = [
148
                        'bStat' => true,
149
                        'message' => 'Início de transferência liberado',
150
                        'status' => 'OK'
151
                    ];
152
                    break;
153
                }
154
                $met = 'iniciarTransferencia';
155
                $body = "<svc:iniciarTransferencia>"
156
                    . "<chaveToken>$this->tokenid</chaveToken>"
157
                    . "</svc:iniciarTransferencia>";
158
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
159
                $resp =  Response::readReturn($met, $retorno);
160
                if ($resp['bStat']) {
161
                    $this->flagIniciar = true;
162
                }
163
                break;
164
            case self::TK_Obtem:
165
                //Retorna um token para a unidade gestora poder usar o serviço do TCE.
166
                //Permite somente um token por unidade gestora.
167 View Code Duplication
                if ($this->tokenid != '') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
168
                    $resp = [
169
                        'bStat' => true,
170
                        'message' => 'Token criado com sucesso',
171
                        'status' => 'OK',
172
                        'chaveToken' => $this->tokenid,
173
                        'posicao' => 2,
174
                        'situacao' => 'Pronto para envio ou consulta'
175
                    ];
176
                    break;
177
                }
178
                $met = 'obterToken';
179
                $body = "<svc:obterToken>"
180
                    . "<codigoUg>$this->codigoUnidadeGestora</codigoUg>"
181
                    . "</svc:obterToken>";
182
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
183
                $resp =  Response::readReturn($met, $retorno);
184
                if ($resp['bStat'] && $resp['chaveToken'] != '') {
185
                    $this->tokenid = $resp['chaveToken'];
186
                }
187
                break;
188
            case self::TK_Status:
189
                //Retorna a situação do token passado como parâmetro. Para evitar solicitações
190
                //indefinidas a este serviço o sistema punirá com a remoção do token da fila
191
                //sempre que for feita duas chamadas seguidas do serviço obterSituacaoToken
192
                //em menos de cinco segundos.
193
                if ($this->tokenid == '') {
194
                    //não é possivel verificar o token
195
                    throw new RuntimeException('Não existe um token aberto.');
196
                }
197
                //se tentativa de verificação ocorrer em menos de 2 seg
198
                //retorna como OK
199 View Code Duplication
                if ((time()-$this->tsLastSitToken) <= 2) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
200
                    $resp = [
201
                        'bStat' => true,
202
                        'message' => 'Situação token obtida com sucesso',
203
                        'status' => 'OK',
204
                        'posicao' => 1,
205
                        'situacao' => 'Pronto para envio ou consulta'
206
                    ];
207
                    break;
208
                }
209
                $met = 'obterSituacaoToken';
210
                $body = "<svc:obterSituacaoToken>"
211
                    . "<chaveToken>$this->tokenid</chaveToken>"
212
                    . "</svc:obterSituacaoToken>";
213
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
214
                $resp =  Response::readReturn($met, $retorno);
215
                $this->tsLastSitToken = time();
0 ignored issues
show
Documentation Bug introduced by
It seems like time() of type integer is incompatible with the declared type object<NFePHP\Esfinge\timestramp> of property $tsLastSitToken.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
216
                break;
217
        }
218
        return $resp;
0 ignored issues
show
Bug introduced by
The variable $resp does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
219
    }
220
    
221
    /**
222
     * Inicia o processo de tranferência de dados
223
     * @param array $data
224
     * @throws InvalidArgumentException
225
     * @throws RuntimeException
226
     */
227
    protected function obterTokenIniciarTransferencia($data = array())
228
    {
229
        if (empty($data)) {
230
            throw new InvalidArgumentException('Não foram passados dados para o método');
231
        }
232
        $this->token(self::TK_Obtem);
233
        $this->token(self::TK_Inicia);
234
        if ($this->tokenid == '' || $this->flagIniciar === false) {
235
            throw new RuntimeException("Falha token:$this->tokenid , Iniciar: $this->flagIniciar");
236
        }
237
    }
238
239
    /**
240
     * Servidor
241
     * @param array $data
242
     * @param string $method
243
     * @return array
244
     */
245 View Code Duplication
    public function servidor($data = array(), $method = 'L')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
246
    {
247
        $this->obterTokenIniciarTransferencia($data);
248
        $uri = $this->url[$this->tpAmb].'/esfinge/services/servidorWS';
249
        $namespace = 'http://servidor.ws.tce.sc.gov.br/';
250
        $met = 'servidor'.$method;
251
        //envia a mensagem via cURL
252
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
253
        return $resp;
254
    }
255
    
256
    /**
257
     * Situação Servidor Folha Pagamento
258
     * @param array $data
259
     * @param string $method
260
     * @return array
261
     */
262 View Code Duplication
    public function situacaoServidorFolhaPagamento($data = array(), $method = 'L')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
263
    {
264
        $this->obterTokenIniciarTransferencia($data);
265
        $uri = $this->url[$this->tpAmb].'/esfinge/services/situacaoServidorFolhaPagamentoWS';
266
        $namespace = 'http://situacaoservidorfolhapagamento.ws.tce.sc.gov.br/';
267
        $met = 'situacaoServidorFolhaPagamento'.$method;
268
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
269
        return $resp;
270
    }
271
272
    /**
273
     * Componentes Folha Pagamento
274
     * @param array $data
275
     * @param string $method
276
     * @return array
277
     */
278 View Code Duplication
    public function componentesFolhaPagamento($data = array(), $method = 'L')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
279
    {
280
        $this->obterTokenIniciarTransferencia($data);
281
        $uri = $this->url[$this->tpAmb].'/esfinge/services/componentesFolhaPagamentoWS';
282
        $namespace = 'http://componentesfolhapagamento.ws.tce.sc.gov.br/';
283
        $met = 'componentesFolhaPagamento'.$method;
284
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
285
        return $resp;
286
    }
287
288
    /**
289
     * Folha Pagamento
290
     * @param array $data
291
     * @param string $method
292
     * @return array
293
     */
294 View Code Duplication
    public function folhaPagamento($data = array(), $method = 'L')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

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

Loading history...
295
    {
296
        $this->obterTokenIniciarTransferencia($data);
297
        $uri = $this->url[$this->tpAmb].'/esfinge/services/folhaPagamentoWS';
298
        $namespace = 'http://folhapagamento.ws.tce.sc.gov.br/';
299
        $met = 'folhaPagamento'.$method;
300
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
301
        return $resp;
302
    }
303
}
304