Skip to content

Instantly share code, notes, and snippets.

@waska14
Last active August 2, 2021 18:13
Show Gist options
  • Save waska14/4651da00e8b5433bdb7bfac3aa3ab259 to your computer and use it in GitHub Desktop.
Save waska14/4651da00e8b5433bdb7bfac3aa3ab259 to your computer and use it in GitHub Desktop.
Laravel: Sync NBG (National Bank of Georgia) currency [console command] | After nbg failure :) 2021.08.02
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use SoapClient;
use SoapFault;
use Throwable;
class SyncNBGCurrency extends Command
{
protected const NBG_WSDL_URL = 'http://old.nbg.gov.ge/currency.wsdl';
protected const NBG_JSON_URL = 'https://nbg.gov.ge/gw/api/ct/monetarypolicy/currencies/ka/json';
/**
* @inheritdoc
*/
protected $signature = 'sync:nbg-currencies';
/**
* @inheritdoc
*/
protected $description = 'This syncs nbg currency rates';
protected $currenciesToSync = [
'USD',
'EUR',
];
public function handle()
{
try {
$this->handleOld();
} catch (Throwable $e) {
$this->handleNew();
}
}
/**
* @throws SoapFault
* @noinspection PhpUndefinedMethodInspection
*/
protected function handleOld()
{
$xml = file_get_contents(self::NBG_WSDL_URL);
$xml = str_replace('//nbg.gov.ge', '//old.nbg.gov.ge', $xml);
$tempWSDL = tmpfile();
fwrite($tempWSDL, $xml);
$WSDLUrl = stream_get_meta_data($tempWSDL)['uri'];
foreach ($this->currenciesToSync as $currency) {
$this->syncRateOld($currency, $WSDLUrl);
}
}
protected function handleNew()
{
$json = file_get_contents(self::NBG_JSON_URL);
$data = json_decode($json, true);
$data = Arr::get(Arr::first($data), 'currencies', []);
foreach ($this->currenciesToSync as $currency) {
$this->syncRateNew($currency, $data);
}
}
/**
* @param string $currency
* @param string $wsdlUrl
* @throws SoapFault
* @noinspection PhpUndefinedMethodInspection
*/
protected function syncRateOld(string $currency, string $wsdlUrl)
{
$rate = (new SoapClient($wsdlUrl))->getCurrency($currency);
// TODO stuff here
dump($currency, $rate);
}
/**
* @param string $currency
* @param array $data
*/
protected function syncRateNew(string $currency, array $data)
{
$nbgCurrency = Arr::first($data, function ($item) use ($currency) {
return Str::upper(Arr::get($item, 'code')) === Str::upper($currency);
});
if ($nbgCurrency) {
$rate = floatval(Arr::get($nbgCurrency, 'rate', 0));
if ($rate) {
// TODO stuff here
dump($currency, $rate);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment