Completed
Push — master ( 662e39...f47b5a )
by Roberto
16:11 queued 14:04
created

Base::buildSoapHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
ccs 0
cts 15
cp 0
rs 9.4285
cc 1
eloc 15
nc 1
nop 0
crap 2
1
<?php
2
3
namespace NFePHP\Esfinge;
4
5
use InvalidArgumentException;
6
use NFePHP\Esfinge\Soap\CurlSoap;
7
use NFePHP\Esfinge\Files\FileFolders;
8
9
class Base
10
{
11
    
12
    protected $errors;
13
    /**
14
     * tpAmb
15
     * @var int
16
     */
17
    protected $tpAmb = 2;
18
    /**
19
     * ambiente
20
     * @var string
21
     */
22
    protected $ambiente = 'homologacao';
23
    /**
24
     * Diretorio para gravar arquivos de LOG
25
     * @var string
26
     */
27
    protected $pathFiles = '';
28
    /**
29
     * aConfig
30
     * @var array
31
     */
32
    protected $aConfig = array();
33
    /**
34
     * aProxy
35
     * @var array
36
     */
37
    protected $aProxy = array();
38
    /**
39
     * soapTimeout
40
     * @var int
41
     */
42
    protected $soapTimeout = 10;
43
    /**
44
     * oSoap
45
     * @var Object Class
46
     */
47
    protected $oSoap;
48
    /**
49
     * soapDebug
50
     * @var string
51
     */
52
    protected $soapDebug = '';
53
        /**
54
     * Header da mensagem SOAP
55
     * @var string
56
     */
57
    protected $header;
58
    /**
59
     * Nome do usuário do sistema
60
     * @var string
61
     */
62
    protected $username;
63
    /**
64
     * Password do usuário do sistema
65
     * @var string
66
     */
67
    protected $password;
68
    /**
69
     * Código da Unidade Gestora conforme informado pelo serviço listar
70
     * da tabela unidades gestoras
71
     * @var string
72
     */
73
    protected $codigoUnidadeGestora;
74
    
75
    /**
76
     * Contrutor
77
     * @param string $configJson
78
     */
79
    public function __construct($configJson = '')
80
    {
81
        if (empty($configJson)) {
82
            throw new InvalidArgumentException('A configuração deve ser passada.');
83
        }
84
        $config = $configJson;
85
        if (is_file($configJson)) {
86
            $config = file_get_contents($configJson);
87
        }
88
        $this->aConfig = json_decode($config, true);
0 ignored issues
show
Documentation Bug introduced by
It seems like json_decode($config, true) of type * is incompatible with the declared type array of property $aConfig.

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...
89
        
90
        $this->username = $this->aConfig['username'];
91
        $this->password = $this->aConfig['password'];
92
        $this->codigoUnidadeGestora = $this->aConfig['codigoUnidadeGestora'];
93
        $this->aProxy = $this->aConfig['aProxyConf'];
94
        $this->setAmbiente($this->aConfig['tpAmb']);
95
        $this->pathFiles = $this->aConfig['pathFiles'];
96
        $this->loadSoapClass();
97
    }
98
    
99
    /**
100
     * Seta o ambiente de trabalho
101
     * 1 - Produção
102
     * 2 - Homologação
103
     * @param int $tpAmb
104
     */
105
    public function setAmbiente($tpAmb = 2)
106
    {
107
        if ($tpAmb == 1) {
108
            $this->tpAmb = 1;
109
            $this->ambiente = 'producao';
110
        } else {
111
            $this->tpAmb = 2;
112
            $this->ambiente = 'homologacao';
113
            //sobrescreve a senha que é diferente no ambiente de teste
114
            $this->password = '123456';
115
        }
116
    }
117
    
118
    /**
119
     * setSoapTimeOut
120
     * Seta um valor para timeout
121
     *
122
     * @param integer $segundos
123
     */
124
    public function setSoapTimeOut($segundos = 10)
125
    {
126
        if (! empty($segundos)) {
127
            $this->soapTimeout = $segundos;
128
            $this->loadSoapClass();
129
        }
130
    }
131
    
132
    /**
133
     * getSoapTimeOut
134
     * Retorna o valor de timeout defido
135
     *
136
     * @return integer
137
     */
138
    public function getSoapTimeOut()
139
    {
140
        return $this->soapTimeout;
141
    }
142
    
143
    /**
144
     * Grava as mensagens em disco
145
     *
146
     * @param string $data conteudo a ser gravado
147
     * @param string $filename
148
     * @param int $tpAmb
149
     * @param string $folder
150
     * @param string $subFolder
151
     * @throws RuntimeException
152
     */
153
    protected function gravaLog(
154
        $data,
155
        $filename,
156
        $tpAmb = '2',
157
        $folder = '',
158
        $subFolder = ''
159
    ) {
160
        $anomes = date('Ym');
161
        $pathTemp = $folder
162
            . Files\FilesFolders::getAmbiente($tpAmb)
0 ignored issues
show
Bug introduced by
The method getAmbiente() does not seem to exist on object<NFePHP\Esfinge\Files\FilesFolders>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
163
            . DIRECTORY_SEPARATOR
164
            . $subFolder
165
            . DIRECTORY_SEPARATOR
166
            . $anomes;
167
        if (! Files\FilesFolders::saveFile($pathTemp, $filename, $data)) {
0 ignored issues
show
Bug introduced by
The method saveFile() does not seem to exist on object<NFePHP\Esfinge\Files\FilesFolders>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
168
            $msg = 'Falha na gravação no diretório. '.$pathTemp;
169
            throw new RuntimeException($msg);
170
        }
171
    }
172
173
    /**
174
     * Monta as tags com base na chave e no valor do array
175
     * @param array $data
176
     * @return string
177
     */
178
    protected function addTag($data)
179
    {
180
        $ret = '';
181
        foreach ($data as $key => $value) {
182
            $ret .= "<$key>$value</$key>";
183
        }
184
        return $ret;
185
    }
186
    
187
    /**
188
     * Monta o conjunto de Body na função enviar
189
     * @param string $key
190
     * @param array $data
191
     * @return string
192
     */
193
    protected function buildEnviarB($key, $data)
194
    {
195
        if (count($data) > 5000) {
196
            throw new InvalidArgumentException('O limite de 5000 dados foi ultrapassado.');
197
        }
198
        $msg = '';
199
        foreach ($data as $field) {
200
            $msg .= "<$key>";
201
            $msg .= $this->addTag($field);
202
            $msg .= "</$key>";
203
        }
204
        $msg .= '</enviar>';
205
        return $msg;
206
    }
207
    
208
    /**
209
     * Monta o conjunto Body da função Listar
210
     * @param string $pagina
211
     * @param array $filtros
212
     * @return string
213
     */
214
    protected function buildListarB($pagina = '', $filtros = [])
215
    {
216
        $msg = '<PAGINA>'.$pagina.'</PAGINA>';
217
        foreach ($filtros as $filtro) {
218
            $f = '<filtros>';
219
            $f .= $this->addTag($filtro);
220
            $f .= '</filtros>';
221
            $msg .= $f;
222
        };
223
        $msg .= '</listar>';
224
        return $msg;
225
    }
226
    
227
    /**
228
     * Monta a primeira parte de todas mensagens
229
     * @param string $namespace
230
     * @return string
231
     */
232
    protected function buildMsgH($tipo, $namespace)
233
    {
234
        $key = 'enviar';
235
        $codug = '';
236
        if ($tipo == 'L') {
237
            $key = 'listar';
238
            $codug = "<codigoUg>$this->codigoUnidadeGestora</codigoUg>";
239
        }
240
        $msg = "<$key xmlns=\"$namespace\">";
241
        $msg .= $codug;
242
        $msg .= "<chaveToken>$this->token</chaveToken>";
0 ignored issues
show
Bug introduced by
The property token does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
243
        $msg .= "<competencia>$this->competencia</competencia>";
0 ignored issues
show
Bug introduced by
The property competencia does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
244
        return $msg;
245
    }
246
    
247
    /**
248
     * Monta o corpo de todas as mensagens
249
     * @param string $tipo
250
     * @param array $data
251
     * @return string
252
     */
253
    protected function buildMsgB($tipo, $data)
254
    {
255
        if ($tipo == 'L') {
256
            $msg = $this->buildListarB($pagina, $filtros);
0 ignored issues
show
Bug introduced by
The variable $pagina 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...
Bug introduced by
The variable $filtros 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...
257
        } elseif ($tipo == 'E') {
258
            $msg = $this->buildEnviarB($key, $data);
0 ignored issues
show
Bug introduced by
The variable $key 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...
259
        }
260
        return $msg;
0 ignored issues
show
Bug introduced by
The variable $msg 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...
261
    }
262
263
    /**
264
     * Constroi o header da mensagem SOAP
265
     */
266
    protected function buildSoapHeader()
267
    {
268
        $this->header = "<wsse:Security "
269
            . "xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" "
270
            . "soap:mustUnderstand=\"1\">"
271
            . "<wsse:UsernameToken "
272
            . "xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
273
            . "<wsse:Username>"
274
            . $this->username
275
            . "</wsse:Username><wsse:Password "
276
            . "Type=\"http://docs.oasis-open.org/wss/2004/01/"
277
            . "oasis-200401-wss-username-token-profile-1.0#PasswordText\">"
278
            . $this->password
279
            . "</wsse:Password>"
280
            . "</wsse:UsernameToken>"
281
            . "</wsse:Security>";
282
    }
283
    
284
    /**
285
     * Envia a mensagem para o webservice
286
     *
287
     * @param string $urlService
0 ignored issues
show
Bug introduced by
There is no parameter named $urlService. 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...
288
     * @param strting $body
0 ignored issues
show
Bug introduced by
There is no parameter named $body. 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...
289
     * @param string $method
290
     * @return string
291
     */
292
    protected function envia($uri, $namespace, $data, $method, $met)
293
    {
294
        //constroi a mensagem
295
        $body = $this->buildMsgH($method, $namespace);
296
        $body .= $this->buildMsgB($method, $data);
297
        
298
        try {
299
            $retorno = $this->oSoap->send($uri, '', '', $body, $this->xmlns.$method);
0 ignored issues
show
Bug introduced by
The property xmlns does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
300
        } catch (RuntimeException $e) {
0 ignored issues
show
Bug introduced by
The class NFePHP\Esfinge\RuntimeException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
301
            $msg = $this->oSoap->infoCurl['http_code'] . ' - ' . $this->oSoap->errorCurl;
302
            throw new RuntimeException($msg);
303
        }
304
        $resp = Response::readReturn($met, $retorno);
0 ignored issues
show
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...
305
        //salvar os arquivos para LOG
306
    }
307
    
308
    /**
309
     * Carrega a classe SOAP e os certificados
310
     */
311
    protected function loadSoapClass()
312
    {
313
        $this->oSoap = null;
314
        //if (! is_object($soap)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
315
            $soap = new CurlSoap(
316
                $this->soapTimeout,
317
                $this->aProxy
318
            );
319
        //}
320
        $this->oSoap = $soap;
321
    }
322
}
323