39 lines
1.3 KiB
PHP
39 lines
1.3 KiB
PHP
|
<?php
|
||
|
namespace Incoviba\Service;
|
||
|
|
||
|
use DateTimeInterface;
|
||
|
use DateTimeImmutable;
|
||
|
use DateInterval;
|
||
|
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
||
|
|
||
|
class IPC
|
||
|
{
|
||
|
protected string $redisKey = 'ipc';
|
||
|
public function __construct(protected Redis $redisService, protected Money $moneyService) {}
|
||
|
|
||
|
public function get(DateTimeInterface $from, DateTimeInterface $to = new DateTimeImmutable()): float
|
||
|
{
|
||
|
$now = new DateTimeImmutable();
|
||
|
if ($to > $now) {
|
||
|
return 0;
|
||
|
}
|
||
|
$dateKey = "{$from->format('Y-m')}-{$to->format('Y-m')}";
|
||
|
$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);
|
||
|
$ipcs[$dateKey] = $ipc;
|
||
|
$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
|
||
|
{
|
||
|
return $base * (1 + $this->get($from, $to->sub(new DateInterval('P1M'))));
|
||
|
}
|
||
|
}
|