Completed
Push — master ( aba811...c04690 )
by Vincent
05:12
created

SMS::bulk()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 9.4285
1
<?php
2
/**
3
 * BongaTech SMS Client Library for PHP.
4
 *
5
 * @copyright Copyright (c) 2017
6
 * @author   Vincent Mosoti <[email protected]>
7
 * @license https://github.com/VMosoti/bongatech-sms/blob/master/LICENSE
8
 */
9
10
namespace VMosoti\BongaTech;
11
12
use VMosoti\BongaTech\Exceptions\BongaTechException;
13
14
/**
15
 * Class SMS.
16
 */
17
class SMS
18
{
19
    /**
20
     * Version number of the SMS API.
21
     *
22
     * @var string
23
     */
24
    const VERSION = '2.0.0';
25
26
    /**
27
     * Base URL.
28
     *
29
     * @var string
30
     */
31
    const BASE_URL = 'http://197.248.4.47/smsapi/';
32
33
    /**
34
     * Send SMS endpoint.
35
     *
36
     * @var string
37
     */
38
    const SMS_ENDPOINT = 'submit.php';
39
40
    /**
41
     * Get Balance endpoint.
42
     *
43
     * @var string
44
     */
45
    const GET_BALANCE_ENDPOINT = 'balance.php';
46
47
    /**
48
     * token is generated by md5(password).
49
     *
50
     * @var string
51
     */
52
    protected $token;
53
54
    /**
55
     * timestamp is the current datetime.
56
     *
57
     * @var string
58
     */
59
    protected $timestamp;
60
61
    /**
62
     * type of SMS to sent.
63
     *
64
     * @var int message
65
     */
66
    protected $message_type = 0;
67
68
    /**
69
     * batch type of the SMS being sent.
70
     *
71
     * @var int batch
72
     */
73
    protected $batch_type;
74
75
    /**
76
     * sms configurations.
77
     *
78
     * @array config
79
     */
80
    protected $config;
81
82
    /**
83
     * end point url.
84
     *
85
     * @string endpoint
86
     */
87
    protected $endpoint;
88
89
    /**
90
     * the message(s) being sent (array of messages in case message is different for each user.
91
     *
92
     * @var array.
93
     */
94
    protected $message;
95
96
    /**
97
     * the recipients .
98
     *
99
     * @var array.
100
     */
101
    protected $recipients;
102
103
    /**
104
     * SMS constructor.
105
     */
106
    public function __construct()
107
    {
108
        $this->config = Config::get();
109
        $this->setTimestamp();
110
        $this->setToken();
111
112
        if(!isset($this->config['user_id']) && !isset($this->config['password']) && !isset($this->config['sender_id'])){
113
            throw new BongaTechException('Please ensure that all configuration variables have been set.');
114
        }
115
    }
116
117
    /**
118
     * set the timestamp.
119
     */
120
    private function setTimestamp()
121
    {
122
        $this->timestamp = date('YmdHis');
123
    }
124
125
    /**
126
     * set the token.
127
     */
128
    private function setToken()
129
    {
130
        $this->token = md5($this->config['password']);
131
    }
132
133
    /**
134
     * invoke if SMS being sent is of type subscribable.
135
     *
136
     * @return $this
137
     */
138
    public function subscribable()
139
    {
140
        $this->message_type = MessageType::SUBSCIBABLE;
141
142
        return $this;
143
    }
144
145
    /**
146
     * invoke if SMS being sent is of type on demand.
147
     *
148
     * @return $this
149
     */
150
    public function onDemand()
151
    {
152
        $this->message_type = MessageType::ON_DEMAND;
153
154
        return $this;
155
    }
156
157
    /**
158
     * invoke if SMS being sent is of type bulk SMS. This will be the common one.
159
     *
160
     * @return $this
161
     */
162
    public function bulk()
163
    {
164
        $this->message_type = MessageType::BULK;
165
166
        return $this;
167
    }
168
169
    /**
170
     * invoke if SMS is being sent to a single recipient.
171
     *
172
     * @return $this
173
     */
174
    public function toOne()
175
    {
176
        $this->batch_type = BatchType::NOT_BATCH;
177
178
        return $this;
179
    }
180
181
    /**
182
     * invoke if SMS is being sent to a different recipients, or if each recipient receives custom sms.
183
     *
184
     * @return $this
185
     */
186
    public function toMany()
187
    {
188
        $this->batch_type = BatchType::BATCH;
189
190
        return $this;
191
    }
192
193
    /**
194
     * @param $recipients
195
     * @param  $message
196
     *
197
     * @throws BongaTechException
198
     *
199
     * @return mixed
200
     */
201
    public function send($recipients, $message)
202
    {
203
        $this->recipients = $recipients;
204
        $this->message = $message;
205
        $this->endpoint = self::BASE_URL.self::SMS_ENDPOINT;
206
207
        if ($this->batch_type === BatchType::NOT_BATCH) {
208 View Code Duplication
            if (is_array($this->message) && array_depth($this->message) == 2 && count($this->message) == 1) {
209
                if (is_array($this->recipients) && array_depth($this->recipients) == 2 && count($this->recipients) == 1) {
210
                    $response = $this->sendForNonBatch($this->buildSendObject($this->recipients, $this->message));
211
                } else {
212
                    throw new BongaTechException('The recipient MUST be an array of depth 2 and count should not be more than 1');
213
                }
214
            } else {
215
                throw new BongaTechException('Message should be provided as an array whose depth is 2 and count should equal 1');
216
            }
217
        } elseif ($this->batch_type === BatchType::BATCH) {
218 View Code Duplication
            if (is_array($this->message) && array_depth($this->message) == 2 && count($this->message) > 0) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
219
                if (is_array($this->recipients) && array_depth($this->recipients) == 2 && count($this->recipients) > 1) {
220
                    $response = $this->sendForBatch($this->buildSendObject($this->recipients, $this->message));
221
                } else {
222
                    throw new BongaTechException('The recipients MUST be an array of depth 2 and count should be more than 1');
223
                }
224
            } else {
225
                throw new BongaTechException('Message should be provided as an array whose depth should be 2');
226
            }
227
        } else {
228
            throw new BongaTechException('Message Batch Type has not been set.');
229
        }
230
231
        return $response;
232
    }
233
234
    /**
235
     * build the send object.
236
     *
237
     * @param  recipients
238
     * @param $messages
239
     *
240
     * @return array
241
     */
242
    private function buildSendObject($recipients, $messages)
243
    {
244
        $body = [
245
            'AuthDetails' => [
246
                [
247
                    'UserID'    => $this->config['user_id'],
248
                    'Token'     => $this->token,
249
                    'Timestamp' => $this->timestamp,
250
251
                ],
252
            ],
253
            'MessageType' => [
254
                (string) $this->message_type,
255
            ],
256
            'BatchType' => [
257
                (string) $this->batch_type,
258
            ],
259
            'SourceAddr' => [
260
                (string) $this->config['sender_id'],
261
            ],
262
            'MessagePayload'  => $messages,
263
            'DestinationAddr' => $recipients,
264
            'DeliveryRequest' => [
265
                [
266
                    'EndPoint'   => $this->config['callback_url'],
267
                    'Correlator' => (string) mt_rand(),
268
                ],
269
            ],
270
        ];
271
272
        return $body;
273
    }
274
275
    /**
276
     * send a message to a single recipient.
277
     *
278
     * @param $body
279
     *
280
     * @return Response
281
     */
282
    private function sendForNonBatch($body)
283
    {
284
        $request = new Request($this->endpoint, $body);
285
        $response = $request->sendSMS();
286
287
        return new Response($response->body[0]);
288
    }
289
290
    /**
291
     * send batch. 1) same message to many recipients 2) different messages to many recipients.
292
     *
293
     * @param $body
294
     *
295
     * @return array
296
     */
297
    private function sendForBatch($body)
298
    {
299
        $request = new Request($this->endpoint, $body);
300
        $response = $request->sendSMS();
301
302
        $responses = [];
303
        $response_count = count($response->body);
304
305
        for ($i = 0; $i < $response_count; $i++) {
306
            $res = new Response($response->body[$i]);
307
            $responses[] = $res;
308
        }
309
310
        return $responses;
311
    }
312
313
    public static function getBalance()
314
    {
315
        $config = Config::get();
316
317
        $endpoint = self::BASE_URL.self::GET_BALANCE_ENDPOINT.'?UserID='.$config['user_id'].'&Token='.md5($config['password']);
318
319
        $request = new Request($endpoint);
320
        $response = $request->getBalance();
321
322
        return new Response($response->body);
323
    }
324
}
325