Зимние правки. MVC/

Signed-off-by: lopar <lopar.4ever@gmail.com>
This commit is contained in:
lopar
2022-08-09 22:57:43 +03:00
parent 0f62ee20e7
commit b9b4c01cf0
104 changed files with 2254 additions and 2086 deletions
+94 -120
View File
@@ -7,21 +7,22 @@
namespace Battles;
use Exceptions\GameException;
use Battles\Database\Db;
use Throwable;
class Bank
{
public int $user_id = 0;
private int $user_id = 0;
private int $money = 0;
private $user;
private string $error = '';
private string $status = '';
private int $comission = 0;
const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
const ERROR_NO_MONEY_IN_BANK_ACCOUNT = "Ошибка! Нет денег на счету!";
const ERROR_WRONG_AMOUNT = "Ошибка! Сумма должна быть положительной!";
const LOG = [
private const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
private const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
private const ERROR_NO_MONEY_IN_BANK_ACCOUNT = "Ошибка! Нет денег на счету!";
private const ERROR_WRONG_AMOUNT = "Ошибка! Сумма должна быть положительной!";
private const ERROR_WRONG_ID = 'Неверный ID!';
private const LOG = [
'sendMoney' => 'Банк: Перевод средств на другой счёт.',
'receiveMoney' => 'Банк: Получение средств.',
'depositMoney' => 'Пополнение счёта.',
@@ -30,10 +31,12 @@ class Bank
'sellShop' => 'Продажа товара в магазине.'
];
public function __construct(int $user_id)
public function __construct(int $user_id = null)
{
if (empty($user_id)) {
$user_id = User::getInstance()->getId();
}
$bank_row = Db::getInstance()->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id);
$this->user = Db::getInstance()->fetch('SELECT money FROM users WHERE id = ?', $user_id);
foreach ($this as $key => $value) {
if (isset($bank_row[$key])) {
$this->$key = $bank_row[$key];
@@ -48,75 +51,69 @@ class Bank
*
* @return int
*/
private function bankCommission(int $amount): int
private function commission(int $amount): int
{
$bankCommission = round($amount * GameConfigs::BANK_COMISSION);
if ($bankCommission < 1) {
return 1;
} else {
return (int)$bankCommission;
}
$this->comission = max(1, (int)$bankCommission);
return $this->comission;
}
/**
* Пишем банковское событие в лог в БД
*
* @param int $receiverId ID получателя.
* @param int $amount сумма.
* @param int $receiverId ID получателя.
* @param int $amount сумма.
* @param string $operationType тип банковской операции.
* @param int $senderId ID отправителя (ID игрока, если не указано иное).
* @param ?int $senderId ID отправителя (ID игрока, если не указано иное).
*
* @return void
*/
private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = null): void
private function addLog(int $receiverId, int $amount, string $operationType, ?int $senderId = null): void
{
if (is_null($senderId)) {
$senderId = $this->user_id;
}
$text = self::LOG[$operationType];
if ($operationType == "sendMoney") {
$text .= " Комиссия: " . $this->bankCommission($amount);
} elseif ($operationType == "depositMoney") {
if ($operationType === 'depositMoney' || $operationType === 'withdrawMoney') {
$receiverId = $this->user_id;
} elseif ($operationType == "withdrawMoney") {
$receiverId = $this->user_id;
$text .= " Комиссия: " . $this->bankCommission($amount);
}
GameLogs::addBankLog($senderId,$receiverId,$amount,$operationType,$text);
$commText = $this->comission ? ' Комиссия: ' . $this->comission : '';
$text = self::LOG[$operationType] . $commText;
$this->status = $text;
GameLogs::addBankLog($senderId, $receiverId, $amount, $operationType, $text);
}
/**
* Перевод денег между банковскими счетами игроков с банковской комиссией.
*
* @param int $receiver ID получателя.
* @param int $amount сумма.
*
* @return int
* @throws GameException
* @param mixed $receiver ID получателя.
* @param mixed $amount Cумма.
*/
public function sendMoney(int $receiver, int $amount): int
public function sendMoney($receiver, $amount)
{
$receiverWallet = Db::getInstance()->ofetch('SELECT money FROM bank WHERE user_id = ?', $receiver);
if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT);
if (!is_numeric($receiver)) {
$this->error = self::ERROR_WRONG_ID;
return;
}
if (!$receiverWallet) {
throw new GameException(self::ERROR_NO_BANK_ACCOUNT);
$rec = new self($receiver);
if (!is_numeric($amount) || $amount <= 0) {
$this->error = self::ERROR_WRONG_AMOUNT;
}
$amountWithComission = $amount + $this->bankCommission($amount);
if (!$rec->user_id) {
$this->error = self::ERROR_NO_BANK_ACCOUNT;
}
$amountWithComission = $amount + $this->commission($amount);
if ($amountWithComission > $this->money) {
throw new GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT);
$this->error = self::ERROR_NO_MONEY_IN_BANK_ACCOUNT;
}
if ($this->error) {
return;
}
// Снимаем сумму с комиссией у отправителя
$this->money -= $amountWithComission;
self::setBankMoney($this->money, $this->user_id);
$this->bankLogs($receiver, $this->money, "sendMoney");
$this->modify(-$amountWithComission);
$this->addLog($rec->user_id, $this->money, 'sendMoney', $this->user_id);
// Отдаём сумму на счёт получателю
$receiverWallet->money += $amount;
self::setBankMoney($receiverWallet->money, $receiver);
$this->bankLogs($receiver, $receiverWallet->money, "receiveMoney");
// Возвращаем изменившиеся значения
return $this->money;
$rec->modify($amount);
$rec->addLog($rec->user_id, $rec->money, 'receiveMoney', $this->user_id);
}
/**
@@ -124,30 +121,22 @@ class Bank
*
* @param int $amount сумма.
*
* @return array
* @throws GameException
*/
public function depositMoney(int $amount): array
public function depositMoney(int $amount)
{
if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT);
}
$walletMoney = Db::getInstance()->fetchColumn('SELECT money FROM users WHERE id = ?', $this->user_id);
if ($walletMoney < $amount) {
throw new GameException(self::ERROR_NO_MONEY_IN_WALLET);
$this->error = self::ERROR_WRONG_AMOUNT;
}
// Забираем деньги из кошелька получателя
$this->user->money -= $amount;
self::setWalletMoney($this->user->money, $this->user_id);
if (!User::getInstance($this->user_id)->money()->spend($amount)) {
$this->error = self::ERROR_NO_MONEY_IN_WALLET;
}
if ($this->error) {
return;
}
// Отдаём сумму на счёт получателю
$this->money += $amount;
self::setBankMoney($this->money, $this->user_id);
$this->bankLogs(0, $this->money, "depositMoney");
// Возвращаем изменившиеся значения
return [
'walletMoney' => $this->user->money,
'bankMoney' => $this->money
];
$this->modify($amount);
$this->addLog(0, $this->money, 'depositMoney');
}
/**
@@ -155,66 +144,29 @@ class Bank
*
* @param int $amount сумма.
*
* @return array
* @throws GameException
*/
public function withdrawMoney(int $amount): array
public function withdrawMoney(int $amount)
{
if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT);
$this->error = self::ERROR_WRONG_AMOUNT;
}
$amountWithComission = $amount + $this->bankCommission($amount);
$amountWithComission = $amount + $this->commission($amount);
if ($this->money < $amountWithComission) {
throw new GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT);
$this->error = self::ERROR_NO_MONEY_IN_BANK_ACCOUNT;
}
if ($this->error) {
return;
}
// Снимаем сумму с комиссией у отправителя
$this->money -= $amountWithComission;
self::setBankMoney($this->money, $this->user_id);
$this->bankLogs(0, $this->money, "withdrawMoney");
$this->modify(-$amountWithComission);
$this->addLog(0, $this->money, 'withdrawMoney');
// Отдаём сумму в кошелёк получателя
$this->user['money'] += $amount;
self::setWalletMoney($this->user['money'], $this->user_id);
// Возвращаем изменившиеся значения
return [
'walletMoney' => $this->user['money'],
'bankMoney' => $this->money
];
User::getInstance($this->user_id)->money()->earn($amount);
}
/**
* Установить количество денег на банковском счету.
*
* @param int $amount сумма.
* @param int $user_id ID пользователя.
* @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог.
*
* @return void
*/
public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void
private function save()
{
try {
Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]);
if ($operationType) {
GameLogs::addBankLog(0, 0, $amount, $operationType, self::LOG[$operationType]);
}
} catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
}
}
/**
* Установить количество денег на руках.
*
* @param int $amount сумма.
* @param int $user_id ID пользователя.
*
* @return void
*/
public static function setWalletMoney(int $amount, int $user_id): void
{
User::getInstance($user_id)->setMoney($amount);
User::getInstance($user_id)->saveMoney();
Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$this->money, $this->user_id]);
}
public function getMoney(): int
@@ -222,8 +174,30 @@ class Bank
return $this->money;
}
public function setMoney($amount)
public function modify(int $amount, string $logType = '')
{
$this->money = $amount;
if ($amount > 0) {
// add_money
$this->money += $amount;
$this->save();
} elseif ($amount < 0) {
// remove_money
if ($this->money < $amount) {
return;
}
$this->money -= $amount;
$this->save();
}
if ($logType && $amount !== 0) {
$this->addLog(0, $this->money, $logType);
}
}
}
public function getStatus(): string
{
if (!$this->error) {
return $this->status;
}
return $this->error;
}
}