Completed
Push — master ( 2e6799...38feca )
by Roberto
06:15 queued 03:49
created

BaseTools::__construct()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 41
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 41
ccs 0
cts 33
cp 0
rs 6.7272
cc 7
eloc 29
nc 7
nop 2
crap 56
1
<?php
2
3
namespace NFePHP\eFinanc;
4
5
/**
6
 * Classe Tools, executa a comunicação com o webservice do e-Financeira
7
 *
8
 * @category  NFePHP
9
 * @package   NFePHP\eFinanc\Factory\BaseTools
10
 * @copyright Copyright (c) 2016
11
 * @license   http://www.gnu.org/licenses/lesser.html LGPL v3
12
 * @author    Roberto L. Machado <linux.rlm at gmail dot com>
13
 * @link      http://github.com/nfephp-org/sped-efinanceira for the canonical source repository
14
 */
15
16
use NFePHP\Common\Certificate\Pkcs12;
17
use NFePHP\Common\DateTime\DateTime;
18
use NFePHP\Common\Dom\Dom;
19
use NFePHP\Common\Soap\CurlSoap;
20
use NFePHP\Common\Files;
21
use RuntimeException;
22
use InvalidArgumentException;
23
24
class BaseTools
25
{
26
    public $errors;
27
    
28
        /**
29
     * verAplic
30
     * Versão da aplicação
31
     * @var string
32
     */
33
    public $verAplic = '';
34
    /**
35
     * certExpireTimestamp
36
     * TimeStamp com a data de vencimento do certificado
37
     * @var double
38
     */
39
    public $certExpireTimestamp = 0;
40
    /**
41
     * String com a data de expiração da validade
42
     * do certificado digital no9 formato dd/mm/aaaa
43
     *
44
     * @var string
45
     */
46
    public $certExpireDate = '';
47
    /**
48
     * tpAmb
49
     * @var int
50
     */
51
    public $tpAmb = 2;
52
    /**
53
     * ambiente
54
     * @var string
55
     */
56
    public $ambiente = 'homologacao';
57
    /**
58
     * aConfig
59
     * @var array
60
     */
61
    public $aConfig = array();
62
    /**
63
     * sslProtocol
64
     * @var int
65
     */
66
    public $sslProtocol = 0;
67
    /**
68
     * soapTimeout
69
     * @var int
70
     */
71
    public $soapTimeout = 10;
72
    /**
73
     * oCertificate
74
     * @var Object Class
75
     */
76
    public $oCertificate;
77
    /**
78
     * oSoap
79
     * @var Object Class
80
     */
81
    public $oSoap;
82
    /**
83
     * soapDebug
84
     * @var string
85
     */
86
    public $soapDebug = '';
87
    /**
88
     * XMLNS namespace
89
     * @var string
90
     */
91
    public $xmlns = "http://sped.fazenda.gov.br/";
92
    
93
    /**
94
     * __construct
95
     *
96
     * @param string $configJson
97
     * @param bool   $ignore default false usado para testes apenas
98
     * @throws InvalidArgumentException
99
     * @throws RuntimeException
100
     */
101
    public function __construct($configJson = '', $ignore = false)
102
    {
103
        if ($configJson == '') {
104
            $msg = 'O arquivo de configuração no formato JSON deve ser passado para a classe.';
105
            throw new InvalidArgumentException($msg);
106
        }
107
        if (is_file($configJson)) {
108
            $configJson = Files\FilesFolders::readFile($configJson);
109
        }
110
        //carrega os dados de configuração
111
        $this->aConfig      = (array) json_decode($configJson, true);
112
        $this->aProxyConf   = (array) $this->aConfig['aProxyConf'];
0 ignored issues
show
Bug introduced by
The property aProxyConf 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...
113
        $this->verAplic     = $this->aConfig['verAplic'];
114
        //seta o timezone
115
        DateTime::tzdBR($this->aConfig['siglaUF']);
116
        //carrega os certificados
117
        $this->oCertificate = new Pkcs12(
118
            $this->aConfig['pathCertsFiles'],
119
            $this->aConfig['cnpj'],
120
            '',
121
            '',
122
            '',
123
            $ignore
124
        );
125
        $timestampnow = gmmktime(0, 0, 0, date("m"), date("d"), date("Y"));
126
        if ($this->oCertificate->expireTimestamp == 0 || $this->oCertificate->expireTimestamp < $timestampnow) {
127
            //tentar carregar novo certificado
128
            $this->atualizaCertificado(
129
                $this->aConfig['pathCertsFiles'].$this->aConfig['certPfxName'],
130
                $this->aConfig['certPassword']
131
            );
132
            if ($this->oCertificate->expireTimestamp == 0 || $this->oCertificate->expireTimestamp < $timestampnow) {
133
                $msg = 'Não existe certificado válido disponível. Atualize o Certificado.';
134
                throw new RuntimeException($msg);
135
            }
136
        }
137
        $this->setAmbiente($this->aConfig['tpAmb']);
138
        $this->certExpireTimestamp = $this->oCertificate->expireTimestamp;
139
        $this->certExpireDate = date('d/m/Y', $this->certExpireTimestamp);
140
        $this->loadSoapClass();
141
    }
142
    
143
   /**
144
    * getCertTimestamp
145
    * Retorna o timestamp para a data de vencimento do Certificado
146
    *
147
    * @return int
148
    */
149
    public function getCertTimestamp()
150
    {
151
        return $this->certExpireTimestamp;
152
    }
153
154
   /**
155
    * getCertValidity
156
    * Retorna o timestamp para a data de vencimento do Certificado
157
    *
158
    * @return int
159
    */
160
    public function getCertValidity()
161
    {
162
        return $this->certExpireDate;
163
    }
164
    
165
    /**
166
     * setSSLProtocol
167
     * Força o uso de um determinado protocolo de encriptação
168
     * na comunicação https com a SEFAZ usando cURL
169
     * Apenas é necessário quando a versão do PHP e do libssl não
170
     * consegue estabelecer o protocolo correto durante o handshake
171
     * @param string $protocol
172
     */
173
    public function setSSLProtocol($protocol = '')
174
    {
175
        if (! empty($protocol)) {
176
            switch ($protocol) {
177
                case 'TLSv1':
178
                    $this->sslProtocol = 1;
179
                    break;
180
                case 'SSLv2':
181
                    $this->sslProtocol = 2;
182
                    break;
183
                case 'SSLv3':
184
                    $this->sslProtocol = 3;
185
                    break;
186
                case 'TLSv1.0':
187
                    $this->sslProtocol = 4;
188
                    break;
189
                case 'TLSv1.1':
190
                    $this->sslProtocol = 5;
191
                    break;
192
                case 'TLSv1.2':
193
                    $this->sslProtocol = 6;
194
                    break;
195
                default:
196
                    $this->sslProtocol = 0;
197
            }
198
            $this->loadSoapClass();
199
        }
200
    }
201
    
202
    /**
203
     * getSSLProtocol
204
     * Retorna o protocolo que está setado
205
     * Se for indicada qualquer opção no parametro será retornada as possiveis
206
     * opções para o protocolo SSL
207
     *
208
     * @return string | array protocolo setado ou array de opções
209
     */
210
    public function getSSLProtocol($opt = '')
211
    {
212
        $aPr = array('automatic','TLSv1','SSLv2','SSLv3','TLSv1.0','TLSv1.1','TLSv1.2');
213
        if ($opt == '') {
214
            return $aPr[$this->sslProtocol];
215
        }
216
        return $aPr;
217
    }
218
    
219
    /**
220
     * setSoapTimeOut
221
     * Seta um valor para timeout
222
     *
223
     * @param integer $segundos
224
     */
225
    public function setSoapTimeOut($segundos = 10)
226
    {
227
        if (! empty($segundos)) {
228
            $this->soapTimeout = $segundos;
229
            $this->loadSoapClass();
230
        }
231
    }
232
    
233
    /**
234
     * getSoapTimeOut
235
     * Retorna o valor de timeout defido
236
     *
237
     * @return integer
238
     */
239
    public function getSoapTimeOut()
240
    {
241
        return $this->soapTimeout;
242
    }
243
    
244
    /**
245
     * setAmbiente
246
     * Seta a varável de ambiente
247
     *
248
     * @param string $tpAmb
249
     */
250
    protected function setAmbiente($tpAmb = '2')
251
    {
252
        $this->tpAmb = $tpAmb;
0 ignored issues
show
Documentation Bug introduced by
The property $tpAmb was declared of type integer, but $tpAmb is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
253
        $this->ambiente = 'homologacao';
254
        if ($tpAmb == '1') {
255
            $this->ambiente = 'producao';
256
        }
257
    }
258
    
259
    /**
260
     * atualizaCertificado
261
     * Permite a atualização de um novo certificado já colocado na pasta dos
262
     * certificados definida no config.json
263
     *
264
     * @param string $certpfx certificado pfx em string ou o nome do arquivo do certificado
265
     * @param string $senha senha para abrir o certificado
266
     * @return boolean
267
     */
268
    public function atualizaCertificado($certpfx = '', $senha = '')
269
    {
270
        if ($certpfx == '' && $senha != '') {
271
            return false;
272
        }
273
        if (is_file($certpfx)) {
274
            $this->oCertificate->loadPfxFile($certpfx, $senha);
275
            return true;
276
        }
277
        $this->oCertificate->loadPfx($certpfx, $senha);
278
        $this->loadSoapClass();
279
        return true;
280
    }
281
    
282
    /**
283
     * Grava as mensagens em disco
284
     *
285
     * @param string $data conteudo a ser gravado
286
     * @param string $filename
287
     * @param int $tpAmb
288
     * @param string $folder
289
     * @param string $subFolder
290
     * @throws RuntimeException
291
     */
292
    protected function gravaFile(
293
        $data,
294
        $filename,
295
        $tpAmb = '2',
296
        $folder = '',
297
        $subFolder = ''
298
    ) {
299
        $anomes = date('Ym');
300
        $pathTemp = $folder
301
            . Files\FilesFolders::getAmbiente($tpAmb)
302
            . DIRECTORY_SEPARATOR
303
            . $subFolder
304
            . DIRECTORY_SEPARATOR
305
            . $anomes;
306
        if (! Files\FilesFolders::saveFile($pathTemp, $filename, $data)) {
307
            $msg = 'Falha na gravação no diretório. '.$pathTemp;
308
            throw new RuntimeException($msg);
309
        }
310
    }
311
    
312
    /**
313
     * Carrega a classe SOAP e os certificados
314
     */
315
    protected function loadSoapClass()
316
    {
317
        $this->oSoap = null;
318
        $this->oSoap = new CurlSoap(
319
            $this->oCertificate->priKeyFile,
320
            $this->oCertificate->pubKeyFile,
321
            $this->oCertificate->certKeyFile,
322
            $this->soapTimeout,
323
            $this->sslProtocol
324
        );
325
    }
326
    
327
    /**
328
     * Retorna uma seguencia não sujeita a repetição indicando
329
     * o ano, mes, dia, hora, minuto e segundo
330
     * Este retorno é usado para nomear os arquivos de log das
331
     * comunicações SOAP enviadas e retornadas
332
     *
333
     * @return string sequencia AAAMMDDHHMMSS
334
     */
335
    protected function generateMark()
336
    {
337
        return date('YmdHis');
338
    }
339
    
340
    /**
341
     * Envia a mensagem para o webservice
342
     *
343
     * @param string $urlService
344
     * @param strting $body
345
     * @param string $method
346
     * @return string
347
     */
348
    public function zSend($urlService, $body, $method)
349
    {
350
        try {
351
            $retorno = $this->oSoap->send($urlService, '', '', $body, $this->xmlns.$method);
352
        } catch (\NFePHP\Common\Exception\RuntimeException $e) {
353
            $msg = $this->oSoap->infoCurl['http_code'] . ' - ' . $this->oSoap->errorCurl;
354
            throw new \RuntimeException($msg);
355
        }
356
        $aRet = [
357
            'retorno'=>$retorno,
358
            'lastMsg' => $this->oSoap->lastMsg,
359
            'soapDebug' => $this->oSoap->soapDebug
360
        ];
361
        return $aRet;
362
    }
363
}
364