|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CoreProc\WalletPlus\Models; |
| 4 | + |
| 5 | +use CoreProc\WalletPlus\Contracts\WalletTransaction; |
| 6 | +use Exception; |
| 7 | +use Illuminate\Database\Eloquent\Model; |
| 8 | + |
| 9 | +class Wallet extends Model |
| 10 | +{ |
| 11 | + protected $fillable = [ |
| 12 | + 'user_id', |
| 13 | + 'user_type', |
| 14 | + 'wallet_type_id', |
| 15 | + 'raw_balance', |
| 16 | + ]; |
| 17 | + |
| 18 | + public function user() |
| 19 | + { |
| 20 | + return $this->morphTo('user'); |
| 21 | + } |
| 22 | + |
| 23 | + public function walletType() |
| 24 | + { |
| 25 | + return $this->belongsTo(WalletType::class); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * @param $transaction WalletTransaction|integer |
| 30 | + * @throws Exception |
| 31 | + */ |
| 32 | + public function incrementBalance($transaction) |
| 33 | + { |
| 34 | + if (is_int($transaction)) { |
| 35 | + $this->increment('raw_balance', $transaction); |
| 36 | + $this->createWalletLedgerEntry($transaction, $this->raw_balance); |
| 37 | + |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + if (! $transaction instanceof WalletTransaction) { |
| 42 | + throw new Exception('Increment balance expects parameter to be an integer or a WalletTransaction object.'); |
| 43 | + } |
| 44 | + |
| 45 | + $this->increment('raw_balance', $transaction->getAmount()); |
| 46 | + |
| 47 | + // Record in ledger |
| 48 | + $this->createWalletLedgerEntry($transaction, $this->raw_balance); |
| 49 | + |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + private function createWalletLedgerEntry($transaction, $newRunningRawBalance) |
| 54 | + { |
| 55 | + if (is_int($transaction)) { |
| 56 | + return WalletLedger::query()->create([ |
| 57 | + 'wallet_id' => $this->id, |
| 58 | + 'amount' => $transaction, |
| 59 | + 'running_raw_balance' => $newRunningRawBalance, |
| 60 | + ]); |
| 61 | + } |
| 62 | + |
| 63 | + if (! $transaction instanceof WalletTransaction) { |
| 64 | + throw new Exception('Increment balance expects parameter to be an integer or a WalletTransaction object.'); |
| 65 | + } |
| 66 | + |
| 67 | + return WalletLedger::query()->create([ |
| 68 | + 'wallet_id' => $this->id, |
| 69 | + 'transaction_id' => $transaction->id, |
| 70 | + 'transaction_type' => get_class($transaction), |
| 71 | + 'amount' => $transaction->getAmount(), |
| 72 | + 'running_raw_balance' => $newRunningRawBalance, |
| 73 | + ]); |
| 74 | + } |
| 75 | +} |
0 commit comments