<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Doctrine\DBAL\Connection;
use Twig\Environment;
class UserSubscriber
{
private $connection;
private $twig;
public function __construct(Connection $connection, Environment $twig)
{
$this->connection = $connection;
$this->twig = $twig;
}
public function onKernelController(ControllerEvent $event): void
{
$request = $event->getRequest();
$session = $request->getSession();
$user = null;
if ($session->has('hash')) {
$hash = $session->get('hash');
$user = $this->connection->fetchAssociative('SELECT * FROM users WHERE hash = ?', [$hash]);
$sumDeposits = $this->connection->fetchOne(
'SELECT COALESCE(SUM(suma), 0) FROM deposits WHERE user_id = ? AND status = 1',
[$user['id']]
);
$xp = (int)$sumDeposits;
$levels = [
['xp' => 1000, 'bonus' => 100],
['xp' => 5000, 'bonus' => 250],
['xp' => 10000, 'bonus' => 500],
['xp' => 25000, 'bonus' => 1000],
['xp' => 100000, 'bonus' => 1500],
];
$oldRank = $user['rank'];
$newRank = 0;
$totalBonus = 0;
foreach ($levels as $i => $level) {
if ($xp >= $level['xp']) {
$newRank = $i + 1;
if ($i + 1 > $oldRank) {
$totalBonus += $level['bonus'];
}
} else {
break;
}
}
if ($newRank > $oldRank) {
$this->connection->executeStatement(
'UPDATE users SET balance = balance + :balance, wager = wager + :wager, `rank` = :rank WHERE id = :id',
[
'balance' => $totalBonus,
'wager' => $totalBonus * 5,
'rank' => $newRank,
'id' => $user['id']
]
);
$this->connection->insert('events', [
'user_id' => $user['id'],
'event' => '[Rank] Получение бонуса +' . $totalBonus . '',
'time' => (new \DateTime())->format('Y-m-d H:i:s')
]);
$user['balance'] += $totalBonus;
$user['wager'] += $totalBonus * 5;
$user['rank'] = $newRank;
}
}
$this->twig->addGlobal('user', $user);
}
}