Passed
Push — master ( 267010...6b37f7 )
by Steeven
02:01 queued 25s
created

Citcall::setAppName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
/**
3
 * This file is part of the Citcall Package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author         Steeve Andrian Salim
9
 * @copyright      Copyright (c) Steeve Andrian Salim
10
 */
11
12
// ------------------------------------------------------------------------
13
14
namespace Steevenz;
15
16
// ------------------------------------------------------------------------
17
18
use O2System\Curl;
19
use O2System\Kernel\Http\Message\Uri;
20
use O2System\Spl\Traits\Collectors\ConfigCollectorTrait;
21
use O2System\Spl\Traits\Collectors\ErrorCollectorTrait;
22
23
/**
24
 * Class Citcall
25
 */
26
class Citcall
27
{
28
    use ConfigCollectorTrait;
29
    use ErrorCollectorTrait;
30
31
    /**
32
     * Citcall::$response
33
     *
34
     * Citcall original response.
35
     *
36
     * @access  protected
37
     * @type    mixed
38
     */
39
    protected $response;
40
41
    // ------------------------------------------------------------------------
42
43
    /**
44
     * Citcall::__construct
45
     *
46
     * @param array $config
47
     *
48
     * @access  public
49
     */
50
    public function __construct(array $config = [])
51
    {
52
        $defaultConfig = [
53
            'apiUrl'   => 'https://gateway.citcall.com/',
54
            'version'  => 'v3',
55
            'appName'  => null,
56
            'userId'   => null,
57
            'senderId' => null,
58
            'apiKey'   => null,
59
            'retry'    => 0,
60
        ];
61
62
        $this->setConfig(array_merge($defaultConfig, $config));
63
    }
64
    // ------------------------------------------------------------------------
65
66
    /**
67
     * Citcall::setApiUrl
68
     *
69
     * Set Citcall API Url.
70
     *
71
     * @param string $serverIp Citcall API Url.
72
     *
73
     * @access  public
74
     * @return  static
75
     */
76
    public function setApiUrl($apiUrl)
0 ignored issues
show
Unused Code introduced by
The parameter $apiUrl is not used and could be removed. ( Ignorable by Annotation )

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

76
    public function setApiUrl(/** @scrutinizer ignore-unused */ $apiUrl)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
77
    {
78
        $this->setConfig('apiUrl', $serverIp);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $serverIp seems to be never defined.
Loading history...
79
80
        return $this;
81
    }
82
    // ------------------------------------------------------------------------
83
84
    /**
85
     * Citcall::setAppName
86
     *
87
     * Set Citcall App Name.
88
     *
89
     * @param string $appName Application Name
90
     *
91
     * @access  public
92
     * @return  static
93
     */
94
    public function setAppName($appName)
95
    {
96
        $this->setConfig('appName', $appName);
97
98
        return $this;
99
    }
100
    // ------------------------------------------------------------------------
101
102
    /**
103
     * Citcall::setUserId
104
     *
105
     * Set Citcall User Id.
106
     *
107
     * @param string $userId Citcall User id
108
     *
109
     * @access  public
110
     * @return  static
111
     */
112
    public function setUserId($userId)
113
    {
114
        $this->setConfig('userId', $userId);
115
116
        return $this;
117
    }
118
    // ------------------------------------------------------------------------
119
120
    /**
121
     * Citcall::setUserId
122
     *
123
     * Set Citcall User Id.
124
     *
125
     * @param string $userId Citcall Sender ID
126
     *
127
     * @access  public
128
     * @return  static
129
     */
130
    public function setSenderId($senderId)
131
    {
132
        $this->setConfig('senderId', $senderId);
133
134
        return $this;
135
    }
136
    // ------------------------------------------------------------------------
137
138
    /**
139
     * Citcall::setApiKey
140
     *
141
     * Set Citcall API Key.
142
     *
143
     * @param string $apiKey Citcall API Key
144
     *
145
     * @access  public
146
     * @return  static
147
     */
148
    public function setApiKey($apiKey)
149
    {
150
        $this->setConfig('apiKey', $apiKey);
151
152
        return $this;
153
    }
154
    // ------------------------------------------------------------------------
155
156
    /**
157
     * Citcall::request
158
     *
159
     * Call API request.
160
     *
161
     * @param string $path
162
     * @param array  $params
163
     * @param string $type
164
     *
165
     * @access  protected
166
     * @return  mixed
167
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadPhpExtensionCallException
168
     */
169
    protected function request($path, $params = [], $type = 'GET')
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed. ( Ignorable by Annotation )

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

169
    protected function request($path, $params = [], /** @scrutinizer ignore-unused */ $type = 'GET')

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
170
    {
171
        // default params
172
        if (empty($this->config[ 'apiUrl' ])) {
173
            throw new \InvalidArgumentException('Citcall: API Url is not set!');
174
        }
175
176
        if (empty($this->config[ 'userId' ])) {
177
            throw new \InvalidArgumentException('Citcall: User ID is not set');
178
        }
179
180
        if (empty($this->config[ 'apiKey' ])) {
181
            throw new \InvalidArgumentException('Citcall: API Key is not set');
182
        }
183
184
        $uri = (new Uri($this->config[ 'apiUrl' ]))
185
            ->addPath($this->config[ 'version' ])
186
            ->addPath($path);
187
188
        $request = new Curl\Request();
189
        $request->setHeaders([
190
            'Authorization' => base64_encode($this->config[ 'userId' ] . ':' . $this->config[ 'apiKey' ]),
191
        ]);
192
        $request->setConnectionTimeout(500);
193
194
        if ($this->config[ 'retry' ] > 0 and $this->config[ 'retry' ] <= 20) {
195
            $params[ 'limit_try' ] = $this->config[ 'retry' ]; // default 5
196
        }
197
198
        if ($this->response = $request->setUri($uri)->post($params, true)) {
199
            if (false !== ($error = $this->response->getError())) {
0 ignored issues
show
introduced by
The condition false !== $error = $this->response->getError() is always true.
Loading history...
200
                $this->addError($error->code, $error->message);
201
            } elseif ($body = $this->response->getBody()) {
202
                return $body;
203
            }
204
        }
205
206
        return false;
207
    }
208
    // ------------------------------------------------------------------------
209
210
    /**
211
     * Citcall::buildSendPackageData
212
     *
213
     * @param array $data
214
     *
215
     * @return array|bool
216
     */
217
    protected function validateMsisdn($msisdn)
218
    {
219
        if (preg_match('/^(62[1-9]{1}[0-9]{1,2})[0-9]{6,8}$/', $msisdn) == 1) {
220
            $msisdn = '0' . substr($msisdn, 2);
221
        } elseif (preg_match('/^(\+62[1-9]{1}[0-9]{1,2})[0-9]{6,8}$/', $msisdn) == 1) {
222
            $msisdn = '0' . substr($msisdn, 3);
223
        }
224
225
        if (preg_match('/^(0[1-9]{1}[0-9]{1,2})[0-9]{6,8}$/', $msisdn) == 1) {
226
            return trim($msisdn);
0 ignored issues
show
Bug Best Practice introduced by
The expression return trim($msisdn) returns the type string which is incompatible with the documented return type array|boolean.
Loading history...
227
        }
228
229
        return false;
230
    }
231
    // ------------------------------------------------------------------------
232
233
    /**
234
     * Citcall::send
235
     *
236
     * Send SMS
237
     *
238
     * @param string $msisdn  MSISDN Number
239
     * @param string $message Message
240
     *
241
     * @access  public
242
     * @return  mixed
243
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadPhpExtensionCallException
244
     */
245
    public function send($msisdn, $message)
246
    {
247
        if (false === ($msisdn = $this->validateMsisdn($msisdn))) {
248
            throw new \InvalidArgumentException('Citcall: Invalid MSISDN Number');
249
        }
250
251
        $senderId = empty($this->config[ 'senderId' ]) ? $this->config[ 'userId' ] : $this->config[ 'senderId' ];
252
253
        return $this->request('sms', [
254
            'senderid' => $senderId,
255
            'msisdn'   => $msisdn,
256
            'text'     => $message,
257
        ], 'POST');
258
    }
259
    // ------------------------------------------------------------------------
260
261
    /**
262
     * Citcall::call
263
     *
264
     * Async Missed Call
265
     *
266
     * @param string $msisdn  MSISDN Number
267
     * @param string $gateway Gateway Number
268
     * @param bool   $async   Asyncronous call
269
     *
270
     * @access  public
271
     * @return  mixed
272
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadPhpExtensionCallException
273
     */
274
    public function call($msisdn, $gateway = 1, $async = false)
275
    {
276
        if (false === ($msisdn = $this->validateMsisdn($msisdn))) {
277
            throw new \InvalidArgumentException('Citcall: Invalid MSISDN Number');
278
        }
279
280
        if ( ! is_int($gateway) or $gateway > 5 or $gateway < 0) {
281
            throw new \InvalidArgumentException('Citcall: Invalid Gateway Number');
282
        }
283
284
        $path = $async === true ? 'asynccall' : 'call';
285
286
        return $this->request($path, [
287
            'msisdn'  => $msisdn,
288
            'gateway' => (int)$gateway,
289
        ], 'POST');
290
    }
291
    // ------------------------------------------------------------------------
292
293
    /**
294
     * Citcall::sendOtp
295
     *
296
     * Send SMS
297
     *
298
     * @param string $msisdn  MSISDN Number
299
     * @param string $token   OTP Token Code
300
     * @param int    $expires Expires time in seconds
301
     *
302
     * @access  public
303
     * @return  mixed
304
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadPhpExtensionCallException
305
     */
306
    public function sendOtp($msisdn, $token, $expires = 0)
307
    {
308
        if (false === ($msisdn = $this->validateMsisdn($msisdn))) {
309
            throw new \InvalidArgumentException('Citcall: Invalid MSISDN Number');
310
        }
311
312
        $params[ 'msisdn' ] = $msisdn;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
313
        $params[ 'senderid' ] = empty($this->config[ 'senderId' ]) ? $this->config[ 'userId' ] : $this->config[ 'senderId' ];
314
315
        $token = trim($token);
316
        if (strlen($token) < 4) {
317
            throw new \InvalidArgumentException('Citcall: OTP Code minimum length is 5 digit');
318
        } elseif (strlen($token) > 8) {
319
            throw new \InvalidArgumentException('Citcall: OTP Code maximum length is 8 digit');
320
        }
321
322
        $params[ 'token' ] = $token;
323
        $params[ 'text' ] = $params[ 'token' ] . ' is your ' . $this->config[ 'appName' ] . 'OTP code.';
324
325
        if ($expires > 0) {
326
            $params[ 'valid_time' ] = $expires;
327
        }
328
329
        return $this->request('smsotp', $params, 'POST');
330
    }
331
    // ------------------------------------------------------------------------
332
333
    /**
334
     * Citcall::verifyOtp
335
     *
336
     * @param string $trxId
337
     * @param string $msisdn
338
     * @param string $token
339
     */
340
    public function verifyOtp($trxId, $msisdn, $token)
341
    {
342
        if (false === ($msisdn = $this->validateMsisdn($msisdn))) {
343
            throw new \InvalidArgumentException('Citcall: Invalid MSISDN Number');
344
        }
345
346
        $token = trim($token);
347
348
        return $this->request('verify', [
349
            'trxid'  => $trxId,
350
            'msisdn' => $msisdn,
351
            'token'  => $token,
352
        ], 'POST');
353
    }
354
    // ------------------------------------------------------------------------
355
356
    /**
357
     * Citcall::getResponse
358
     *
359
     * Get original response object.
360
     *
361
     * @access  public
362
     * @return  \O2System\Curl\Response|bool Returns FALSE if failed.
363
     */
364
    public function getResponse()
365
    {
366
        return $this->response;
367
    }
368
    // ------------------------------------------------------------------------
369
370
    /**
371
     * Citcall::getCallback
372
     *
373
     * Get callback json response from Citcall
374
     *
375
     * @return \O2System\Curl\Response\SimpleJSONElement
376
     */
377
    public function getCallback()
378
    {
379
        $result = new Curl\Response\SimpleJSONElement([
380
            'rc'  => 0,
381
            'msg' => 'invalid callback response',
382
        ]);
383
384
        if ($response = file_get_contents('php://input')) {
385
            $data = json_decode($response, true);
386
387
            if (json_last_error() !== JSON_ERROR_NONE) {
388
                $result = new Curl\Response\SimpleJSONElement($data);
389
            }
390
        }
391
392
        return $result;
393
    }
394
}