From 3ca33f38aa7c0669e96d22f87b681d5e129458e2 Mon Sep 17 00:00:00 2001 From: "Igor Barkov (iwork)" Date: Fri, 25 Sep 2020 19:27:11 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA.=20=D0=9C?= =?UTF-8?q?=D0=B5=D0=BD=D1=8C=D1=88=D0=B5=20sql-=D0=B7=D0=B0=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D1=81=D0=BE=D0=B2=20=D0=B2=20=D0=BB=D0=BE=D0=B3=D0=B8?= =?UTF-8?q?=D0=BA=D0=B5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bank.php | 28 +++++----- classes/Bank.php | 138 ++++++++++++++++++++++++++--------------------- functions.php | 7 ++- 3 files changed, 94 insertions(+), 79 deletions(-) diff --git a/bank.php b/bank.php index a5645e4..0b3d06a 100644 --- a/bank.php +++ b/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); } ?> @@ -64,7 +66,7 @@ if ($_SESSION[BANK_SESSION_NAME]) {

← выйти из счёта

-
status ?>
+
Cчет №user_id ?> На счету: money ?> diff --git a/classes/Bank.php b/classes/Bank.php index 2ee341d..09aa7fd 100644 --- a/classes/Bank.php +++ b/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)) { - $amountWithComission = $amount + $this->bankComission($amount); - if ($amountWithComission <= $this->money) { - // Снимаем сумму с комиссией у отправителя - db::c()->query('UPDATE bank SET money = money - ?i WHERE `user_id` = ?i', $amountWithComission, $this->user_id); - // Отдаём сумму на счёт получателю - db::c()->query('UPDATE bank SET money = money + ?i WHERE `user_id` = ?i', $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; + if ($amount <= 0) { + throw new Exception(self::ERROR_WRONG_AMOUNT); } - return $this->status; + 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) { + throw new Exception(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT); + } + $this->money -= $amountWithComission; + // Снимаем сумму с комиссией у отправителя + $this->setBankMoney($this->money, $this->user_id); + // Отдаём сумму на счёт получателю + $this->setBankMoney($amount, $receiver); + $this->bankLogs($receiver, $amount, "sendMoney"); } /** * Пополнение банковского счёта игрока - * @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']) { - // Забираем деньги из кошелька получателя - db::c()->query('UPDATE users SET money = money - ?i WHERE `id` = ?i', $amount, $this->user_id); - // Отдаём сумму на счёт получателю - db::c()->query('UPDATE bank SET money = money + ?i WHERE `user_id` = ?i', $amount, $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; + if ($amount <= 0) { + throw new Exception(self::ERROR_WRONG_AMOUNT); } - return $this->status; + $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); + } + // Забираем деньги из кошелька получателя + //todo check it! + $this->user->money -= $amount; + $this->setWalletMoney($this->user->money, $this->user_id); + // Отдаём сумму на счёт получателю + $this->money += $amount; + $this->setBankMoney($this->money, $this->user_id); + $this->bankLogs(0, $amount, "depositMoney"); } /** * Снятие денег с банковского счёта игрока с банковской комиссией. - * @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) { - $amountWithComission = $amount + $this->bankComission($amount); - if ($amountWithComission <= $this->money) { - // Снимаем сумму с комиссией у отправителя - db::c()->query('UPDATE bank SET money = money - ?i WHERE `user_id` = ?i', $amountWithComission, $this->user_id); - // Отдаём сумму в кошелёк получателя - db::c()->query('UPDATE users SET money = money + ?i WHERE `id` = ?i', $amount, $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; + if ($amount <= 0) { + throw new Exception(self::ERROR_WRONG_AMOUNT); } - return $this->status; + $amountWithComission = $amount + $this->bankComission($amount); + if ($this->money < $amountWithComission) { + throw new Exception(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT); + } + // Снимаем сумму с комиссией у отправителя + $this->money -= $amountWithComission; + $this->setBankMoney($this->money, $this->user_id); + // Отдаём сумму в кошелёк получателя + //todo check it! + $this->user->money += $amount; + $this->setWalletMoney($this->user->money, $this->user_id); + $this->bankLogs(0, $amount, "withdrawMoney"); + } + + private function setBankMoney(int $amount, int $user_id): void + { + db::c()->query('UPDATE bank SET money = ?i WHERE `id` = ?i', $amount, $user_id); + } + private function setWalletMoney(int $amount, int $user_id): void + { + db::c()->query('UPDATE users SET money = ?i WHERE `id` = ?i', $amount, $user_id); } } \ No newline at end of file diff --git a/functions.php b/functions.php index efd6261..8f6b196 100644 --- a/functions.php +++ b/functions.php @@ -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!'); }