Skip to content

Commit c7447ba

Browse files
✨ feat: Return of the request response header
1 parent 17a11d6 commit c7447ba

File tree

6 files changed

+75
-27
lines changed

6 files changed

+75
-27
lines changed

src/Efi/ApiRequest.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,8 @@ public function send(string $method, string $route, string $scope, array $body)
6868
'error' => $e->getResponse(),
6969
'error_description' => $e->getResponse()->getBody()
7070
],
71-
$e->getResponse()->getStatusCode()
71+
$e->getResponse()->getStatusCode(),
72+
$e->getResponse()->getHeaders()
7273
);
7374
}
7475
}

src/Efi/Auth.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public function authorize()
4747
{
4848
$this->initializeRequestOptions();
4949
$response = $this->sendAuthorizationRequest();
50-
$this->processAuthorizationResponse($response);
50+
$this->processAuthorizationResponse(($this->config['responseHeaders']) ? $response->body : $response);
5151
}
5252

5353
/**

src/Efi/Config.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ public static function options(array $options): array
5454
$conf['sandbox'] = (bool) isset($options['sandbox']) ? filter_var($options['sandbox'], FILTER_VALIDATE_BOOLEAN) : false;
5555
$conf['debug'] = (bool) isset($options['debug']) ? filter_var($options['debug'], FILTER_VALIDATE_BOOLEAN) : false;
5656
$conf['cache'] = (bool) isset($options['cache']) ? filter_var($options['cache'], FILTER_VALIDATE_BOOLEAN) : true;
57+
$conf['responseHeaders'] = (bool) isset($options['responseHeaders']) ? filter_var($options['responseHeaders'], FILTER_VALIDATE_BOOLEAN) : false;
5758
$conf['timeout'] = (float) isset($options['timeout']) ? $options['timeout'] : 30.0;
5859
$conf['clientId'] = (string) isset($options['client_id']) || isset($options['clientId']) ? $options['client_id'] ?? $options['clientId'] : null;
5960
$conf['clientSecret'] = (string) isset($options['client_secret']) || isset($options['clientSecret']) ? $options['client_secret'] ?? $options['clientSecret'] : null;

src/Efi/Exception/EfiException.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
*/
1515
class EfiException extends Exception
1616
{
17+
private $headers;
1718
private $error;
1819
private $errorDescription;
1920

@@ -23,7 +24,7 @@ class EfiException extends Exception
2324
* @param mixed $exception The original exception or error response.
2425
* @param int $code The error code.
2526
*/
26-
public function __construct($api, $exception, int $code)
27+
public function __construct($api, $exception, int $code, array $headers)
2728
{
2829
$error = $exception;
2930

@@ -52,7 +53,7 @@ public function __construct($api, $exception, int $code)
5253
break;
5354
}
5455

55-
$this->handleException($exceptionClass, $error, $code);
56+
$this->handleException($exceptionClass, $error, $code, $headers);
5657
}
5758

5859
/**
@@ -78,13 +79,14 @@ private function parseStream(\GuzzleHttp\Psr7\Stream $stream)
7879
* @param array $error The error response array.
7980
* @param int $code The error code.
8081
*/
81-
private function handleException(string $exceptionClass, array $error, int $code)
82+
private function handleException(string $exceptionClass, array $error, int $code, array $headers)
8283
{
8384
$exception = new $exceptionClass($error, $code);
8485
$this->error = $exception->error;
8586
$this->errorDescription = $exception->errorDescription;
8687
$this->code = $exception->code;
8788
$this->message = $exception->message;
89+
$this->headers = $headers;
8890
}
8991

9092
/**

src/Efi/Request.php

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use GuzzleHttp\Exception\ClientException;
77
use GuzzleHttp\Exception\ServerException;
88
use Efi\Exception\EfiException;
9+
use Efi\Response;
910

1011
class Request extends BaseModel
1112
{
@@ -69,7 +70,7 @@ private function verifyCertificate(string $certificate): string
6970

7071
return $certPath;
7172
} else {
72-
$this->throwEfiException('Certificado não encontrado', 403);
73+
$this->throwEfiException('Certificado não encontrado', 403, ['headers' => []]);
7374
}
7475
}
7576

@@ -85,7 +86,7 @@ private function readCertificateFile(string $certPath): string
8586
{
8687
$fileContents = file_get_contents($certPath);
8788
if (!$fileContents) {
88-
$this->throwEfiException('Não foi possível ler o arquivo de certificado', 403);
89+
$this->throwEfiException('Não foi possível ler o arquivo de certificado', 403, ['headers' => []]);
8990
}
9091
return $fileContents;
9192
}
@@ -107,7 +108,7 @@ private function validateCertificate(string $fileContents, string $certPath): vo
107108

108109
$publicKey = openssl_x509_parse($fileContents);
109110
if (!$publicKey) {
110-
$this->throwEfiException('Certificado inválido ou inativo', 403);
111+
$this->throwEfiException('Certificado inválido ou inativo', 403, ['headers' => []]);
111112
}
112113

113114
$this->checkCertificateEnviroment($publicKey['issuer']['CN']);
@@ -125,7 +126,7 @@ private function validateCertificate(string $fileContents, string $certPath): vo
125126
private function readP12Certificate(string $fileContents): array
126127
{
127128
if (!openssl_pkcs12_read($fileContents, $certData, $this->config['pwdCertificate'])) {
128-
$this->throwEfiException('Não foi possível ler o arquivo de certificado p12', 403);
129+
$this->throwEfiException('Não foi possível ler o arquivo de certificado p12', 403, ['headers' => []]);
129130
}
130131
return $certData;
131132
}
@@ -139,9 +140,9 @@ private function readP12Certificate(string $fileContents): array
139140
private function checkCertificateEnviroment(string $issuerCn): void
140141
{
141142
if ($this->config['sandbox'] === true && ($issuerCn === 'apis.sejaefi.com.br' || $issuerCn === 'apis.efipay.com.br' || $issuerCn === 'api-pix.gerencianet.com.br')) {
142-
$this->throwEfiException('Certificado de produção inválido para o ambiente escolhido [homologação].', 403);
143+
$this->throwEfiException('Certificado de produção inválido para o ambiente escolhido [homologação].', 403, ['headers' => []]);
143144
} elseif (!$this->config['sandbox'] && ($issuerCn === 'apis-h.sejaefi.com.br' || $issuerCn === 'apis-h.efipay.com.br' || $issuerCn === 'api-pix-h.gerencianet.com.br')) {
144-
$this->throwEfiException('Certificado de homologação inválido para o ambiente escolhido [produção].', 403);
145+
$this->throwEfiException('Certificado de homologação inválido para o ambiente escolhido [produção].', 403, ['headers' => []]);
145146
}
146147
}
147148

@@ -156,7 +157,7 @@ private function checkCertificateExpiration(string $validToTime): void
156157
$today = date("Y-m-d H:i:s");
157158
$validTo = date('Y-m-d H:i:s', $validToTime);
158159
if ($validTo <= $today) {
159-
$this->throwEfiException('O certificado de autenticação expirou em ' . $validTo, 403);
160+
$this->throwEfiException('O certificado de autenticação expirou em ' . $validTo, 403, ['headers' => []]);
160161
}
161162
}
162163

@@ -166,7 +167,7 @@ private function checkCertificateExpiration(string $validToTime): void
166167
* @param string $method The HTTP method.
167168
* @param string $route The URL route.
168169
* @param array $requestOptions The request options.
169-
* @return mixed The response data.
170+
* @return object The response data.
170171
* @throws EfiException If there is an EFI Pay specific error.
171172
*/
172173

@@ -180,7 +181,7 @@ public function send(string $method, string $route, array $requestOptions)
180181
} catch (ClientException $e) {
181182
throw $this->handleClientException($e);
182183
} catch (ServerException $se) {
183-
$this->throwEfiException($se->getResponse()->getBody(), $se->getResponse()->getStatusCode());
184+
$this->throwEfiException($se->getResponse()->getBody(), $se->getResponse()->getStatusCode(), $se->getResponse()->getHeaders());
184185
}
185186
}
186187

@@ -228,21 +229,24 @@ private function mergeHeaders(array $requestOptions, array $defaultHeaders): arr
228229

229230
private function processResponse($response)
230231
{
231-
$headersResponse = $response->getHeader('Content-Type');
232+
$headersResponse = $this->config['responseHeaders'] ? $response->getHeaders() : $response->getHeader('Content-Type');
232233

233-
if (isset($headersResponse[0]) && stristr(substr($headersResponse[0], 0, strpos($headersResponse[0], ';')), 'application/json')) {
234-
return json_decode($response->getBody(), true);
234+
$contentType = isset($headersResponse['Content-Type'][0]) ? $headersResponse['Content-Type'][0] : $headersResponse[0];
235+
236+
if (stristr($contentType, 'application/json')) {
237+
$bodyResponse = json_decode($response->getBody(), true);
235238
} else {
236239
$bodyResponse = $response->getBody()->getContents();
240+
}
237241

238-
if ($bodyResponse) {
239-
return $bodyResponse;
240-
} else {
241-
return ["code" => $response->getStatusCode()];
242-
}
242+
if ($this->config['responseHeaders']) {
243+
return new Response($bodyResponse ?: ["code" => $response->getStatusCode()], $headersResponse);
243244
}
245+
246+
return $bodyResponse ?: ["code" => $response->getStatusCode()];
244247
}
245248

249+
246250
/**
247251
* Handles the ClientException and creates an EFI exception.
248252
*
@@ -252,16 +256,18 @@ private function processResponse($response)
252256

253257
private function handleClientException(ClientException $e): EfiException
254258
{
259+
$responseHeaders = $e->getResponse()->getHeaders();
255260
if (is_array(json_decode($e->getResponse()->getBody(), true))) {
256-
return new EfiException($this->config['api'], json_decode($e->getResponse()->getBody(), true), $e->getResponse()->getStatusCode());
261+
return new EfiException($this->config['api'], json_decode($e->getResponse()->getBody(), true), $e->getResponse()->getStatusCode(), $responseHeaders);
257262
} else {
258263
return new EfiException(
259264
$this->config['api'],
260265
[
261266
'error' => $e->getResponse()->getReasonPhrase(),
262267
'error_description' => $e->getResponse()->getBody()
263268
],
264-
$e->getResponse()->getStatusCode()
269+
$e->getResponse()->getStatusCode(),
270+
$responseHeaders
265271
);
266272
}
267273
}
@@ -273,12 +279,12 @@ private function handleClientException(ClientException $e): EfiException
273279
* @param int $statusCode HTTP status code.
274280
* @throws EfiException The EfiException.
275281
*/
276-
private function throwEfiException(string $message, int $statusCode): void
282+
private function throwEfiException(string $message, int $statusCode, array $headers): void
277283
{
278284
if (is_array(json_decode($message, true))) {
279-
throw new EfiException($this->config['api'], json_decode($message, true), $statusCode);
285+
throw new EfiException($this->config['api'], json_decode($message, true), $statusCode, $headers);
280286
} else {
281-
throw new EfiException($this->config['api'], ['error' => 'forbidden', 'error_description' => $message], $statusCode);
287+
throw new EfiException($this->config['api'], ['error' => 'forbidden', 'error_description' => $message], $statusCode, $headers);
282288
}
283289
}
284290
}

src/Efi/Response.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace Efi;
4+
5+
/**
6+
* Class for success responses in the Efí SDK.
7+
*/
8+
class Response
9+
{
10+
public $body;
11+
public $headers;
12+
13+
/**
14+
* Initializes a new instance of the Efi Response class.
15+
*
16+
* @param $body The body informations of response.
17+
* @param array $headers The headers informations of response.
18+
*/
19+
public function __construct($body, array $headers) {
20+
$this->body = $body;
21+
$this->headers = $headers;
22+
}
23+
24+
/**
25+
* Magic getter method to access the properties of the exception.
26+
*
27+
* @param string $property The property name.
28+
* @return mixed|null The value of the property or null if it doesn't exist.
29+
*/
30+
public function __get($property)
31+
{
32+
if (property_exists($this, $property)) {
33+
return $this->$property;
34+
}
35+
36+
return null;
37+
}
38+
}

0 commit comments

Comments
 (0)