Обработка ошибок. Меньше sql-запросов в логике.
This commit is contained in:
parent
5b78d00f19
commit
3ca33f38aa
28
bank.php
28
bank.php
@ -4,22 +4,25 @@ session_start();
|
||||
|
||||
if (is_null($_SESSION['uid'])) {
|
||||
header("Location: index.php");
|
||||
exit;
|
||||
}
|
||||
require_once "functions.php";
|
||||
if ($user['room'] != 29) {
|
||||
$user = $user ?? [];
|
||||
if ($user->room != 29) {
|
||||
header("Location: main.php");
|
||||
die();
|
||||
exit;
|
||||
}
|
||||
if ($user['battle'] != 0) {
|
||||
if ($user->battle != 0) {
|
||||
header('location: fbattle.php');
|
||||
die();
|
||||
exit;
|
||||
}
|
||||
const BANK_SESSION_NAME = "bankid";
|
||||
const SUCCESS = "Успешная операция!";
|
||||
$get = urldecode(filter_input(INPUT_SERVER, 'QUERY_STRING'));
|
||||
if ($get == 'exit') {
|
||||
$_SESSION[BANK_SESSION_NAME] = null;
|
||||
}
|
||||
$bank = new Bank($_SESSION['uid']);
|
||||
$bank = new Bank($user->id);
|
||||
|
||||
if (isset($_POST['userlogin'])) {
|
||||
$_SESSION[BANK_SESSION_NAME] = $bank->user_id;
|
||||
@ -28,24 +31,23 @@ if ($_SESSION[BANK_SESSION_NAME]) {
|
||||
$toid = (int)$_POST['to_id'] ?? 0;
|
||||
$summa = (int)$_POST['summa'] ?? 0;
|
||||
$submit = $_POST['action'] ?? '';
|
||||
|
||||
// Зачисдение кредитов на счёт.
|
||||
$status = '';
|
||||
// Зачисление кредитов на счёт.
|
||||
if ($submit === 'depositMoney' && $summa) {
|
||||
$bank->depositMoney($summa);
|
||||
unset($submit, $summa);
|
||||
$status = SUCCESS;
|
||||
}
|
||||
|
||||
// Снятие кредитов со счёта.
|
||||
if ($submit === 'withdrawMoney' && $summa) {
|
||||
$bank->withdrawMoney($summa);
|
||||
unset($submit, $summa);
|
||||
$status = SUCCESS;
|
||||
}
|
||||
|
||||
// Перевод кредитов на другой счёт.
|
||||
if ($submit === 'sendMoney' && $summa && $toid) {
|
||||
$bank->sendMoney($toid, $summa);
|
||||
unset($submit, $summa, $toid);
|
||||
$status = SUCCESS;
|
||||
}
|
||||
unset($submit, $summa, $toid);
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
@ -64,7 +66,7 @@ if ($_SESSION[BANK_SESSION_NAME]) {
|
||||
<form method="post"><input type="submit" name="userlogin" value="Управление счётом"></form>
|
||||
<?php else: ?>
|
||||
<p><a href="?exit"> ← выйти из счёта</a></p>
|
||||
<div><?= $bank->status ?></div>
|
||||
<div><?= $status ?></div>
|
||||
<div class="appblock appblock-main">
|
||||
<span class="legend">Cчет №<?= $bank->user_id ?></span>
|
||||
<span class="wrap">На счету: <span class="num"><?= $bank->money ?></span></span>
|
||||
|
118
classes/Bank.php
118
classes/Bank.php
@ -8,11 +8,11 @@
|
||||
class Bank
|
||||
{
|
||||
public $user_id;
|
||||
public $money = 0;
|
||||
public $status = '';
|
||||
public $money;
|
||||
private $user;
|
||||
|
||||
public const BANK_COMISSION = 0.05; //5%
|
||||
const SUCCESS = "Успешная операция!";
|
||||
|
||||
const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
|
||||
const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
|
||||
const ERROR_NO_MONEY_IN_BANK_ACCOUNT = "Ошибка! Нет денег на счету!";
|
||||
@ -25,6 +25,7 @@ class Bank
|
||||
public function __construct($row)
|
||||
{
|
||||
$bank_row = db::c()->query('SELECT user_id, money FROM bank WHERE user_id = ?i', $row)->fetch_assoc();
|
||||
$this->user = db::c()->query('SELECT money FROM users WHERE id = ?i', $row)->fetch_object();
|
||||
foreach ($this as $key => $value) {
|
||||
if (isset($bank_row[$key])) {
|
||||
$this->$key = $bank_row[$key];
|
||||
@ -39,7 +40,9 @@ class Bank
|
||||
|
||||
/**
|
||||
* Комиссия: self::BANK_COMISSION от переводимой суммы, но не менее 1 кр.
|
||||
*
|
||||
* @param $amount
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private function bankComission($amount)
|
||||
@ -54,9 +57,11 @@ class Bank
|
||||
|
||||
/**
|
||||
* Пишем банковское событие в лог в БД
|
||||
*
|
||||
* @param $receiverId - user_id получателя
|
||||
* @param $amount
|
||||
* @param $operationType
|
||||
*
|
||||
* @throws \Krugozor\Database\Mysql\Exception
|
||||
*/
|
||||
private function bankLogs($receiverId, $amount, $operationType)
|
||||
@ -79,84 +84,93 @@ class Bank
|
||||
|
||||
/**
|
||||
* Перевод денег между бансковскими счетами игроков с банковской комиссией.
|
||||
* @param $receiver - получатель
|
||||
* @param $amount - сумма
|
||||
* @return string
|
||||
*
|
||||
* @param int $receiver
|
||||
* @param int $amount
|
||||
*
|
||||
* @return void
|
||||
* @throws \Krugozor\Database\Mysql\Exception
|
||||
*/
|
||||
public function sendMoney($receiver, $amount)
|
||||
public function sendMoney(int $receiver, int $amount): void
|
||||
{
|
||||
if ($amount > 0) {
|
||||
if (db::c()->query('SELECT `user_id` FROM `bank` WHERE `id` = ?i', $receiver)) {
|
||||
if ($amount <= 0) {
|
||||
throw new Exception(self::ERROR_WRONG_AMOUNT);
|
||||
}
|
||||
if (!db::c()->query('SELECT 1 FROM bank WHERE user_id = ?i', $receiver)) {
|
||||
throw new Exception(self::ERROR_NO_BANK_ACCOUNT);
|
||||
}
|
||||
$amountWithComission = $amount + $this->bankComission($amount);
|
||||
if ($amountWithComission <= $this->money) {
|
||||
if ($amountWithComission > $this->money) {
|
||||
throw new Exception(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT);
|
||||
}
|
||||
$this->money -= $amountWithComission;
|
||||
// Снимаем сумму с комиссией у отправителя
|
||||
db::c()->query('UPDATE bank SET money = money - ?i WHERE `user_id` = ?i', $amountWithComission, $this->user_id);
|
||||
$this->setBankMoney($this->money, $this->user_id);
|
||||
// Отдаём сумму на счёт получателю
|
||||
db::c()->query('UPDATE bank SET money = money + ?i WHERE `user_id` = ?i', $amount, $receiver);
|
||||
$this->setBankMoney($amount, $receiver);
|
||||
$this->bankLogs($receiver, $amount, "sendMoney");
|
||||
$this->status = self::SUCCESS;
|
||||
} else {
|
||||
$this->status = self::ERROR_NO_MONEY_IN_BANK_ACCOUNT;
|
||||
}
|
||||
} else {
|
||||
$this->status = self::ERROR_NO_BANK_ACCOUNT;
|
||||
}
|
||||
} else {
|
||||
$this->status = self::ERROR_WRONG_AMOUNT;
|
||||
}
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Пополнение банковского счёта игрока
|
||||
* @param $amount - сумма
|
||||
* @return string
|
||||
*
|
||||
* @param int $amount - сумма
|
||||
*
|
||||
* @return void
|
||||
* @throws \Krugozor\Database\Mysql\Exception
|
||||
*/
|
||||
public function depositMoney($amount)
|
||||
public function depositMoney(int $amount): void
|
||||
{
|
||||
if ($amount > 0) {
|
||||
$row = db::c()->query('SELECT money FROM users WHERE id = ?i', $this->user_id)->fetch_assoc();
|
||||
if ($amount >= $row['money']) {
|
||||
if ($amount <= 0) {
|
||||
throw new Exception(self::ERROR_WRONG_AMOUNT);
|
||||
}
|
||||
$wallet = db::c()->query('SELECT money FROM users WHERE id = ?i', $this->user_id)->fetch_object();
|
||||
if ($wallet->money < $amount) {
|
||||
throw new Exception(self::ERROR_NO_MONEY_IN_WALLET);
|
||||
}
|
||||
// Забираем деньги из кошелька получателя
|
||||
db::c()->query('UPDATE users SET money = money - ?i WHERE `id` = ?i', $amount, $this->user_id);
|
||||
//todo check it!
|
||||
$this->user->money -= $amount;
|
||||
$this->setWalletMoney($this->user->money, $this->user_id);
|
||||
// Отдаём сумму на счёт получателю
|
||||
db::c()->query('UPDATE bank SET money = money + ?i WHERE `user_id` = ?i', $amount, $this->user_id);
|
||||
$this->money += $amount;
|
||||
$this->setBankMoney($this->money, $this->user_id);
|
||||
$this->bankLogs(0, $amount, "depositMoney");
|
||||
$this->status = self::SUCCESS;
|
||||
} else {
|
||||
$this->status = self::ERROR_NO_MONEY_IN_WALLET;
|
||||
}
|
||||
} else {
|
||||
$this->status = self::ERROR_WRONG_AMOUNT;
|
||||
}
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Снятие денег с банковского счёта игрока с банковской комиссией.
|
||||
* @param $amount - сумма
|
||||
* @return string
|
||||
*
|
||||
* @param int $amount - сумма
|
||||
*
|
||||
* @return void
|
||||
* @throws \Krugozor\Database\Mysql\Exception
|
||||
*/
|
||||
public function withdrawMoney($amount)
|
||||
public function withdrawMoney(int $amount): void
|
||||
{
|
||||
if ($amount > 0) {
|
||||
if ($amount <= 0) {
|
||||
throw new Exception(self::ERROR_WRONG_AMOUNT);
|
||||
}
|
||||
$amountWithComission = $amount + $this->bankComission($amount);
|
||||
if ($amountWithComission <= $this->money) {
|
||||
if ($this->money < $amountWithComission) {
|
||||
throw new Exception(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT);
|
||||
}
|
||||
// Снимаем сумму с комиссией у отправителя
|
||||
db::c()->query('UPDATE bank SET money = money - ?i WHERE `user_id` = ?i', $amountWithComission, $this->user_id);
|
||||
$this->money -= $amountWithComission;
|
||||
$this->setBankMoney($this->money, $this->user_id);
|
||||
// Отдаём сумму в кошелёк получателя
|
||||
db::c()->query('UPDATE users SET money = money + ?i WHERE `id` = ?i', $amount, $this->user_id);
|
||||
//todo check it!
|
||||
$this->user->money += $amount;
|
||||
$this->setWalletMoney($this->user->money, $this->user_id);
|
||||
$this->bankLogs(0, $amount, "withdrawMoney");
|
||||
$this->status = self::SUCCESS;
|
||||
} else {
|
||||
$this->status = self::ERROR_NO_MONEY_IN_BANK_ACCOUNT;
|
||||
}
|
||||
} else {
|
||||
$this->status = self::ERROR_WRONG_AMOUNT;
|
||||
|
||||
private function setBankMoney(int $amount, int $user_id): void
|
||||
{
|
||||
db::c()->query('UPDATE bank SET money = ?i WHERE `id` = ?i', $amount, $user_id);
|
||||
}
|
||||
return $this->status;
|
||||
private function setWalletMoney(int $amount, int $user_id): void
|
||||
{
|
||||
db::c()->query('UPDATE users SET money = ?i WHERE `id` = ?i', $amount, $user_id);
|
||||
}
|
||||
}
|
@ -6,11 +6,10 @@
|
||||
* Project name: Battles-Game
|
||||
*/
|
||||
require_once 'config.php';
|
||||
if (isset($_SESSION['uid'])) {
|
||||
$user = new User($_SESSION['uid']);
|
||||
} else {
|
||||
echo "Не могу проинициализировать игрока!";
|
||||
if (empty($_SESSION['uid'])) {
|
||||
throw new Exception('Не могу проинициализировать игрока!');
|
||||
}
|
||||
$user = new User($_SESSION['uid']);
|
||||
if ($user->id && $user->block) {
|
||||
exit('user blocked!');
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user