Cleaner code

This commit is contained in:
2022-01-05 16:01:27 -03:00
parent 665f426011
commit af78106700

View File

@ -20,27 +20,19 @@ class TiposCambios {
$this->base_url = $api_url; $this->base_url = $api_url;
$this->key = $api_key; $this->key = $api_key;
} }
public function get(string $fecha, int $moneda_id) { protected function getWeekday(\DateTimeInterface $fecha) {
$fecha = Carbon::parse($fecha);
$moneda = $this->factory->find(Moneda::class)->one($moneda_id);
if ($moneda->codigo == 'USD') {
if ($fecha->weekday() == 0) { if ($fecha->weekday() == 0) {
$fecha = $fecha->subWeek()->weekday(5); return $fecha->subWeek()->weekday(5);
} }
if ($fecha->weekday() == 6) { if ($fecha->weekday() == 6) {
$fecha = $fecha->weekday(5); return $fecha->weekday(5);
} }
return $fecha;
} }
$cambio = $moneda->cambio($fecha); protected function getValor(\DateTimeInterface $fecha, string $moneda_codigo) {
if ($cambio) {
if ($cambio->desde()->id != $moneda->id) {
return 1 / $cambio->valor;
}
return $cambio->valor;
}
$data = [ $data = [
'fecha' => $fecha->format('Y-m-d'), 'fecha' => $fecha->format('Y-m-d'),
'desde' => $moneda->codigo 'desde' => $moneda_codigo
]; ];
$headers = [ $headers = [
'Authorization' => 'Bearer ' . $this->key 'Authorization' => 'Bearer ' . $this->key
@ -60,7 +52,23 @@ class TiposCambios {
return null; return null;
} }
$result = json_decode($response->getBody()); $result = json_decode($response->getBody());
$valor = $result->serie[0]->valor; return $result->serie[0]->valor;
}
public function get(string $fecha, int $moneda_id) {
$fecha = Carbon::parse($fecha);
$moneda = $this->factory->find(Moneda::class)->one($moneda_id);
if ($moneda->codigo == 'USD') {
$fecha = $this->getWeekday($fecha);
}
// If a value exists in the database
$cambio = $moneda->cambio($fecha);
if ($cambio) {
if ($cambio->desde()->id != $moneda->id) {
return 1 / $cambio->valor;
}
return $cambio->valor;
}
$valor = $this->getValor($fecha, $moneda->codigo);
$data = [ $data = [
'fecha' => $fecha->format('Y-m-d H:i:s'), 'fecha' => $fecha->format('Y-m-d H:i:s'),
'desde_id' => $moneda->id, 'desde_id' => $moneda->id,