Files
oficial/app/src/Service/Money/Ine.php
2025-10-24 18:35:52 -03:00

70 lines
2.1 KiB
PHP

<?php
namespace Incoviba\Service\Money;
use Exception;
use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use Psr\Http\Client\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Common\Ideal;
use Incoviba\Service\Money;
class Ine extends Ideal\Money\Provider
{
protected string $uri = 'https://api-calculadora.ine.cl/ServiciosCalculadoraVariacion';
public function __construct(protected ClientInterface $client) {}
/**
* @throws EmptyResponse
* @throws Exception
*/
public function get(string $money_symbol, ?DateTimeInterface $dateTime = null): float
{
if (!$this->supported($money_symbol)) {
throw new EmptyResponse($money_symbol);
}
if ($dateTime === null) {
$dateTime = new DateTimeImmutable();
}
$end = new DateTimeImmutable($dateTime->format('Y-m-1'));
$start = $end->sub(new DateInterval('P1M'));
return $this->getVar($start, $end);
}
protected array $supportedMap = [
Money::IPC => 'ipc'
];
/**
* @throws EmptyResponse
*/
public function getVar(DateTimeInterface $start, DateTimeInterface $end): float
{
$base = 1000000000;
$request_query = [
'mesInicio' => $start->format('m'),
'AnioInicio' => $start->format('Y'),
'mesTermino' => $end->format('m'),
'AnioTermino' => $end->format('Y'),
'valor_a_ajustar' => $base
];
$request_uri = implode('?', [
$this->uri,
http_build_query($request_query),
]);
try {
$response = $this->client->get($request_uri);
} catch (GuzzleException $exception) {
throw new EmptyResponse($request_uri, $exception);
}
$body = $response->getBody();
$json = json_decode($body->getContents());
if (empty($json)) {
throw new EmptyResponse($request_uri);
}
return ((int) str_replace('.', '', $json[0]->valorajustado) - $base) / $base;
}
}