Tools   B
last analyzed

Complexity

Total Complexity 44

Size/Duplication

Total Lines 361
Duplicated Lines 26.87 %

Coupling/Cohesion

Components 2
Dependencies 1

Test Coverage

Coverage 10.49%

Importance

Changes 0
Metric Value
wmc 44
lcom 2
cbo 1
dl 97
loc 361
ccs 17
cts 162
cp 0.1049
rs 8.8798
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setCompetencia() 0 11 4
A getCompetencia() 0 4 1
A getToken() 0 4 1
A getTransferencia() 0 4 1
F token() 60 145 26
A getStringBetween() 0 11 2
A obterTokenIniciarTransferencia() 0 13 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    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Tools often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Tools, and based on these observations, apply Extract Interface, too.

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
     * Construtor
52
     * @param string $configJson
53
     */
54 6
    public function __construct($configJson = '', $debug = false)
55
    {
56 6
        parent::__construct($configJson, $debug);
57 3
    }
58
    
59
    /**
60
     * Define o período de competência das informações
61
     * formado AAAABB sendo BB o bimestre de 01 até 06
62
     * @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...
63
     */
64 9
    public function setCompetencia($aaaabb)
65
    {
66 9
        if (!is_numeric($aaaabb)) {
67 3
            throw new InvalidArgumentException('O periodo de competência é uma informação APENAS numérica.');
68
        }
69 6
        $bm = intval(substr($aaaabb, -2));
70 6
        if ($bm > 6 || $bm <= 0) {
71 3
            throw new InvalidArgumentException('O bimestre pode ser de 01 até 06 APENAS.');
72
        }
73 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...
74 3
    }
75
    
76
    /**
77
     * Retorna o período de competência informado
78
     * @return string
79
     */
80 3
    public function getCompetencia()
81
    {
82 3
        return $this->competencia;
83
    }
84
    
85
    /**
86
     * Retorna no token ativo
87
     * @return string
88
     */
89 3
    public function getToken()
90
    {
91 3
        return $this->tokenid;
92
    }
93
    
94
    /**
95
     * Retorna o status de inicio de transferencia
96
     * @return bool
97
     */
98 3
    public function getTransferencia()
99
    {
100 3
        return $this->flagIniciar;
101
    }
102
    
103
    /**
104
     * Operações com token
105
     * O método pode ser:
106
     *   C - cancela a transferencia
107
     *   F - finaliza a transferencia
108
     *   I - inica a transferencia
109
     *   O - Obtem o token para realizar as operações
110
     *   S - Verifica a situação do token
111
     * @param string $method
112
     */
113
    public function token($method = self::TK_OBTEM)
114
    {
115
        $uri = $this->url[$this->tpAmb].'/esfinge/services/tokenWS';
116
        $namespace = 'http://token.ws.tce.sc.gov.br/';
117
        
118
        switch ($method) {
119 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...
120
                //cancela as operações realizadas com um determinado token
121
                //se OK o token é removido e todas as operações com ele
122
                //realizadas são descartadas
123
                if ($this->flagIniciar === false) {
124
                    //não está iniciada a tranferencia então não dá para cancelar
125
                    throw new RuntimeException('A transferência não foi iniciada, então não pode ser cancelada');
126
                }
127
                $met = 'cancelarTransferencia';
128
                $body = "<svc:cancelarTransferencia>"
129
                    . "<chaveToken>$this->tokenid</chaveToken>"
130
                    . "</svc:cancelarTransferencia>";
131
                $resp = $this->envia($uri, $namespace, $body, '', $met);
0 ignored issues
show
Documentation introduced by
$body is of type string, but the function expects a array.

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...
132
                if ($resp['bStat'] && $resp['status'] == 'OK') {
133
                    //cancelamento aceito
134
                    $this->tokenid = '';
135
                    $this->flagIniciar = false;
136
                }
137
                break;
138 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...
139
                //Ao final da transferência caso queria confirmar todos os elementos inseridos
140
                //(que não retornaram erro) nesta sessão, ou seja todos os elementos ligados a
141
                //determinado token passado para o serviço. Uma vez executado este serviço
142
                //o token atual será descartado.
143
                if ($this->flagIniciar === false) {
144
                    //não está iniciada a tranferencia então não dá para finalizar
145
                    throw new RuntimeException('A transferência não foi iniciada, então não pode ser finalizada');
146
                }
147
                $met = 'finalizarTransferencia';
148
                $body = "<svc:finalizarTransferencia>"
149
                    . "<chaveToken>$this->tokenid</chaveToken>"
150
                    . "</svc:finalizarTransferencia>";
151
                $resp = $this->envia($uri, $namespace, $body, '', $met);
0 ignored issues
show
Documentation introduced by
$body is of type string, but the function expects a array.

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...
152
                if ($resp['bStat'] && $resp['status'] == 'OK') {
153
                    //finalização aceita
154
                    $this->tokenid = '';
155
                    $this->flagIniciar = false;
156
                }
157
                break;
158
            case self::TK_INICIA:
159
                //Antes de iniciar a transferência dos dados propriamente dita, será necessário executar
160
                //o serviço iniciarTransferencia
161
                if ($this->tokenid == '') {
162
                    //não é possivel iniciar sem um token valido
163
                    throw new RuntimeException('Não é possivel iniciar a transferência sem um token valido');
164
                }
165
                if ($this->flagIniciar === true) {
166
                    $resp = [
167
                        'bStat' => true,
168
                        'message' => 'Início de transferência liberado',
169
                        'status' => 'OK'
170
                    ];
171
                    break;
172
                }
173
                $met = 'iniciarTransferencia';
174
                $body = "<svc:iniciarTransferencia>"
175
                    . "<chaveToken>$this->tokenid</chaveToken>"
176
                    . "</svc:iniciarTransferencia>";
177
                $resp = $this->envia($uri, $namespace, $body, '', $met);
0 ignored issues
show
Documentation introduced by
$body is of type string, but the function expects a array.

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...
178
                if ($resp['bStat'] && $resp['status'] == 'OK') {
179
                    $this->flagIniciar = true;
180
                }
181
                break;
182
            case self::TK_OBTEM:
183
                //Retorna um token para a unidade gestora poder usar o serviço do TCE.
184
                //Permite somente um token por unidade gestora.
185 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...
186
                    $resp = [
187
                        'bStat' => true,
188
                        'message' => 'Token criado com sucesso',
189
                        'status' => 'OK',
190
                        'chaveToken' => $this->tokenid,
191
                        'posicao' => 2,
192
                        'situacao' => 'Pronto para envio ou consulta'
193
                    ];
194
                    break;
195
                }
196
                $met = 'obterToken';
197
                $body = "<svc:obterToken>"
198
                    . "<codigoUg>$this->codigoUnidadeGestora</codigoUg>"
199
                    . "</svc:obterToken>";
200
                $resp = $this->envia($uri, $namespace, $body, '', $met);
0 ignored issues
show
Documentation introduced by
$body is of type string, but the function expects a array.

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...
201
                if ($resp['bStat']
202
                    && $resp['chaveToken'] != ''
203
                    && $resp['status'] == 'OK'
204
                ) {
205
                    $this->tokenid = $resp['chaveToken'];
206
                }
207
                $resp1 = $resp;
208
                if ($resp['bStat'] && $resp['status'] == 'ERRO') {
209
                    $xPos = stripos('xx'.$resp['message'], "Sua unidade gestora já obteve o token com chave [");
210
                    if ($xPos !== false) {
211
                        $chave = $this->getStringBetween($resp['message'], '[', ']');
212
                        if ($chave != '') {
213
                            $this->tokenid = $chave;
214
                            $resp = [
215
                                'bStat' => true,
216
                                'message' => $resp1['message'],
217
                                'status' => 'OK',
218
                                'chaveToken' => $this->tokenid,
219
                                'posicao' => 2,
220
                                'situacao' => 'Pronto para envio ou consulta'
221
                            ];
222
                        }
223
                    }
224
                }
225
                $resp1 = null;
0 ignored issues
show
Unused Code introduced by
$resp1 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...
226
                break;
227
            case self::TK_STATUS:
228
                //Retorna a situação do token passado como parâmetro. Para evitar solicitações
229
                //indefinidas a este serviço o sistema punirá com a remoção do token da fila
230
                //sempre que for feita duas chamadas seguidas do serviço obterSituacaoToken
231
                //em menos de cinco segundos.
232
                if ($this->tokenid == '') {
233
                    //não é possivel verificar o token
234
                    throw new RuntimeException('Não existe um token aberto.');
235
                }
236
                //se tentativa de verificação ocorrer em menos de 2 seg
237
                //retorna como OK
238 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...
239
                    $resp = [
240
                        'bStat' => true,
241
                        'message' => 'Situação token obtida com sucesso',
242
                        'status' => 'OK',
243
                        'posicao' => 1,
244
                        'situacao' => 'Pronto para envio ou consulta'
245
                    ];
246
                    break;
247
                }
248
                $met = 'obterSituacaoToken';
249
                $body = "<svc:obterSituacaoToken>"
250
                    . "<chaveToken>$this->tokenid</chaveToken>"
251
                    . "</svc:obterSituacaoToken>";
252
                $resp = $this->envia($uri, $namespace, $body, '', $met);
0 ignored issues
show
Documentation introduced by
$body is of type string, but the function expects a array.

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...
253
                $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...
254
                break;
255
        }
256
        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...
257
    }
258
    
259
    /**
260
     * Extrai os dados entre dois marcadores
261
     * @param string $string
262
     * @param string $start
263
     * @param string $end
264
     * @return string
265
     */
266
    private function getStringBetween($string, $start, $end)
267
    {
268
        $string = ' ' . $string;
269
        $ini = strpos($string, $start);
270
        if ($ini == 0) {
271
            return '';
272
        }
273
        $ini += strlen($start);
274
        $len = strpos($string, $end, $ini) - $ini;
275
        return substr($string, $ini, $len);
276
    }
277
    
278
    /**
279
     * Inicia o processo de tranferência de dados
280
     * @param array $data
281
     * @throws InvalidArgumentException
282
     * @throws RuntimeException
283
     */
284
    protected function obterTokenIniciarTransferencia($data = [], $method = 'L')
285
    {
286
        if (empty($data)) {
287
            throw new InvalidArgumentException('Não foram passados dados para o método');
288
        }
289
        $this->token(self::TK_OBTEM);
290
        if ($method == 'E') {
291
            $this->token(self::TK_INICIA);
292
        }
293
        if ($this->tokenid == '') {
294
            throw new RuntimeException("Falha token:$this->tokenid , Iniciar: $this->flagIniciar");
295
        }
296
    }
297
298
    /**
299
     * Servidor
300
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
301
     *  se ainda não tiver iniciado -> inicia (automático)
302
     * @param array $data
303
     * @param string $method
304
     * @return array
305
     */
306 View Code Duplication
    public function servidor($data = [], $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...
307
    {
308
        $this->obterTokenIniciarTransferencia($data, $method);
309
        $uri = $this->url[$this->tpAmb].'/esfinge/services/servidorWS';
310
        $namespace = 'http://servidor.ws.tce.sc.gov.br/';
311
        $met = 'servidor'.$method;
312
        //envia a mensagem via cURL
313
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
314
        return $resp;
315
    }
316
    
317
    /**
318
     * Situação Servidor Folha Pagamento
319
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
320
     *  se ainda não tiver iniciado -> inicia (automático)
321
     * @param array $data
322
     * @param string $method
323
     * @return array
324
     */
325 View Code Duplication
    public function situacaoServidorFolhaPagamento($data = [], $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...
326
    {
327
        $this->obterTokenIniciarTransferencia($data, $method);
328
        $uri = $this->url[$this->tpAmb].'/esfinge/services/situacaoServidorFolhaPagamentoWS';
329
        $namespace = 'http://situacaoservidorfolhapagamento.ws.tce.sc.gov.br/';
330
        $met = 'situacaoServidorFolhaPagamento'.$method;
331
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
332
        return $resp;
333
    }
334
335
    /**
336
     * Componentes Folha Pagamento
337
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
338
     *  se ainda não tiver iniciado -> inicia (automático)
339
     * @param array $data
340
     * @param string $method
341
     * @return array
342
     */
343 View Code Duplication
    public function componentesFolhaPagamento($data = [], $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...
344
    {
345
        $this->obterTokenIniciarTransferencia($data, $method);
346
        $uri = $this->url[$this->tpAmb].'/esfinge/services/componentesFolhaPagamentoWS';
347
        $namespace = 'http://componentesfolhapagamento.ws.tce.sc.gov.br/';
348
        $met = 'componentesFolhaPagamento'.$method;
349
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
350
        return $resp;
351
    }
352
353
    /**
354
     * Folha Pagamento
355
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
356
     *  se ainda não tiver iniciado -> inicia (automático)
357
     * @param array $data
358
     * @param string $method
359
     * @return array
360
     */
361 View Code Duplication
    public function folhaPagamento($data = [], $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...
362
    {
363
        $this->obterTokenIniciarTransferencia($data, $method);
364
        $uri = $this->url[$this->tpAmb].'/esfinge/services/folhaPagamentoWS';
365
        $namespace = 'http://folhapagamento.ws.tce.sc.gov.br/';
366
        $met = 'folhaPagamento'.$method;
367
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
368
        return $resp;
369
    }
370
}
371