94 lines
2.8 KiB
PHP
94 lines
2.8 KiB
PHP
<?php
|
|
namespace Incoviba\Service;
|
|
|
|
use DateTimeInterface;
|
|
use Psr\Log\LoggerInterface;
|
|
use Incoviba\Common\Define\Money\Provider;
|
|
use Incoviba\Common\Implement\Exception\EmptyResponse;
|
|
|
|
class Money
|
|
{
|
|
const string UF = 'uf';
|
|
const string USD = 'usd';
|
|
const string IPC = 'ipc';
|
|
|
|
public function __construct(protected LoggerInterface $logger) {}
|
|
|
|
protected array $providers = [];
|
|
public function register(Provider $provider): Money
|
|
{
|
|
if (in_array($provider, $this->providers)) {
|
|
return $this;
|
|
}
|
|
$this->providers []= $provider;
|
|
return $this;
|
|
}
|
|
public function getProviders(string $name): array
|
|
{
|
|
return array_values(array_filter($this->providers, fn($provider) => $provider->supported($name)));
|
|
}
|
|
|
|
public function get(string $name, DateTimeInterface $dateTime): float
|
|
{
|
|
$providers = $this->getProviders($name);
|
|
foreach ($providers as $provider) {
|
|
try {
|
|
return $provider->get(self::getSymbol($provider), $dateTime);
|
|
} catch (EmptyResponse $exception) {
|
|
$this->logger->notice($exception);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
public function getUF(?DateTimeInterface $dateTime = null): float
|
|
{
|
|
$providers = $this->getProviders(self::UF);
|
|
foreach ($providers as $provider) {
|
|
try {
|
|
return $provider->get(self::UF, $dateTime);
|
|
} catch (EmptyResponse $exception) {
|
|
$this->logger->notice($exception);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
public function getIPC(DateTimeInterface $start, DateTimeInterface $end): float
|
|
{
|
|
if ($start >= $end) {
|
|
return 0;
|
|
}
|
|
$providers = $this->getProviders(self::IPC);
|
|
foreach ($providers as $provider) {
|
|
try {
|
|
if (method_exists($provider, 'getVar')) {
|
|
return $provider->getVar($start, $end);
|
|
}
|
|
return $provider->get(self::IPC, $end);
|
|
} catch (EmptyResponse $exception) {
|
|
$this->logger->notice($exception);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
public function getUSD(DateTimeInterface $dateTime): float
|
|
{
|
|
$providers = $this->getProviders(self::USD);
|
|
foreach ($providers as $provider) {
|
|
try {
|
|
return $provider->get(self::USD, $dateTime);
|
|
} catch (EmptyResponse $exception) {
|
|
$this->logger->notice($exception);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
public static function getSymbol(string $identifier): string
|
|
{
|
|
$upper = strtoupper($identifier);
|
|
$output = '';
|
|
eval("\$output = self::{$upper};");
|
|
return $output;
|
|
}
|
|
}
|