RestApiRequest   A
last analyzed

Complexity

Total Complexity 28

Size/Duplication

Total Lines 217
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 28
eloc 105
c 1
b 0
f 0
dl 0
loc 217
rs 10

18 Methods

Rating   Name   Duplication   Size   Complexity  
A post() 0 16 3
A setRequestOptions() 0 5 1
A setRequestClient() 0 3 1
A setPort() 0 3 1
A put() 0 16 3
A getAuthorisationHeader() 0 15 1
A generateRawString() 0 9 1
A setProtocol() 0 3 1
A setHost() 0 3 1
A setBaseUrl() 0 3 1
A get() 0 15 3
A getJsonResponse() 0 3 1
A generateTimeStamp() 0 3 1
A setApiVersion() 0 3 1
A generateNonce() 0 3 1
A delete() 0 16 3
A __construct() 0 11 1
A patch() 0 16 3
1
<?php
2
3
namespace JoshuaChinemezu\SmsGlobal\RestApi\Request;
4
5
use Illuminate\Support\Facades\Config;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Psr7;
8
use GuzzleHttp\Exception\RequestException;
9
10
/*
11
 * This file is part of the SmsGlobal Laravel Package.
12
 *
13
 * (c) Joshua Chinemezu <[email protected]>
14
 *
15
 * For the full copyright and license information, please view the LICENSE
16
 * file that was distributed with this source code.
17
 */
18
19
class RestApiRequest
20
{
21
    protected $host;
22
    protected $protocol;
23
    protected $port;
24
    protected $apiVersion;
25
    protected $extraData;
26
    protected $client;
27
    protected $url;
28
    protected $action;
29
    protected $timestamp;
30
    protected $nonce;
31
    protected $apiKey;
32
    protected $secretKey;
33
    protected $hashAlgo;
34
    protected $baseUrl;
35
36
    public function __construct($apiKey, $secretKey, $hashAlgo)
37
    {
38
        $this->apiKey = $apiKey;
39
        $this->secretKey = $secretKey;
40
        $this->hashAlgo = $hashAlgo;
41
        $this->setHost();
42
        $this->setProtocol();
43
        $this->setPort();
44
        $this->setApiVersion();
45
        $this->setBaseUrl();
46
        $this->setRequestClient();
47
    }
48
49
    /**
50
     * Get debug mode from SmsGlobal config file
51
     */
52
    public function setRequestClient()
53
    {
54
        $this->client = new Client();
55
    }
56
57
    /**
58
     * Get host from SmsGlobal config file
59
     */
60
    public function setHost()
61
    {
62
        $this->host = Config::get('smsglobal.host');
63
    }
64
65
    /**
66
     * Get protocol from SmsGlobal config file
67
     */
68
    public function setProtocol()
69
    {
70
        $this->protocol = strtolower(Config::get('smsglobal.protocol'));
71
    }
72
73
    /**
74
     * Get port from SmsGlobal config file
75
     */
76
    public function setPort()
77
    {
78
        $this->port = Config::get('smsglobal.port');
79
    }
80
81
    /**
82
     * Get api version from SmsGlobal config file
83
     */
84
    public function setApiVersion()
85
    {
86
        $this->apiVersion = Config::get('smsglobal.apiVersion');
87
    }
88
89
    public function setBaseUrl()
90
    {
91
        $this->baseUrl = "{$this->protocol}://{$this->host}/{$this->apiVersion}";
92
    }
93
94
    private function setRequestOptions($action, $method)
95
    {
96
        $this->method = $method;
0 ignored issues
show
Bug Best Practice introduced by
The property method does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
97
        $this->action = $action;
98
        $this->url = "{$this->baseUrl}/{$this->action}";
99
    }
100
101
    public function get($action, $queryOptions = [])
102
    {
103
        $this->setRequestOptions($action, 'GET');
104
        try {
105
            $request = $this->client->get($this->url, [
106
                'headers' => $this->getAuthorisationHeader(),
107
                'query' => $queryOptions
108
            ],  array());
0 ignored issues
show
Unused Code introduced by
The call to GuzzleHttp\Client::get() has too many arguments starting with array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
            /** @scrutinizer ignore-call */ 
109
            $request = $this->client->get($this->url, [

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
109
        } catch (RequestException $e) {
110
            if ($e->hasResponse()) {
111
                return $this->getJsonResponse($e->getResponse());
112
            }
113
            return Psr7\str($e->getRequest());
0 ignored issues
show
Bug introduced by
The function str was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

113
            return /** @scrutinizer ignore-call */ Psr7\str($e->getRequest());
Loading history...
114
        }
115
        return $this->getJsonResponse($request);
116
    }
117
118
    public function post($action, $formData = [])
119
    {
120
        $this->setRequestOptions($action, 'POST');
121
        try {
122
            $request = $this->client->post($this->url, [
123
                'form_params' => $formData,
124
                'headers' => $this->getAuthorisationHeader(),
125
            ], array());
0 ignored issues
show
Unused Code introduced by
The call to GuzzleHttp\Client::post() has too many arguments starting with array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
            /** @scrutinizer ignore-call */ 
126
            $request = $this->client->post($this->url, [

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
126
        } catch (RequestException $e) {
127
            if ($e->hasResponse()) {
128
                return $this->getJsonResponse($e->getResponse());
129
            }
130
            return Psr7\str($e->getRequest());
0 ignored issues
show
Bug introduced by
The function str was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

130
            return /** @scrutinizer ignore-call */ Psr7\str($e->getRequest());
Loading history...
131
        }
132
133
        return $this->getJsonResponse($request);
134
    }
135
136
    public function put($action, $optionData = [])
137
    {
138
        $this->setRequestOptions($action, 'PUT');
139
        try {
140
            $request = $this->client->put($this->url, [
141
                'form_params' => $optionData,
142
                'headers' => $this->getAuthorisationHeader(),
143
            ], array());
0 ignored issues
show
Unused Code introduced by
The call to GuzzleHttp\Client::put() has too many arguments starting with array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

143
            /** @scrutinizer ignore-call */ 
144
            $request = $this->client->put($this->url, [

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
144
        } catch (RequestException $e) {
145
            if ($e->hasResponse()) {
146
                return $this->getJsonResponse($e->getResponse());
147
            }
148
            return Psr7\str($e->getRequest());
0 ignored issues
show
Bug introduced by
The function str was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

148
            return /** @scrutinizer ignore-call */ Psr7\str($e->getRequest());
Loading history...
149
        }
150
151
        return $this->getJsonResponse($request);
152
    }
153
154
    public function patch($action, $optionData = [])
155
    {
156
        $this->setRequestOptions($action, 'PATCH');
157
        try {
158
            $request = $this->client->patch($this->url, [
159
                'form_params' => $optionData,
160
                'headers' => $this->getAuthorisationHeader(),
161
            ], array());
0 ignored issues
show
Unused Code introduced by
The call to GuzzleHttp\Client::patch() has too many arguments starting with array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

161
            /** @scrutinizer ignore-call */ 
162
            $request = $this->client->patch($this->url, [

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
162
        } catch (RequestException $e) {
163
            if ($e->hasResponse()) {
164
                return $this->getJsonResponse($e->getResponse());
165
            }
166
            return Psr7\str($e->getRequest());
0 ignored issues
show
Bug introduced by
The function str was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

166
            return /** @scrutinizer ignore-call */ Psr7\str($e->getRequest());
Loading history...
167
        }
168
169
        return $this->getJsonResponse($request);
170
    }
171
172
    public function delete($action)
173
    {
174
175
        $this->setRequestOptions($action, 'DELETE');
176
        try {
177
            $request = $this->client->delete($this->url, [
178
                'headers' => $this->getAuthorisationHeader(),
179
            ], array());
0 ignored issues
show
Unused Code introduced by
The call to GuzzleHttp\Client::delete() has too many arguments starting with array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

179
            /** @scrutinizer ignore-call */ 
180
            $request = $this->client->delete($this->url, [

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
180
        } catch (RequestException $e) {
181
            if ($e->hasResponse()) {
182
                return $this->getJsonResponse($e->getResponse());
183
            }
184
            return Psr7\str($e->getRequest());
0 ignored issues
show
Bug introduced by
The function str was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

184
            return /** @scrutinizer ignore-call */ Psr7\str($e->getRequest());
Loading history...
185
        }
186
187
        return $this->getJsonResponse($request);
188
    }
189
190
    private function getJsonResponse($request)
191
    {
192
        return json_decode($request->getBody());
193
    }
194
195
    private function generateRawString()
196
    {
197
        return $this->timestamp . "\n"
198
            . $this->nonce . "\n"
199
            . $this->method . "\n"
200
            . '/' . $this->apiVersion . '/' . $this->action . "\n"
201
            . $this->host . "\n"
202
            . $this->port . "\n"
203
            . $this->extraData . "\n";
204
    }
205
206
    private function generateNonce()
207
    {
208
        return md5(microtime() . mt_rand());
209
    }
210
211
    private function generateTimeStamp()
212
    {
213
        return time();
214
    }
215
216
    /**
217
     * @param $method
218
     * @param $action
219
     * @return array of HTTP headers in key/value pair
220
     */
221
    private function getAuthorisationHeader()
222
    {
223
        $this->timestamp = $this->generateTimeStamp();
224
        $this->nonce = $this->generateNonce();
225
226
        // dd($this->generateRawString());
227
228
        # Encrypt
229
        $hash = hash_hmac($this->hashAlgo, $this->generateRawString(), $this->secretKey, true);
230
        $hash = base64_encode($hash);
231
232
        return array(
233
            "Authorization" => sprintf('MAC id="%s", ts="%s", nonce="%s", mac="%s"', $this->apiKey, $this->timestamp, $this->nonce, $hash),
234
            'Accept' => 'application/json',
235
            'Content-Type'  => 'application/json',
236
        );
237
    }
238
}
239