Новая реализация курсов валют.

This commit is contained in:
2023-08-10 17:04:23 +03:00
parent f4a66a1147
commit deac9203bd
7 changed files with 421 additions and 509 deletions
+9 -5
View File
@@ -4,19 +4,18 @@ namespace Core;
class Config
{
const EKR_RUB_PRICE = 30;
const KR_TO_EKR_EXCHANGE = 500;
const EKR_TO_KR_EXCHANGE = 200;
private static self $instance;
private static string $hostname = 'new-combats.tech';
private static string $gamename = 'Бойцовский Клуб';
private function __construct()
{
//singleton
}
private static function subdomain(string $name): string
{
return DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . $name . '.' . self::$hostname;
}
/** Самый распространённый субдомен
* //img.{siteName}.
* @return string
@@ -26,6 +25,11 @@ class Config
return self::subdomain('img');
}
private static function subdomain(string $name): string
{
return DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . $name . '.' . self::$hostname;
}
public static function get(?string $key = null)
{
$c['ver'] = '1.8.3.7';
@@ -0,0 +1,37 @@
<?php
namespace Model;
use Core\Db;
class EkrExchangeRates
{
/**
* @var array|false
*/
private $today;
public function __construct()
{
$this->today = Db::getRow('select RUB, USD, from_unixtime(id, ?) as date from ekr_exchange_rates order by id desc limit 1', ['%d.%m.%Y']);
if (empty($this->today)) {
$this->today = ['RUB' => 0, 'USD' => 0, 'date' => '00.00.0000'];
}
}
public function oneEkrInUSD(): float
{
return round($this->today['RUB'] / $this->today['USD'], 2);
}
public function oneEkrInRUB(): float
{
return $this->today['RUB'];
}
public function date(): string
{
return $this->today['date'];
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
use Core\{Config, Db};
/**
* Парсинг данных ЦБ РФ.
* https://www.cbr-xml-daily.ru/#howto
* Раз в день в час ночи.
*/
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoload.php';
$todayExchangeRate = new class {
private const API = 'https://www.cbr-xml-daily.ru/daily_json.js';
public static function getUSDEkrPrice(): float
{
$rates = json_decode(file_get_contents(self::API));
return round(Config::EKR_RUB_PRICE / $rates->Valute->USD->Value, 2);
}
};
$sql = 'insert into ekr_exchange_rates (RUB, USD) values (?,?)';
$args = [
round(Config::EKR_RUB_PRICE, 2),
$todayExchangeRate::getUSDEkrPrice(),
];
Db::sql($sql, $args);
@@ -1,101 +0,0 @@
<?php
use Core\Config;
use Core\Db;
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoload.php';
/**
* Обновление данных о курсах валют из Центробанка РФ.
* Раз в день в час ночи.
*/
// Обнуление(?!) передач раз в сутки
Db::sql('update stats set transfers = 100 where transfers < 200');
function getCurs()
{
// создаем объект для работы с XML
$xml = new DOMDocument();
// ссылка на сайт банка
$url = 'https://www.cbr.ru/scripts/XML_daily.asp?date_req=' . date('d.m.Y');
// получаем xml с курсами всех валют
if (!$xml->load($url)) {
// если не получили xml возвращаем false
return false;
}
// массив для хранения курсов валют
$result = [];
// разбираем xml
$root = $xml->documentElement;
// берем все теги 'Valute' и их содержимое
$items = $root->getElementsByTagName('Valute');
// переберем теги 'Valute' по одному
foreach ($items as $item) {
// получаем код валюты
$code = $item->getElementsByTagName('CharCode')->item(0)->nodeValue;
// получаем значение курса валюты, относительно рубля
$value = $item->getElementsByTagName('Value')->item(0)->nodeValue;
// номинал
$nominal = $item->getElementsByTagName('Nominal')->item(0)->nodeValue;
// записываем в массив, предварительно заменив запятую на точку
$result[$code] = round(str_replace(',', '.', $value), 5) / $nominal;
}// возвращаем значение курса, для запрошенной валюты
return $result;
}
$get = getCurs();
if (Config::get('curency_name') === 'RUB') {
$curency = Config::get('curency_value');
} else {
$curency = round($get[Config::get('curency_name')] * Config::get('curency_value'), 4);
}
if ($get['USD'] > 0) {
$price = [
'AUD',
'AZN',
'AMD',
'BYR',
'BGN',
'BRL',
'HUF',
'KRW',
'DKK',
'USD',
'EUR',
'INR',
'KZT',
'CAD',
'KGS',
'CNY',
'LVL',
'LTL',
'MDL',
'RON',
'TMT',
'NOK',
'PLN',
'XDR',
'SGD',
'TJS',
'TRY',
'UZS',
'UAH',
'GBP',
'CZK',
'SEK',
'CHF',
'ZAR',
'JPY',
];
$r = '';
foreach ($price as $value) {
if (!$get[$value]) {
continue;
}
$r .= ',`' . $value . '`="' . $get[$value] . '"';
}
Db::sql('insert into bank_table set time = unix_timestamp(), cur = ?, data = ?', [$curency, date('d.m.Y') . $r]);
}