public function sendAction() { if ($this->request->isPost()) { $sender = User::findFirst($this->request->getPost("senderId", "int", 0)); $recipient = User::findFirst($this->request->getPost("recipientId", "int", 0)); $amount = $this->request->getPost("amount", "float", 0); $transaction = new Transaction(); $result = $sender->sendMoney($amount, $recipient, $transaction); if ($result === false) { foreach ($sender->getErrors() as $error) { $this->flashSession->error($error); } } else { $this->flashSession->success("transaction processed successfully"); } } return $this->response->redirect("/", true); }
public function sendMoney($amount, User $recipient, Transaction $transaction) { if ($amount > 0 && $recipient) { if ($this->getId() != $recipient->getId()) { $senderCardAmount = $this->getCardAmount(); $recipientCardAmount = $recipient->getCardAmount(); if ($senderCardAmount >= $amount) { $this->setCardAmount($senderCardAmount - $amount); $recipient->setCardAmount($recipientCardAmount + $amount); /** @var \Phalcon\Db\Adapter\Pdo\Mysql $db */ $db = $this->getDI()->get("db"); $db->begin(); $result = $this->save() && $recipient->save(); if ($result === false) { foreach (array_merge($this->getMessages(), $recipient->getMessages()) as $message) { $this->_addError($message->getMessage()); } $db->rollback(); } $transaction->setAmount($amount); $transaction->setRecipientId($recipient->getId()); $transaction->setSenderId($this->getId()); if ($transaction->save() === false) { foreach ($transaction->getMessages() as $message) { $this->_addError($message->getMessage()); } $db->rollback(); } $db->commit(); return true; } else { $this->_addError("sender amount must be less than sender card amount"); } } else { $this->_addError("sender and recipient cannot be equal"); } } else { $this->_addError("invalid amount or/and recipient or sender"); } return false; }