StkPush   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 159
Duplicated Lines 5.03 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 30.65%

Importance

Changes 0
Metric Value
dl 8
loc 159
ccs 19
cts 62
cp 0.3065
rs 10
c 0
b 0
f 0
wmc 14
lcom 1
cbo 6

6 Methods

Rating   Name   Duplication   Size   Complexity  
A request() 8 8 2
A from() 0 5 1
A usingReference() 0 10 2
A push() 0 24 3
A saveStkRequest() 0 18 3
A validate() 0 21 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Samerior\MobileMoney\Mpesa\Library;
4
5
use Carbon\Carbon;
6
use Samerior\MobileMoney\Mpesa\Database\Entities\MpesaStkRequest;
7
use Samerior\MobileMoney\Mpesa\Events\StkPushRequestedEvent;
8
use Samerior\MobileMoney\Mpesa\Exceptions\MpesaException;
9
use Samerior\MobileMoney\Mpesa\Repositories\Generator;
10
use GuzzleHttp\Exception\RequestException;
11
use Illuminate\Support\Facades\Auth;
12
13
/**
14
 * Class StkPush
15
 * @package Samerior\MobileMoney\Mpesa\Library
16
 */
17
class StkPush extends ApiCore
18
{
19
    /**
20
     * @var string
21
     */
22
    protected $number;
23
    /**
24
     * @var int
25
     */
26
    protected $amount;
27
    /**
28
     * @var string
29
     */
30
    protected $reference;
31
    /**
32
     * @var string
33
     */
34
    protected $description;
35
36
    /**
37
     * @param string $amount
38
     * @return $this
39
     * @throws \Exception
40
     * @throws MpesaException
41
     */
42 View Code Duplication
    public function request($amount): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44
        if (!\is_numeric($amount)) {
45
            throw new MpesaException('The amount must be numeric, got ' . $amount);
46
        }
47
        $this->amount = $amount;
0 ignored issues
show
Documentation Bug introduced by
It seems like $amount can also be of type double or string. However, the property $amount is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
48
        return $this;
49
    }
50
51
    /**
52
     * @param string $number
53
     * @return $this
54
     */
55
    public function from($number): self
56
    {
57
        $this->number = $this->formatPhoneNumber($number);
58
        return $this;
59
    }
60
61
    /**
62
     * Set the mpesa reference
63
     *
64
     * @param string $reference
65
     * @param string $description
66
     * @return $this
67
     * @throws \Exception
68
     * @throws MpesaException
69
     */
70
    public function usingReference($reference, $description): self
71
    {
72
        \preg_match('/[^A-Za-z0-9]/', $reference, $matches);
73
        if (\count($matches)) {
74
            throw new MpesaException('Reference should be alphanumeric.');
75
        }
76
        $this->reference = $reference;
77
        $this->description = $description;
78
        return $this;
79
    }
80
81
    /**
82
     * Send a payment request
83
     *
84
     * @param null|int $amount
85
     * @param null|string $number
86
     * @param null|string $reference
87
     * @param null|string $description
88
     * @return mixed
89
     * @throws \Samerior\MobileMoney\Mpesa\Exceptions\MpesaException
90
     * @throws \GuzzleHttp\Exception\GuzzleException
91
     * @throws \Exception
92
     */
93 1
    public function push($amount = null, $number = null, $reference = null, $description = null)
94
    {
95 1
        $time = Carbon::now()->format('YmdHis');
96 1
        $shortCode = \config('samerior.mpesa.c2b.short_code');
97 1
        $passkey = \config('samerior.mpesa.c2b.passkey');
98 1
        $callback = \config('samerior.mpesa.c2b.stk_callback');
99 1
        $password = \base64_encode($shortCode . $passkey . $time);
100 1
        $good_phone = $this->formatPhoneNumber($number ?: $this->number);
101
        $body = [
102 1
            'BusinessShortCode' => $shortCode,
103 1
            'Password' => $password,
104 1
            'Timestamp' => $time,
105 1
            'TransactionType' => 'CustomerPayBillOnline',
106 1
            'Amount' => $amount ?: $this->amount,
107 1
            'PartyA' => $good_phone,
108 1
            'PartyB' => $shortCode,
109 1
            'PhoneNumber' => $good_phone,
110 1
            'CallBackURL' => $callback,
111 1
            'AccountReference' => $reference ?? $this->reference ?? $good_phone,
112 1
            'TransactionDesc' => $description ?? $this->description ?? Generator::generateTransactionNumber(),
113
        ];
114 1
        $response = $this->sendRequest($body, 'stk_push');
115
        return $this->saveStkRequest($body, (array)$response);
116
    }
117
118
    /**
119
     * @param array $body
120
     * @param array $response
121
     * @return MpesaStkRequest|\Illuminate\Database\Eloquent\Model
122
     * @throws \Exception
123
     * @throws MpesaException
124
     */
125
    private function saveStkRequest($body, $response)
126
    {
127
        if ($response['ResponseCode'] == 0) {
128
            $incoming = [
129
                'phone' => $body['PartyA'],
130
                'amount' => $body['Amount'],
131
                'reference' => $body['AccountReference'],
132
                'description' => $body['TransactionDesc'],
133
                'CheckoutRequestID' => $response['CheckoutRequestID'],
134
                'MerchantRequestID' => $response['MerchantRequestID'],
135
                'user_id' => @(Auth::id() ?: request('user_id')),
136
            ];
137
            $stk = MpesaStkRequest::create($incoming);
138
            event(new StkPushRequestedEvent($stk, request()));
139
            return $stk;
140
        }
141
        throw new MpesaException($response['ResponseDescription']);
142
    }
143
144
    /**
145
     * Validate an initialized transaction.
146
     *
147
     * @param string|int $checkoutRequestID
148
     *
149
     * @return mixed
150
     * @throws MpesaException
151
     * @throws \Exception
152
     * @throws \GuzzleHttp\Exception\GuzzleException
153
     */
154
    public function validate($checkoutRequestID)
155
    {
156
        if ((int)$checkoutRequestID) {
157
            $checkoutRequestID = MpesaStkRequest::find($checkoutRequestID)->CheckoutRequestID;
158
        }
159
        $time = Carbon::now()->format('YmdHis');
160
        $shortCode = \config('samerior.mpesa.c2b.short_code');
161
        $passkey = \config('samerior.mpesa.c2b.passkey');
162
        $password = \base64_encode($shortCode . $passkey . $time);
163
        $body = [
164
            'BusinessShortCode' => $shortCode,
165
            'Password' => $password,
166
            'Timestamp' => $time,
167
            'CheckoutRequestID' => $checkoutRequestID,
168
        ];
169
        try {
170
            return $this->sendRequest($body, 'stk_status');
171
        } catch (RequestException $exception) {
172
            throw new MpesaException($exception->getMessage());
173
        }
174
    }
175
}
176