Completed
Pull Request — master (#9)
by Roberto
04:28
created

Tools::token()   D

Complexity

Conditions 17
Paths 16

Size

Total Lines 110
Code Lines 75

Duplication

Lines 37
Ratio 33.64 %

Code Coverage

Tests 0
CRAP Score 306

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 37
loc 110
ccs 0
cts 77
cp 0
rs 4.8361
cc 17
eloc 75
nc 16
nop 1
crap 306

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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_O = 'O';
13
    const TK_I = 'I';
14
    const TK_F = 'F';
15
    const TK_C = 'C';
16
    const TK_S = '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
    private $competencia;
33
    /**
34
     * Token de segurança e queue
35
     * hash com 36 caracteres aleatórios
36
     * @var string
37
     */
38
    private $tokenid;
39
    /**
40
     * Flag iniciar tranferencia
41
     * @var bool
42
     */
43
    private $flagIniciar = false;
44
    /**
45
     * Datahora da ultima solicitação da situação do token
46
     * @var timestramp
47
     */
48
    private $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 = 'O')
93
    {
94
        $uri = $this->url[$this->tpAmb].'/esfinge/services/tokenWS';
95
        $namespace = 'http://token.ws.tce.sc.gov.br/';
96
        
97
        switch ($method) {
98
            case 'C':
99
                if ($this->flagIniciar === false) {
100
                    //não está iniciada a tranferencia então não dá para cancelar
101
                    throw new RuntimeException('A tranferencia não foi iniciada, então não pode ser cancelada');
102
                }
103
                //cancela as operações realizadas com um determinado token
104
                //se OK o token é removido e todas as operações com ele
105
                //realizadas são descartadas
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 = "<cancelarTransferencia xmlns=\"$namespace\">"
109
                    . "<chaveToken>$this->tokenid</chaveToken>"
110
                    . "</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 'F':
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
                if ($this->flagIniciar === false) {
120
                    //não está iniciada a tranferencia então não dá para finalizar
121
                    throw new RuntimeException('A tranferencia não foi iniciada, então não pode ser finalizada');
122
                }
123
                //Ao final da transferência caso queria confirmar todos os elementos inseridos
124
                //(que não retornaram erro) nesta sessão, ou seja todos os elementos ligados a
125
                //determinado token passado para o serviço. Uma vez executado este serviço
126
                //o token atual será descartado.
127
                $met = 'finalizarTransferencia';
128
                $body = "<finalizarTransferencia xmlns=\"$namespace\">"
129
                    . "<chaveToken>$this->tokenid</chaveToken>"
130
                    . "</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 View Code Duplication
            case 'I':
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
                if ($this->tokenid == '') {
140
                    //não é possivel iniciar sem um token valido
141
                    throw new RuntimeException('Não é possivel iniciar a tranferência sem um token valido');
142
                }
143
                //Antes de iniciar a transferência dos dados propriamente dita será necessário executar
144
                //o serviço iniciarTransferencia
145
                $met = 'iniciarTransferencia';
146
                $body = "<iniciarTransferencia xmlns=\"$namespace\">"
147
                    . "<chaveToken>$this->tokenid</chaveToken>"
148
                    . "</iniciarTransferencia>";
149
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
150
                $resp =  Response::readReturn($met, $retorno);
151
                if ($resp['bStat']) {
152
                    $this->flagIniciar = true;
153
                }
154
                break;
155
            case 'O':
156
                if ($this->tokenid != '') {
157
                    //já existe um token
158
                    throw new RuntimeException('Já existe um token aberto.');
159
                }
160
                $met = 'obterToken';
161
                $body = "<obterToken xmlns=\"$namespace\">"
162
                    . "<codigoUg>$this->codigoUnidadeGestora</codigoUg>"
163
                    . "</obterToken>";
164
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
165
                $resp =  Response::readReturn($met, $retorno);
166
                if ($resp['bStat'] && $resp['chaveToken'] != '') {
167
                    $this->tokenid = $resp['chaveToken'];
168
                }
169
                break;
170
            case 'S':
171
                //Retorna a situação do token passado como parâmetro. Para evitar solicitações
172
                //indefinidas a este serviço o sistema punirá com a remoção do token da fila
173
                //sempre que for feita duas chamadas seguidas do serviço obterSituacaoToken
174
                //em menos de cinco segundos.
175
                if ($this->tokenid == '') {
176
                    //não é possivel verificar o token
177
                    throw new RuntimeException('Não existe um token aberto.');
178
                }
179
                //se tentativa de verificação ocorrer em menos de 2 seg
180
                //retorna como OK
181
                if ((time()-$this->tsLastSitToken) <= 2) {
182
                    $resp = [
183
                        'bStat' => true,
184
                        'message' => 'Situação token obtida com sucesso',
185
                        'status' => 'OK',
186
                        'posicao' => 1,
187
                        'situacao' => 'Pronto para envio ou consulta'
188
                    ];
189
                    break;
190
                }
191
                $met = 'obterSituacaoToken';
192
                $body = "<obterSituacaoToken xmlns=\"$namespace\">"
193
                    . "<chaveToken>$this->tokenid</chaveToken>"
194
                    . "</obterSituacaoToken>";
195
                $retorno = $this->oSoap->send($uri, $namespace, $this->header, $body, $met);
196
                $resp =  Response::readReturn($met, $retorno);
197
                $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...
198
                break;
199
        }
200
        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...
201
    }
202
    
203
    /**
204
     * Servidor
205
     * @param array $data
206
     * @param string $method
207
     * @return array
208
     */
209
    public function servidor($data = array(), $method = 'L')
210
    {
211
        $uri = 'servidorWS';
0 ignored issues
show
Unused Code introduced by
$uri 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...
212
        $namespace = 'http://servidor.ws.tce.sc.gov.br/';
213
        $met = 'servidor'.$method;
214
        //obtêm o token para essa operação
215
        if ($this->tokenid == '') {
216
            $this->token('O');
217
        }
218
        if (! $this->flagIniciar) {
219
            //soliciar inicio de transferencia
220
            $this->token('I');
221
        }
222
        if ($this->tokenid != '' && $this->flagIniciar) {
223
            //constroi a mensagem
224
            $msg = $this->buildMsgH($method, $namespace);
225
            $msg .= $this->buildMsgB($method, $data);
226
            //envia a mensagem via cURL
227
            $retorno = $this->envia($msg, $body, $method);
0 ignored issues
show
Bug introduced by
The variable $body does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
228
            $resp =  Response::readReturn($met, $retorno);
0 ignored issues
show
Documentation introduced by
$retorno is of type array<string,?,{"retorno...":"?","soapDebug":"?"}>, but the function expects a string.

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...
Unused Code introduced by
$resp 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...
229
            //se sucesso
230
            $this->token('F');
231
        }
232
    }
233
    
234
    /**
235
     * Situação Servidor Folha Pagamento
236
     * @param array $data
237
     * @param string $method
238
     * @return array
239
     */
240 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...
241
    {
242
        $uri = 'situacaoServidorFolhaPagamentoWS';
0 ignored issues
show
Unused Code introduced by
$uri 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...
243
        $namespace = 'http://situacaoservidorfolhapagamento.ws.tce.sc.gov.br/';
244
        $met = 'situacaoServidorFolhaPagamento'.$method;
245
        //constroi a mensagem
246
        $msg = $this->buildMsgH($method, $namespace);
247
        $msg .= $this->buildMsgB($method, $data);
248
        //envia a mensagem via cURL
249
        $retorno = $this->envia($msg, $body, $method);
0 ignored issues
show
Bug introduced by
The variable $body does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
250
        $resp =  Response::readReturn($met, $retorno);
0 ignored issues
show
Documentation introduced by
$retorno is of type array<string,?,{"retorno...":"?","soapDebug":"?"}>, but the function expects a string.

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...
Unused Code introduced by
$resp 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...
251
    }
252
253
    /**
254
     * Componentes Folha Pagamento
255
     * @param array $data
256
     * @param string $method
257
     * @return array
258
     */
259 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...
260
    {
261
        $uri = 'componentesFolhaPagamentoWS';
0 ignored issues
show
Unused Code introduced by
$uri 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...
262
        $namespace = 'http://componentesfolhapagamento.ws.tce.sc.gov.br/';
263
        $met = 'componentesFolhaPagamento'.$method;
264
        //constroi a mensagem
265
        $msg = $this->buildMsgH($method, $namespace);
266
        $msg .= $this->buildMsgB($method, $data);
267
        //envia a mensagem via cURL
268
        $retorno = $this->envia($msg, $body, $method);
0 ignored issues
show
Bug introduced by
The variable $body does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
269
        $resp =  Response::readReturn($met, $retorno);
0 ignored issues
show
Documentation introduced by
$retorno is of type array<string,?,{"retorno...":"?","soapDebug":"?"}>, but the function expects a string.

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...
Unused Code introduced by
$resp 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...
270
    }
271
272
    /**
273
     * Folha Pagamento
274
     * @param array $data
275
     * @param string $method
276
     * @return array
277
     */
278 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...
279
    {
280
        if (empty($data)) {
281
            return;
282
        }
283
        $uri = 'folhaPagamentoWS';
0 ignored issues
show
Unused Code introduced by
$uri 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...
284
        $namespace = 'http://folhapagamento.ws.tce.sc.gov.br/';
285
        $met = 'folhaPagamento'.$method;
286
        //constroi a mensagem
287
        $msg = $this->buildMsgH($method, $namespace);
288
        $msg .= $this->buildMsgB($method, $data);
289
        //envia a mensagem via cURL
290
        $retorno = $this->envia($msg, $body, $method);
0 ignored issues
show
Bug introduced by
The variable $body does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
291
        $resp =  Response::readReturn($met, $retorno);
0 ignored issues
show
Documentation introduced by
$retorno is of type array<string,?,{"retorno...":"?","soapDebug":"?"}>, but the function expects a string.

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...
Unused Code introduced by
$resp 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...
292
    }
293
}
294