Completed
Push — master ( 339387...5ba555 )
by
unknown
04:30
created

ChargeableTrait::purchaseShoppingCart()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
dl 0
loc 25
rs 8.8571
c 1
b 1
f 0
cc 2
eloc 11
nc 2
nop 2
1
<?php
2
3
namespace App\Containers\Payment\Traits;
4
5
use App\Containers\Payment\Gateway\PaymentsGateway;
6
use App\Containers\Payment\Models\PaymentAccount;
7
use App\Containers\Payment\Models\PaymentTransaction;
8
use Illuminate\Support\Facades\App;
9
use JohannesSchobel\ShoppingCart\Models\ShoppingCart;
10
11
/**
12
 * Class ChargeableTrait.
13
 *
14
 * @author  Johannes Schobel <[email protected]>
15
 * @author  Mahmoud Zalt <[email protected]>
16
 */
17
trait ChargeableTrait
18
{
19
20
    /**
21
     * @param \App\Containers\Payment\Models\PaymentAccount $account
22
     * @param int|float                                     $amount
23
     * @param string|null                                   $currency
24
     *
25
     * @return  PaymentTransaction
26
     */
27
    public function charge(PaymentAccount $account, $amount, $currency = null) : PaymentTransaction
28
    {
29
        $transaction = App::make(PaymentsGateway::class)->charge($this, $account, $amount, $currency);
30
31
        return $transaction;
32
    }
33
34
    /**
35
     * @param \App\Containers\Payment\Models\PaymentAccount     $account
36
     * @param \JohannesSchobel\ShoppingCart\Models\ShoppingCart $cart
37
     *
38
     * @return  PaymentTransaction
39
     */
40
    public function purchaseShoppingCart(PaymentAccount $account, ShoppingCart $cart) : PaymentTransaction
41
    {
42
        /**
43
         * get the "value" of the shopping cart
44
         * Note that MONEY stores the values internally as integers with the smallest currency value (e.g., 500 means 5.00 USD).
45
         * Basically, we need to re-format it to a respective float value. However, the problem is, that some currencies do not have
46
         * "smaller" currencies (cents), like others do. JPY (Yen) is such an example.
47
         * In order to handle this "automatically", we simply use the formatXXX() functions from the shopping cart!
48
         */
49
        $amount = $cart->formatMoney($cart->getTotal());
50
        $amount = floatval($amount);
51
52
        $currency = $cart->getTotal()->getCurrency();
53
54
        $transaction = $this->charge($account, $amount, $currency);
55
56
        $custom = $transaction->custom ? $transaction->custom : [];
57
        $transaction->custom = array_merge(
58
            $custom,
59
            ['cart' => $cart]
60
        );
61
        $transaction->save();
62
63
        return $transaction;
64
    }
65
66
}
67