Passed
Push — main ( aecaa1...99996f )
by Leandro
01:27
created

ItauCertificate::requestCertificate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 47
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 26
c 2
b 0
f 0
nc 5
nop 2
dl 0
loc 47
rs 9.1928
1
<?php
2
3
namespace Itau\API;
4
5
use Exception;
6
7
/**
8
 * Class Itau
9
 *
10
 * @package Itau\API
11
 */
12
class ItauCertificate
13
{
14
    public function requestCertificate(string $token, string $certificadoCSR)
15
    {
16
        $endpoint = 'https://sts.itau.com.br/seguranca/v1/certificado/solicitacao';
17
        $headers = [
18
            'Content-Type: text/plain',
19
            'Authorization: Bearer ' . $token
20
        ];
21
22
        $curl = curl_init();
23
24
        curl_setopt_array($curl, [
25
            CURLOPT_URL => $endpoint,
26
            CURLOPT_HTTPHEADER => $headers,
27
            CURLOPT_RETURNTRANSFER => true,
28
            CURLOPT_CUSTOMREQUEST => 'POST',
29
            CURLOPT_POSTFIELDS => $certificadoCSR,
30
        ]);
31
32
        $response = curl_exec($curl);
33
34
        if ($response === false) {
35
            $error = curl_error($curl);
36
            curl_close($curl);
37
            throw new Exception('CURL Error: ' . $error, 100);
38
        }
39
40
        $statusCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
41
        curl_close($curl);
42
43
        // Verifica status HTTP
44
        if ($statusCode >= 400) {
45
            throw new Exception("HTTP Error: $statusCode - $response", $statusCode);
46
        }
47
48
        // Lógica para 204
49
        if ($statusCode === 204) {
50
            return [
51
                'status_code' => 204
52
            ];
53
        }
54
55
        // Verifica resposta vazia
56
        if (empty($response)) {
57
            throw new Exception('Empty response received from server.', $statusCode);
58
        }
59
60
        return $response;
61
    }
62
}
63