MtnMomo   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 157
Duplicated Lines 16.56 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 4
dl 26
loc 157
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A setConfig() 0 6 1
A getToken() 0 24 2
A getBalance() 0 11 1
A getTransaction() 13 13 1
A createTransaction() 0 35 5
A accountHolderActive() 13 13 1
requestUrl() 0 1 ?

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 PatricPoba\MtnMomo;
4
  
5
use GuzzleHttp\ClientInterface;
6
use PatricPoba\MtnMomo\MtnConfig;
7
use PatricPoba\MtnMomo\Http\GuzzleClient;
8
use PatricPoba\MtnMomo\Utilities\Helpers;
9
use PatricPoba\MtnMomo\Exceptions\MtnMomoException;
10
11
abstract class MtnMomo extends GuzzleClient
12
{
13
    use Helpers;
14
    
15
    /**
16
     * @var string the base url of the API 
17
     */ 
18
    const VERSION = '1.0';
19
 
20
    /**
21
     * Current product, would be overriden by the child classes
22
     * Example: 'collection', 'disbursement', 'remittance'
23
     */
24
    const PRODUCT = null; 
25
 
26
27
    public function __construct(MtnConfig $config, ClientInterface $client = null)
28
    { 
29
        parent::__construct($client);
30
 
31
        $this->setConfig($config);
32
    }
33
    
34
35
    public function setConfig(MtnConfig $config)
36
    {
37
        $this->config = $config; 
0 ignored issues
show
Bug introduced by
The property config does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
38
39
        return $this;
40
    }
41
42
    /**
43
     * Get the auth token
44
     * @return string The OAuth Token.
45
     */
46
    public function getToken() : string
47
    {  
48
        $this->config->validate(static::PRODUCT);
49
        
50
        $encodedString = base64_encode(
51
            // $this->config->collectionUserId . ':' . $this->config->collectionApiSecret
52
            $this->config->getValue(static::PRODUCT, 'userId') . ':' . $this->config->getValue(static::PRODUCT, 'apiSecret')
53
        );
54
        
55
        $headers = [
56
            'Authorization'             => 'Basic ' . $encodedString,
57
            'Content-Type'              => 'application/json', 
58
            'Ocp-Apim-Subscription-Key' => $this->config->getValue(static::PRODUCT, 'primaryKey')
59
        ];
60
          
61
        $response = $this->request('post', $url = $this->requestUrl('token'), $params = [], $headers);
62
        // { access_token: "eyJ0eXAi7MRHUfMHikzQNBPAwZ2dVaIVrUgrbhiUb10A", token_type: "access_token", expires_in: 3600 }
63
64
        if ( ! $response->isSuccess() ) {
65
            throw new MtnMomoException("Error in getting token: {$url}");
66
        }
67
68
        return $response->access_token;
0 ignored issues
show
Bug introduced by
The property access_token does not seem to exist in PatricPoba\MtnMomo\Http\ApiResponse.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
69
    }
70
71
72
    public function getBalance()
73
    {  
74
        $headers = [
75
            'Authorization'             => 'Bearer ' . $this->getToken() ,
76
            'Content-Type'              => 'application/json',
77
            "X-Target-Environment"      => $this->config->targetEnvironment,
78
            'Ocp-Apim-Subscription-Key' => $this->config->getValue(static::PRODUCT, 'primaryKey')
79
        ];
80
  
81
        return $this->request('get', $this->requestUrl('balance'), $params = [], $headers);
82
    }
83
84
85 View Code Duplication
    public function getTransaction(string $transactionId)
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...
86
    {
87
        $headers = [
88
            'Authorization'             => 'Bearer ' . $this->getToken() ,
89
            'Content-Type'              => 'application/json',
90
            "X-Target-Environment"      => $this->config->targetEnvironment,
91
            'Ocp-Apim-Subscription-Key' => $this->config->getValue(static::PRODUCT, 'primaryKey')
92
        ];
93
        
94
        $url = $this->requestUrl('getTransaction', ['referenceId'=> $transactionId]);
95
96
        return $this->request('get', $url, $params = [], $headers);
97
    }
98
 
99
    /**
100
     * Make a requestToPay (collection product) or transfer (disbursement product) or transfer (remittance product)
101
     *
102
     * @param array $params amount, mobileNumber,payeeNote,payerMessage,externalId, callbackUrl*
0 ignored issues
show
Bug introduced by
There is no parameter named $params. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
103
     * @param string $transactionUuid
104
     * @throws \Exception
105
     * @return mixed string | PatricPoba\MtnMomo\Http\ApiReponse
106
     */
107
    public function createTransaction(array $data, string $transactionUuid = null)
108
    {
109
        $params = [
110
            "amount"            => $data['amount'],
111
            "currency"          => $data['currency'] ?? $this->config->currency,
112
            "externalId"        => $data['externalId'], 
113
            /** key can be either "payee" or payer depending on the product */
114
            (static::PRODUCT === 'collection' ? 'payer' : 'payee') => [
115
                "partyIdType"   => $data['partyIdType'] ?? 'MSISDN',
116
                "partyId"       => $data['mobileNumber']
117
            ], 
118
            "payerMessage"      => $data['payerMessage'],
119
            "payeeNote"         => $data['payeeNote']
120
        ];
121
122
        $transactionUuid = $transactionUuid ?? static::uuid();
123
124
        $headers = [
125
            'Authorization'             => 'Bearer ' . $this->getToken() ,
126
            'Content-Type'              => 'application/json',
127
            "X-Target-Environment"      => $this->config->targetEnvironment,
128
            'Ocp-Apim-Subscription-Key' => $this->config->getValue(static::PRODUCT, 'primaryKey'), 
129
            "X-Reference-Id"            => $transactionUuid
130
        ];
131
        
132
        $defaultCallbackUrlInEnv = $this->config->getValue(static::PRODUCT, 'callbackUrl');
133
134
        if ( isset($data['callbackUrl']) || is_string($defaultCallbackUrlInEnv) ) {
135
            $headers['X-Callback-Url'] = $params['callbackUrl'] ?? $defaultCallbackUrlInEnv; 
136
        }
137
138
        $response = $this->request('post', $this->requestUrl('createTransaction'), $params, $headers);
139
 
140
        return $response->isSuccess() ? $transactionUuid : $response;
141
    }
142
 
143
    /**
144
     * Undocumented function
145
     *
146
     * @param [type] $mobileNumber
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
147
     * @return void
148
     */
149 View Code Duplication
    public function accountHolderActive($mobileNumber)
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...
150
    {
151
        $headers = [
152
            'Authorization'             => 'Bearer ' . $this->getToken() ,
153
            'Content-Type'              => 'application/json',
154
            "X-Target-Environment"      => $this->config->targetEnvironment,
155
            'Ocp-Apim-Subscription-Key' => $this->config->getValue(static::PRODUCT, 'primaryKey')
156
        ];
157
158
        $url = $this->requestUrl('accountholderActive', ['accountHolderId'=> $mobileNumber]) ;
159
  
160
        return $this->request('get', $url, $params = [], $headers);
161
    }
162
    
163
    
164
    abstract protected function requestUrl(string $endpointName, array $params = []) : string;
165
166
    
167
}
168