Changeset View
Changeset View
Standalone View
Standalone View
src/app/Backends/OpenExchangeRates.php
- This file was added.
<?php | |||||
namespace App\Backends; | |||||
class OpenExchangeRates | |||||
{ | |||||
machniak: I was going to say that it would probably be better to move it to app\Providers, but thinking… | |||||
Done Inline ActionsMoving payment providers to backends could make sense indeed. mollekopf: Moving payment providers to backends could make sense indeed. | |||||
/** | |||||
* Import exchange rates from openexchangerates.org | |||||
* | |||||
* @param string Base currency | |||||
Done Inline ActionsMissing argument doc. machniak: Missing argument doc. | |||||
* | |||||
* @return array exchange rates | |||||
*/ | |||||
public static function retrieveRates($baseCurrency) | |||||
{ | |||||
Done Inline ActionsShort array syntax, please (here and below). Shouldn't it be 'base' => $base_currency? machniak: Short array syntax, please (here and below). Shouldn't it be `'base' => $base_currency`? | |||||
Done Inline ActionsThe base currency for the request is fixed to USD for the free plan. That's why we calculate the conversion rate manually below. mollekopf: The base currency for the request is fixed to USD for the free plan. That's why we calculate… | |||||
$baseCurrency = strtoupper($baseCurrency); | |||||
$apiKey = \config('services.openexchangerates.api_key'); | |||||
$query = http_build_query(['app_id' => $apiKey, 'base' => 'USD']); | |||||
$url = 'https://openexchangerates.org/api/latest.json?' . $query; | |||||
$html = file_get_contents($url, false); | |||||
$rates = []; | |||||
if ($html && ($result = json_decode($html, true)) && !empty($result['rates'])) { | |||||
foreach ($result['rates'] as $code => $rate) { | |||||
$rates[strtoupper($code)] = $rate; | |||||
} | |||||
if ($baseCurrency != 'USD') { | |||||
if ($base = $rates[$baseCurrency]) { | |||||
foreach ($rates as $code => $rate) { | |||||
$rates[$code] = $rate / $base; | |||||
} | |||||
} else { | |||||
$rates = []; | |||||
} | |||||
} | |||||
foreach ($rates as $code => $rate) { | |||||
\Log::debug(sprintf("Update %s: %0.8f", $code, $rate)); | |||||
} | |||||
} else { | |||||
throw new \Exception("Failed to parse exchange rates"); | |||||
} | |||||
if (count($rates) > 1) { | |||||
$rates[$baseCurrency] = 1; | |||||
return $rates; | |||||
} | |||||
Done Inline ActionsI don't remember if we ever do both Log::error() and throw. Looks redundant. machniak: I don't remember if we ever do both Log::error() and throw. Looks redundant. | |||||
throw new \Exception("Failed to retrieve exchange rates"); | |||||
} | |||||
} |
I was going to say that it would probably be better to move it to app\Providers, but thinking more, I'm not sure. Maybe it's ok and we should rather move payment providers code here, and leave app\Providers for the Laravel framework stuff only.