Guest User

Untitled

a guest
Nov 22nd, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. <?php
  2.  
  3. function transfer($fromAccountId, $toAccountId, $balance)
  4. {
  5. $fromQuery = Account::whereId($fromAccountId);
  6. if (! $fromQuery->exists()) {
  7. throw new InvalidAccountException();
  8. }
  9.  
  10. $toQuery = Account::whereId($toAccountId);
  11. if (! $toQuery->exists()) {
  12. throw new InvalidAccountException();
  13. }
  14.  
  15. do {
  16. $fromAccount = $fromQuery->first();
  17. if ($fromAccount->balance < $amount) {
  18. throw new InsufficientBalanceException();
  19. }
  20. $updated = Account::whereId($fromAccountId)
  21. ->where('updated_at', '=', $fromAccount->updated_at)
  22. ->update(['balance' => $fromAccount->balance - $amount]);
  23. } while (! $updated);
  24.  
  25. do {
  26. $toAccount = $toQuery->first();
  27. $updated = Account::whereId($toAccountId)
  28. ->where('updated_at', '=', $toAccount->updated_at)
  29. ->update(['balance' => $toAccount->balance + $amount]);
  30. } while (! $updated);
  31.  
  32. $transaction = new Transaction();
  33. $transaction->from_account_id = $fromAccountId;
  34. $transaction->to_account_id = $toAccountId;
  35. $transaction->amount = $amount;
  36. $transaction->save();
  37. }
Add Comment
Please, Sign In to add comment