Files
oficial/app/src/Service/IPC.php

47 lines
1.5 KiB
PHP
Raw Normal View History

2023-11-29 20:09:08 -03:00
<?php
namespace Incoviba\Service;
use DateTimeInterface;
use DateTimeImmutable;
use DateInterval;
use Incoviba\Common\Implement\Exception\EmptyRedis;
2024-01-18 13:15:26 -03:00
use Psr\Log\LoggerInterface;
2023-11-29 20:09:08 -03:00
class IPC
{
protected string $redisKey = 'ipc';
2024-01-18 13:15:26 -03:00
public function __construct(protected Redis $redisService, protected Money $moneyService, protected LoggerInterface $logger) {}
2023-11-29 20:09:08 -03:00
public function get(DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()): float
{
$now = new DateTimeImmutable();
if ($to > $now) {
return 0;
}
2023-11-30 00:06:21 -03:00
$dateKey = "{$from->format('Y-m')}|{$to->format('Y-m')}";
2023-11-29 20:09:08 -03:00
$ipcs = [];
try {
$ipcs = json_decode($this->redisService->get($this->redisKey), JSON_OBJECT_AS_ARRAY);
if (!isset($ipcs[$dateKey])) {
throw new EmptyRedis($this->redisKey);
}
} catch (EmptyRedis) {
$ipc = $this->moneyService->getIPC($from, $to);
2023-12-04 19:51:44 -03:00
if ($ipc === -1.0) {
return 0;
}
2023-11-29 20:09:08 -03:00
$ipcs[$dateKey] = $ipc;
2023-11-30 00:24:08 -03:00
ksort($ipcs);
2023-11-29 20:09:08 -03:00
$this->redisService->set($this->redisKey, json_encode($ipcs), 60 * 60 * 24 * 30);
}
return $ipcs[$dateKey];
}
public function readjust(float $base, DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()):float
{
2023-12-04 19:51:44 -03:00
if (($ipc = $this->get($from, $to->sub(new DateInterval('P1M')))) === 0.0) {
2024-01-18 13:15:26 -03:00
return $base;
2023-12-04 19:51:44 -03:00
}
return $base * (1 + $ipc);
2023-11-29 20:09:08 -03:00
}
}