52 lines
1.4 KiB
PHP
52 lines
1.4 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Controller;
|
|
|
|
use Model\Context;
|
|
use Model\User;
|
|
|
|
class Transaction
|
|
{
|
|
protected function __construct(
|
|
protected Context $context,
|
|
protected \PDO $sql,
|
|
) {
|
|
}
|
|
|
|
public static function run(Context $context, callable $f): mixed
|
|
{
|
|
$sql = Sql::connection();
|
|
$sql->query('START TRANSACTION');
|
|
$result = $f(new self($context, $sql));
|
|
$sql->query('COMMIT');
|
|
return $result;
|
|
}
|
|
|
|
public function createBooking(User $user, int $type, int $amount, ?User $related, string $text): bool
|
|
{
|
|
$stmt = $this->sql->prepare('SELECT balance FROM user WHERE id = ?');
|
|
$stmt->execute([$user->id]);
|
|
$currentAmount = (int) $stmt->fetch(\PDO::FETCH_ASSOC)['balance'];
|
|
$newAmount = (int) ($currentAmount + $amount);
|
|
if ($newAmount < 0) {
|
|
return false;
|
|
}
|
|
|
|
// create booking entry
|
|
$stmt = $this->sql->prepare(
|
|
'INSERT INTO booking
|
|
(affected, time, type, amount, related, comment)
|
|
VALUES
|
|
(?, ?, ?, ?, ?, ?)'
|
|
);
|
|
$stmt->execute([$user->id, $this->context->requestTime, $type, $amount, $related?->id, $text]);
|
|
|
|
// change amount
|
|
$stmt = $this->sql->prepare('UPDATE user SET balance = ? WHERE id = ?');
|
|
$stmt->execute([$newAmount, $user->id]);
|
|
|
|
return true;
|
|
}
|
|
}
|