Completed
Push — master ( 9a5b9a...15c7c2 )
by Roberto
13:36 queued 10:26
created

Tools::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 = '')
55
    {
56 6
        parent::__construct($configJson);
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
     * Operações com token
87
     * O método pode ser:
88
     *   C - cancela a transferencia
89
     *   F - finaliza a transferencia
90
     *   I - inica a transferencia
91
     *   O - Obtem o token para realizar as operações
92
     *   S - Verifica a situação do token
93
     * @param string $method
94
     */
95
    public function token($method = self::TK_OBTEM)
96
    {
97
        $uri = $this->url[$this->tpAmb].'/esfinge/services/tokenWS';
98
        $namespace = 'http://token.ws.tce.sc.gov.br/';
99
        
100
        switch ($method) {
101 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...
102
                //cancela as operações realizadas com um determinado token
103
                //se OK o token é removido e todas as operações com ele
104
                //realizadas são descartadas
105
                if ($this->flagIniciar === false) {
106
                    //não está iniciada a tranferencia então não dá para cancelar
107
                    throw new RuntimeException('A tranferencia não foi iniciada, então não pode ser cancelada');
108
                }
109
                $met = 'cancelarTransferencia';
110
                $body = "<svc:cancelarTransferencia>"
111
                    . "<chaveToken>$this->tokenid</chaveToken>"
112
                    . "</svc:cancelarTransferencia>";
113
                $resp = $this->envia($uri, $namespace, $body, '', $met);
114
                if ($resp['bStat'] && $resp['status'] == 'OK') {
115
                    //cancelamento aceito
116
                    $this->tokenid = '';
117
                    $this->flagIniciar = false;
118
                }
119
                break;
120 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...
121
                //Ao final da transferência caso queria confirmar todos os elementos inseridos
122
                //(que não retornaram erro) nesta sessão, ou seja todos os elementos ligados a
123
                //determinado token passado para o serviço. Uma vez executado este serviço
124
                //o token atual será descartado.
125
                if ($this->flagIniciar === false) {
126
                    //não está iniciada a tranferencia então não dá para finalizar
127
                    throw new RuntimeException('A tranferencia não foi iniciada, então não pode ser finalizada');
128
                }
129
                $met = 'finalizarTransferencia';
130
                $body = "<svc:finalizarTransferencia>"
131
                    . "<chaveToken>$this->tokenid</chaveToken>"
132
                    . "</svc:finalizarTransferencia>";
133
                $resp = $this->envia($uri, $namespace, $body, '', $met);
134
                if ($resp['bStat'] && $resp['status'] == 'OK') {
135
                    //finalização aceita
136
                    $this->tokenid = '';
137
                    $this->flagIniciar = false;
138
                }
139
                break;
140
            case self::TK_INICIA:
141
                //Antes de iniciar a transferência dos dados propriamente dita, será necessário executar
142
                //o serviço iniciarTransferencia
143
                if ($this->tokenid == '') {
144
                    //não é possivel iniciar sem um token valido
145
                    throw new RuntimeException('Não é possivel iniciar a tranferência sem um token valido');
146
                    //$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...
147
                }
148
                if ($this->flagIniciar === true) {
149
                    $resp = [
150
                        'bStat' => true,
151
                        'message' => 'Início de transferência liberado',
152
                        'status' => 'OK'
153
                    ];
154
                    break;
155
                }
156
                $met = 'iniciarTransferencia';
157
                $body = "<svc:iniciarTransferencia>"
158
                    . "<chaveToken>$this->tokenid</chaveToken>"
159
                    . "</svc:iniciarTransferencia>";
160
                $resp = $this->envia($uri, $namespace, $body, '', $met);
161
                if ($resp['bStat'] && $resp['status'] == 'OK') {
162
                    $this->flagIniciar = true;
163
                }
164
                break;
165
            case self::TK_OBTEM:
166
                //Retorna um token para a unidade gestora poder usar o serviço do TCE.
167
                //Permite somente um token por unidade gestora.
168 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...
169
                    $resp = [
170
                        'bStat' => true,
171
                        'message' => 'Token criado com sucesso',
172
                        'status' => 'OK',
173
                        'chaveToken' => $this->tokenid,
174
                        'posicao' => 2,
175
                        'situacao' => 'Pronto para envio ou consulta'
176
                    ];
177
                    break;
178
                }
179
                $met = 'obterToken';
180
                $body = "<svc:obterToken>"
181
                    . "<codigoUg>$this->codigoUnidadeGestora</codigoUg>"
182
                    . "</svc:obterToken>";
183
                $resp = $this->envia($uri, $namespace, $body, '', $met);
184
                if ($resp['bStat']
185
                    && $resp['chaveToken'] != ''
186
                    && $resp['status'] == 'OK'
187
                ) {
188
                    $this->tokenid = $resp['chaveToken'];
189
                }
190
                break;
191
            case self::TK_STATUS:
192
                //Retorna a situação do token passado como parâmetro. Para evitar solicitações
193
                //indefinidas a este serviço o sistema punirá com a remoção do token da fila
194
                //sempre que for feita duas chamadas seguidas do serviço obterSituacaoToken
195
                //em menos de cinco segundos.
196
                if ($this->tokenid == '') {
197
                    //não é possivel verificar o token
198
                    throw new RuntimeException('Não existe um token aberto.');
199
                }
200
                //se tentativa de verificação ocorrer em menos de 2 seg
201
                //retorna como OK
202 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...
203
                    $resp = [
204
                        'bStat' => true,
205
                        'message' => 'Situação token obtida com sucesso',
206
                        'status' => 'OK',
207
                        'posicao' => 1,
208
                        'situacao' => 'Pronto para envio ou consulta'
209
                    ];
210
                    break;
211
                }
212
                $met = 'obterSituacaoToken';
213
                $body = "<svc:obterSituacaoToken>"
214
                    . "<chaveToken>$this->tokenid</chaveToken>"
215
                    . "</svc:obterSituacaoToken>";
216
                $resp = $this->envia($uri, $namespace, $body, '', $met);
217
                $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...
218
                break;
219
        }
220
        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...
221
    }
222
    
223
    /**
224
     * Inicia o processo de tranferência de dados
225
     * @param array $data
226
     * @throws InvalidArgumentException
227
     * @throws RuntimeException
228
     */
229
    protected function obterTokenIniciarTransferencia($data = array())
230
    {
231
        if (empty($data)) {
232
            throw new InvalidArgumentException('Não foram passados dados para o método');
233
        }
234
        $this->token(self::TK_OBTEM);
235
        $this->token(self::TK_INICIA);
236
        if ($this->tokenid == '' || $this->flagIniciar === false) {
237
            throw new RuntimeException("Falha token:$this->tokenid , Iniciar: $this->flagIniciar");
238
        }
239
    }
240
241
    /**
242
     * Servidor
243
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
244
     *  se ainda não tiver iniciado -> inicia (automático)
245
     * @param array $data
246
     * @param string $method
247
     * @return array
248
     */
249 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...
250
    {
251
        $this->obterTokenIniciarTransferencia($data);
252
        $uri = $this->url[$this->tpAmb].'/esfinge/services/servidorWS';
253
        $namespace = 'http://servidor.ws.tce.sc.gov.br/';
254
        $met = 'servidor'.$method;
255
        //envia a mensagem via cURL
256
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
257
        return $resp;
258
    }
259
    
260
    /**
261
     * Situação Servidor Folha Pagamento
262
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
263
     *  se ainda não tiver iniciado -> inicia (automático)
264
     * @param array $data
265
     * @param string $method
266
     * @return array
267
     */
268 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...
269
    {
270
        $this->obterTokenIniciarTransferencia($data);
271
        $uri = $this->url[$this->tpAmb].'/esfinge/services/situacaoServidorFolhaPagamentoWS';
272
        $namespace = 'http://situacaoservidorfolhapagamento.ws.tce.sc.gov.br/';
273
        $met = 'situacaoServidorFolhaPagamento'.$method;
274
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
275
        return $resp;
276
    }
277
278
    /**
279
     * Componentes Folha Pagamento
280
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
281
     *  se ainda não tiver iniciado -> inicia (automático)
282
     * @param array $data
283
     * @param string $method
284
     * @return array
285
     */
286 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...
287
    {
288
        $this->obterTokenIniciarTransferencia($data);
289
        $uri = $this->url[$this->tpAmb].'/esfinge/services/componentesFolhaPagamentoWS';
290
        $namespace = 'http://componentesfolhapagamento.ws.tce.sc.gov.br/';
291
        $met = 'componentesFolhaPagamento'.$method;
292
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
293
        return $resp;
294
    }
295
296
    /**
297
     * Folha Pagamento
298
     *  se ainda não tiver o TOKEN -> Obtem  (automático)
299
     *  se ainda não tiver iniciado -> inicia (automático)
300
     * @param array $data
301
     * @param string $method
302
     * @return array
303
     */
304 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...
305
    {
306
        $this->obterTokenIniciarTransferencia($data);
307
        $uri = $this->url[$this->tpAmb].'/esfinge/services/folhaPagamentoWS';
308
        $namespace = 'http://folhapagamento.ws.tce.sc.gov.br/';
309
        $met = 'folhaPagamento'.$method;
310
        $resp = $this->envia($uri, $namespace, $data, $method, $met);
311
        return $resp;
312
    }
313
}
314