Skip to content

Commit cddb3bf

Browse files
Correccion PHPStan, PHPUnit, Upgrade php 8.5
1 parent d52034d commit cddb3bf

37 files changed

Lines changed: 242 additions & 219 deletions

.github/workflows/ci.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jobs:
1313

1414
strategy:
1515
matrix:
16-
php-version: ['8.4', '8.5']
16+
php-version: ['8.5']
1717

1818
steps:
1919
- name: Check out repository code
@@ -33,6 +33,7 @@ jobs:
3333
env:
3434
CONTAFI_API_TOKEN: ${{ secrets.CONTAFI_API_TOKEN }}
3535
CONTAFI_CONTRIBUYENTE_RUT: ${{ vars.CONTAFI_CONTRIBUYENTE_RUT }}
36+
ADD_SKIPPED: true
3637
run: |
3738
composer tests-readonly
3839

composer.json

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,18 @@
2020
"contafi\\api_client\\": "src/"
2121
}
2222
},
23+
"autoload-dev": {
24+
"psr-4": {
25+
"contafi\\tests\\Helpers\\": "tests/Helpers/"
26+
}
27+
},
2328
"require": {
24-
"php": "^8.4",
29+
"php": "^8.5",
2530
"guzzlehttp/guzzle": "^7.10"
2631
},
2732
"require-dev": {
2833
"friendsofphp/php-cs-fixer": "^3.94",
29-
"phpstan/phpstan": "^1.12",
34+
"phpstan/phpstan": "^2",
3035
"phpunit/phpunit": "^13.0",
3136
"vlucas/phpdotenv": "^5.6"
3237
},

phpunit.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,6 @@
6464
</logging>
6565
<php>
6666
<ini name="memory_limit" value="-1" />
67-
<env name="CONTAFI_API_URL" value="https://contafi.cl" />
67+
<env name="CONTAFI_API_URL" value="https://app.contafi.cl" />
6868
</php>
6969
</phpunit>

src/ApiBase.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ class ApiBase extends ApiClient
3636
* @param string|null $url Versión de la API.
3737
*/
3838
public function __construct(
39-
string $token = null,
40-
string $rut = null,
41-
string $url = null
39+
?string $token = null,
40+
?string $rut = null,
41+
?string $url = null
4242
) {
4343
parent::__construct($token, $rut, $url);
4444
}

src/ApiClient.php

Lines changed: 36 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,9 @@ class ApiClient
8787
* @param string|null $url URL base de la API.
8888
*/
8989
public function __construct(
90-
string $token = null,
91-
string $rut = null,
92-
string $url = null
90+
?string $token = null,
91+
?string $rut = null,
92+
?string $url = null
9393
) {
9494
$this->apiToken = $token ?: $this->env('CONTAFI_API_TOKEN');
9595
if (!$this->apiToken) {
@@ -146,7 +146,7 @@ public function setRut(string $rut): static
146146
*
147147
* @return string|null
148148
*/
149-
public function getLastUrl(): string
149+
public function getLastUrl(): ?string
150150
{
151151
return $this->lastUrl;
152152
}
@@ -156,7 +156,7 @@ public function getLastUrl(): string
156156
*
157157
* @return \Psr\Http\Message\ResponseInterface|null
158158
*/
159-
public function getLastResponse(): ResponseInterface
159+
public function getLastResponse(): ?ResponseInterface
160160
{
161161
return $this->lastResponse;
162162
}
@@ -354,60 +354,26 @@ public function consume(
354354
// realizar consulta HTTP
355355
try {
356356
$this->lastResponse = $client->request(
357-
$method,
358-
$this->lastUrl,
359-
$options
357+
method: $method,
358+
uri: $this->lastUrl,
359+
options: $options
360360
);
361-
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
361+
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
362+
// Obtener la respuesta de la llamada.
362363
$this->lastResponse = $e->getResponse();
364+
365+
// Si no es un error 401 con problema de sesión se lanza la excepción.
363366
$this->throwException();
367+
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
368+
throw new ApiException('Error de conexión con el SII: ' . $e->getMessage(), 500);
364369
}
370+
371+
// Si no se reintentó se lanza excepción por no ser código 200.
365372
if ($this->getLastResponse()->getStatusCode() != 200) {
366373
$this->throwException();
367374
}
368-
return $this;
369-
}
370-
371-
/**
372-
* Extrae información detallada sobre un error a partir de la última respuesta HTTP.
373-
*
374-
* Este método analiza la última respuesta HTTP para extraer información
375-
* detallada sobre un error que ocurrió durante la solicitud. Devuelve un
376-
* objeto con los detalles del error, incluyendo el código y el mensaje.
377-
*
378-
* @return object Detalles del error con propiedades 'code' y 'message'.
379-
*/
380-
private function getError(): object
381-
{
382-
$data = $this->getBodyDecoded();
383-
$response = $this->getLastResponse();
384-
$statusCode = $response ? $response->getStatusCode() : null;
385-
$reasonPhrase = $response ? $response
386-
->getReasonPhrase() : 'Sin respuesta';
387375

388-
if ($data) {
389-
$code = isset($data['code']) ? $data['code'] : $statusCode;
390-
$message = isset(
391-
$data['message']
392-
) ? $data['message'] : $reasonPhrase;
393-
} else {
394-
$code = $statusCode;
395-
$message = $reasonPhrase;
396-
}
397-
398-
// Se maneja el caso donde no se encuentra un mensaje de error específico
399-
if (!$message || $message === '') {
400-
$message = sprintf(
401-
'[ContaFi API] Código HTTP %d: %s',
402-
$code,
403-
$reasonPhrase
404-
);
405-
}
406-
407-
return (object)[
408-
'code' => $code,
409-
'message' => $message,
410-
];
376+
return $this;
411377
}
412378

413379
/**
@@ -422,8 +388,25 @@ private function getError(): object
422388
*/
423389
private function throwException(): ApiException
424390
{
425-
$error = $this->getError();
426-
throw new ApiException($error->message, $error->code);
391+
$response = $this->getLastResponse();
392+
393+
if (!$response) {
394+
throw new ApiException(
395+
message: 'Error desconocido.',
396+
code: 500,
397+
responseBody: null
398+
);
399+
}
400+
401+
$status = $response->getStatusCode();
402+
$body = (string) $response->getBody();
403+
$message = $body !== '' ? $body : $response->getReasonPhrase();
404+
405+
throw new ApiException(
406+
message: $message,
407+
code: $status,
408+
responseBody: $body
409+
);
427410
}
428411

429412
/**

src/ApiException.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,20 @@
3232
*/
3333
class ApiException extends \Exception
3434
{
35-
// Aquí van los métodos y propiedades de la clase
35+
private ?string $responseBody;
36+
37+
public function __construct(
38+
string $message = '',
39+
int $code = 0,
40+
?string $responseBody = null,
41+
?\Throwable $previous = null
42+
) {
43+
parent::__construct($message, $code, $previous);
44+
$this->responseBody = $responseBody;
45+
}
46+
47+
public function getResponseBody(): ?string
48+
{
49+
return $this->responseBody;
50+
}
3651
}

tests/Helpers/FunctionHelpers.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace contafi\tests\Helpers;
6+
7+
use PHPUnit\Framework\SkippedTestSuiteError;
8+
use contafi\api_client\ApiException;
9+
10+
trait FunctionHelpers
11+
{
12+
protected static function requireEnv(string $str_var): void
13+
{
14+
$value =
15+
$_ENV[$str_var]
16+
?? $_SERVER[$str_var]
17+
?? getenv($str_var);
18+
19+
if ($value == false || $value == null || $value == '') {
20+
throw new SkippedTestSuiteError(
21+
sprintf($str_var . ' no está definido.')
22+
);
23+
}
24+
}
25+
26+
protected function handleApiException(ApiException $e): void
27+
{
28+
$code = (int) $e->getCode();
29+
$message = sprintf(
30+
'[ApiException %d] %s',
31+
$code,
32+
$e->getMessage()
33+
);
34+
if ($code >= 400 && $code < 500 && env('ADD_SKIPPED', false)) {
35+
$this->markTestSkipped($message);
36+
}
37+
$this->fail($message);
38+
39+
}
40+
}

tests/sii/bhe/ListarBhesRecibidasTest.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,15 @@
2525
use contafi\api_client\client\Bhe;
2626
use PHPUnit\Framework\Attributes\CoversClass;
2727
use PHPUnit\Framework\TestCase;
28+
use contafi\tests\Helpers\FunctionHelpers;
2829

2930
#[CoversClass(Bhe::class)]
3031
/**
3132
* Clase de pruebas para listar Boletas de Honorarios Electrónicas recibidas.
3233
*/
3334
class ListarBhesRecibidasTest extends TestCase
3435
{
36+
use FunctionHelpers;
3537
/**
3638
* Variable que permite desplegar en consola los resultados.
3739
*
@@ -48,6 +50,7 @@ class ListarBhesRecibidasTest extends TestCase
4850

4951
public static function setUpBeforeClass(): void
5052
{
53+
self::requireEnv('CONTAFI_API_TOKEN');
5154
self::$verbose = env(varname: 'TEST_VERBOSE', default: false);
5255
self::$client = new Bhe();
5356
}
@@ -62,7 +65,7 @@ public static function setUpBeforeClass(): void
6265
public function testListarBhesRecibidas(): void
6366
{
6467
$filtros = [
65-
'periodo' => env(varname: 'TEST_PERIODO', default: date('Ym')),
68+
'periodo' => env('TEST_PERIODO') ?: date('Ym'),
6669
];
6770
try {
6871
$response = self::$client->listado($filtros);
@@ -76,11 +79,7 @@ public function testListarBhesRecibidas(): void
7679
"\n";
7780
}
7881
} catch (ApiException $e) {
79-
throw new ApiException(message: sprintf(
80-
'[ApiException %d] %s',
81-
$e->getCode(),
82-
$e->getMessage()
83-
));
82+
$this->handleApiException($e);
8483
}
8584
}
8685
}

tests/sii/bhe/ListarEmisoresTest.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,15 @@
2525
use contafi\api_client\client\Bhe;
2626
use PHPUnit\Framework\Attributes\CoversClass;
2727
use PHPUnit\Framework\TestCase;
28+
use contafi\tests\Helpers\FunctionHelpers;
2829

2930
#[CoversClass(Bhe::class)]
3031
/**
3132
* Clase de pruebas para listar emisores de BHEs recibidas.
3233
*/
3334
class ListarEmisoresTest extends TestCase
3435
{
36+
use FunctionHelpers;
3537
/**
3638
* Variable que permite desplegar en consola los resultados.
3739
*
@@ -48,6 +50,7 @@ class ListarEmisoresTest extends TestCase
4850

4951
public static function setUpBeforeClass(): void
5052
{
53+
self::requireEnv('CONTAFI_API_TOKEN');
5154
self::$verbose = env(varname: 'TEST_VERBOSE', default: false);
5255
self::$client = new Bhe();
5356
}
@@ -74,11 +77,7 @@ public function testListarEmisores(): void
7477
"\n";
7578
}
7679
} catch (ApiException $e) {
77-
throw new ApiException(message: sprintf(
78-
'[ApiException %d] %s',
79-
$e->getCode(),
80-
$e->getMessage()
81-
));
80+
$this->handleApiException($e);
8281
}
8382
}
8483
}

tests/sii/bhe/ObservarBheRecibidaTest.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,15 @@
2525
use contafi\api_client\client\Bhe;
2626
use PHPUnit\Framework\Attributes\CoversClass;
2727
use PHPUnit\Framework\TestCase;
28+
use contafi\tests\Helpers\FunctionHelpers;
2829

2930
#[CoversClass(Bhe::class)]
3031
/**
3132
* Clase de pruebas para observar una Boleta de Honorarios Electrónica recibida.
3233
*/
3334
class ObservarBheRecibidaTest extends TestCase
3435
{
36+
use FunctionHelpers;
3537
/**
3638
* Variable que permite desplegar en consola los resultados.
3739
*
@@ -64,6 +66,7 @@ class ObservarBheRecibidaTest extends TestCase
6466

6567
public static function setUpBeforeClass(): void
6668
{
69+
self::requireEnv('CONTAFI_API_TOKEN');
6770
self::$verbose = env(varname: 'TEST_VERBOSE', default: false);
6871
self::$client = new Bhe();
6972
self::$testNumero = env('TEST_NRO_BHE', null);
@@ -102,7 +105,7 @@ public function testObservarBheRecibida(): void
102105
}
103106
$response = self::$client->observar(
104107
self::$testEmisor,
105-
self::$testNumero,
108+
(int)self::$testNumero,
106109
$data
107110
);
108111

@@ -115,11 +118,7 @@ public function testObservarBheRecibida(): void
115118
"\n";
116119
}
117120
} catch (ApiException $e) {
118-
throw new ApiException(message: sprintf(
119-
'[ApiException %d] %s',
120-
$e->getCode(),
121-
$e->getMessage()
122-
));
121+
$this->handleApiException($e);
123122
}
124123
}
125124
}

0 commit comments

Comments
 (0)