Files
oficial/app/Service/Money.php

56 lines
1.6 KiB
PHP
Raw Normal View History

2023-06-22 14:04:40 -04:00
<?php
namespace App\Service;
use DateTimeInterface;
use Psr\Http\Message\ResponseInterface;
use Carbon\Carbon;
use GuzzleHttp\Client;
class Money
{
public function __construct(protected Client $client) {}
public function getUF(string|DateTimeInterface $date): object
{
$date = $this->parseDate($date);
if (!$this->checkNextMonthValueCalculationByDate($date)) {
return $this->emptyResult();
}
$response = $this->client->get('api/uf/value/' . $date->format('Y-m-d'));
if (!$this->isOk($response)) {
return $this->emptyResult();
}
$body = $response->getBody()->getContents();
if (trim($response->getBody()) === '') {
return $this->emptyResult();
}
return json_decode($body);
}
protected function parseDate(string|DateTimeInterface $date): DateTimeInterface
{
if (is_string($date)) {
$date = Carbon::parse($date, config('app.timezone'));
}
return $date;
}
protected function checkNextMonthValueCalculationByDate(DateTimeInterface $date): bool
{
$next_m_9 = Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9);
2023-06-22 23:15:17 -04:00
$date = Carbon::parse($date);
2023-06-22 14:04:40 -04:00
return $date->lessThan($next_m_9);
}
protected function isOk(ResponseInterface $response): bool
{
$statusCode = $response->getStatusCode();
return $statusCode >= 200 and $statusCode < 300;
}
protected function emptyResult(): object
{
return (object) ['total' => 0];
}
}