client = $client; $this->factory = $factory; $this->base_url = $api_url; $this->key = $api_key; } protected function getWeekday(\DateTimeInterface $fecha) { if ($fecha->weekday() == 0) { return $fecha->subWeek()->weekday(5); } 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 ]; $headers = [ 'Authorization' => "Bearer {$this->key}" ]; $url = implode('/', [ $this->base_url, 'cambio', 'get' ]); try { $response = $this->client->request('POST', $url, ['json' => $data, 'headers' => $headers]); } catch (ConnectException | RequestException | ServerException $e) { error_log($e); return null; } if ($response->getStatusCode() !== 200) { error_log('Could not connect to python API.'); return null; } $result = json_decode($response->getBody()); if (isset($result->message) and $result->message === 'Not Authorized') { error_log('Not authorized for connecting to python API.'); return null; } 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 !== null) { if ($cambio->desde()->id != $moneda->id) { return 1 / $cambio->valor; } return $cambio->valor; } $valor = $this->getValor($fecha, $moneda->codigo); if ($valor === null) { return 1; } $data = [ 'fecha' => $fecha->format('Y-m-d H:i:s'), 'desde_id' => $moneda->id, 'hasta_id' => 1, 'valor' => $valor ]; $tipo = TipoCambio::add($this->factory, $data); if ($tipo !== false and $tipo->is_new()) { $tipo->save(); } return $valor; } }