From af78106700036bc5ffdb2789f4c12dab4ae7a8f9 Mon Sep 17 00:00:00 2001 From: Aldarien Date: Wed, 5 Jan 2022 16:01:27 -0300 Subject: [PATCH] Cleaner code --- api/common/Service/TiposCambios.php | 44 +++++++++++++++++------------ 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/api/common/Service/TiposCambios.php b/api/common/Service/TiposCambios.php index be9f88d..7319c30 100644 --- a/api/common/Service/TiposCambios.php +++ b/api/common/Service/TiposCambios.php @@ -20,27 +20,19 @@ class TiposCambios { $this->base_url = $api_url; $this->key = $api_key; } - 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') { - if ($fecha->weekday() == 0) { - $fecha = $fecha->subWeek()->weekday(5); - } - if ($fecha->weekday() == 6) { - $fecha = $fecha->weekday(5); - } + protected function getWeekday(\DateTimeInterface $fecha) { + if ($fecha->weekday() == 0) { + return $fecha->subWeek()->weekday(5); } - $cambio = $moneda->cambio($fecha); - if ($cambio) { - if ($cambio->desde()->id != $moneda->id) { - return 1 / $cambio->valor; - } - return $cambio->valor; + if ($fecha->weekday() == 6) { + return $fecha->weekday(5); } + return $fecha; + } + protected function getValor(\DateTimeInterface $fecha, string $moneda_codigo) { $data = [ 'fecha' => $fecha->format('Y-m-d'), - 'desde' => $moneda->codigo + 'desde' => $moneda_codigo ]; $headers = [ 'Authorization' => 'Bearer ' . $this->key @@ -60,7 +52,23 @@ class TiposCambios { return null; } $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 = [ 'fecha' => $fecha->format('Y-m-d H:i:s'), 'desde_id' => $moneda->id,