insecure-bank/webroot/lib/Controller/TransferController.php

77 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Controller;
use Model\User;
use View\TransferPage;
use View\MoneyFormatter;
use View\Sendable;
class TransferController extends RestrictedPageController
{
public function __construct()
{
parent::__construct('/transfer.php');
}
protected function runLogic(): Sendable
{
$transferPage = new TransferPage($this->context);
if ($transferPage->formWasSent) {
$transferPage->fieldTarget = trim($transferPage->fieldTarget);
$error = false;
// find target user
$targetUser = User::byName($transferPage->fieldTarget);
if (empty($targetUser)) {
$transferPage->errorTargetNotFound = true;
$error = true;
}
// check amount
$amount = MoneyFormatter::parseAmount($transferPage->fieldAmount);
if ($amount === null) {
$transferPage->errorAmountInvalid = true;
$error = true;
} elseif ($amount === 0) {
$transferPage->errorAmountZero = true;
$error = true;
}
// check text
$text = $transferPage->fieldText;
if (iconv_strlen($text) > 100) {
$transferPage->errorTextTooLong = true;
$error = true;
}
// create the actual bookings
if (!$error) {
$success = Transaction::run($this->context, function ($transaction) use ($targetUser, $amount, $text) {
$success = $transaction->createBooking($this->context->session->user, 3, -$amount, $targetUser, $text);
if ($success) {
$transaction->createBooking($targetUser, 4, $amount, $this->context->session->user, $text);
}
return $success;
});
if (!$success) {
$transferPage->errorInsufficientFunds = true;
$error = true;
}
}
if (!$error) {
$transferPage->fieldTarget = '';
$transferPage->fieldAmount = '';
$transferPage->fieldText = '';
$transferPage->success = true;
$transferPage->successTarget = $targetUser->name;
$transferPage->successAmount = $amount;
}
}
return $transferPage;
}
}