Passed
Push — master ( 2d5f59...f3a7c1 )
by Andrey
06:30
created

TurboSMS::getResponse()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 46
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 6
eloc 31
c 3
b 0
f 1
nc 4
nop 2
dl 0
loc 46
rs 8.8017
1
<?php
2
3
namespace Daaner\TurboSMS;
4
5
use Daaner\TurboSMS\Contracts\TurboSMSInterface;
6
use Daaner\TurboSMS\Traits\StartTimeAddition;
7
use Daaner\TurboSMS\Traits\ViberAddition;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Facades\Http;
10
11
class TurboSMS implements TurboSMSInterface
12
{
13
    use ViberAddition, StartTimeAddition;
14
15
    protected $api;
16
    protected $viberSender;
17
    protected $smsSender;
18
    protected $startTime;
19
    protected $isTest;
20
21
    protected $baseUri = 'https://api.turbosms.ua/';
22
23
    /**
24
     * TurboSMS constructor main settings.
25
     */
26
    public function __construct()
27
    {
28
        $this->getApi();
29
        $this->getViberSender();
30
        $this->getSMSSender();
31
        $this->isTest = config('turbosms.test_mode');
32
    }
33
34
    /**
35
     * @return int|null
36
     */
37
    public function getBalance(): ?int
38
    {
39
        $balance = null;
40
        $module = 'user';
41
        $method = 'balance.json';
42
43
        $url = $this->baseUri.$module.'/'.$method;
44
        $body = [];
45
46
        $answers = $this->getResponse($url, $body);
47
48
        if (isset($answers['result']['balance'])) {
49
            $balance = $answers['result']['balance'];
50
        }
51
52
        return $balance;
53
    }
54
55
    /**
56
     * @return array
57
     */
58
    public function getBalanceJson(): array
59
    {
60
        $module = 'user';
61
        $method = 'balance.json';
62
63
        $url = $this->baseUri.$module.'/'.$method;
64
        $body = [];
65
66
        return $this->getResponse($url, $body);
67
    }
68
69
    /**
70
     * @param  string|array  $messageId
71
     * @return array
72
     */
73
    public function getItemsStatus($messageId): array
74
    {
75
        $module = 'message';
76
        $method = 'status.json';
77
78
        $messages = collect($messageId)->values()->all();
79
80
        $url = $this->baseUri.$module.'/'.$method;
81
        $body = [
82
            'messages' => $messages,
83
        ];
84
85
        return $this->getResponse($url, $body);
86
    }
87
88
    /**
89
     * @param  string|array  $recipients
90
     * @param  string  $text
91
     * @param  string|null  $type
92
     * @return array
93
     */
94
    public function sendMessages($recipients, string $text, string $type = null): array
95
    {
96
        $module = 'message';
97
        $method = 'send.json';
98
99
        if (! $text) {
100
            return [
101
                'success' => false,
102
                'result' => null,
103
                'info' => __('turbosms::turbosms.empty_text'),
104
            ];
105
        }
106
107
        $phone = collect($recipients);
108
        $phones = $this->phonesTrim($phone);
109
        $phones = $phones->values()->all();
110
111
        $url = $this->baseUri.$module.'/'.$method;
112
        $body = [
113
            'recipients' => $phones,
114
        ];
115
116
        //SMS
117
        if ($type == 'sms' || ! $type) {
118
            $body = $this->bodySMS($body, $text);
119
        }
120
        //VIBER
121
        if ($type == 'viber') {
122
            $body = $this->bodyViber($body, $text);
123
        }
124
        //Гибридная доставка
125
        if ($type == 'both') {
126
            $body = $this->bodySMS($body, $text);
127
            $body = $this->bodyViber($body, $text);
128
        }
129
130
        //Доставка в определенное время
131
        if ($this->startTime) {
132
            $body['start_time'] = $this->startTime;
133
        }
134
135
        return $this->getResponse($url, $body);
136
    }
137
138
    /**
139
     * @param  string  $url
140
     * @param  array  $body
141
     * @return array
142
     */
143
    public function getResponse(string $url, array $body): array
144
    {
145
        if ($this->isTest) {
146
            return [
147
                'success' => false,
148
                'result' => [
149
                    'url' => $url,
150
                    'body' => $body,
151
                ],
152
                'info' => __('turbosms::turbosms.test_mode'),
153
            ];
154
        }
155
156
        $response = Http::timeout(config('turbosms.http_response_timeout', 3))
157
            ->retry(config('turbosms.http_retry_max_time', 2), config('turbosms.http_retry_delay', 200))
158
            ->withHeaders([
159
                'Accept' => 'application/json',
160
                'Authorization' => 'Bearer '.$this->api,
161
                'Content-Type' => 'application/json',
162
            ])->post($url, $body);
163
164
        if ($response->failed()) {
165
            return [
166
                'success' => false,
167
                'result' => null,
168
                'info' => __('turbosms::turbosms.error_data'),
169
            ];
170
        }
171
172
        $answer = $response->json();
173
        if (!$answer || ! isset($answer['response_result']) || ! $answer['response_result']) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $answer of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
174
            $error = __('turbosms::turbosms.response_status.'.$answer['response_status']);
175
176
            return [
177
                'success' => false,
178
                'result' => null,
179
                'info' => $error,
180
            ];
181
        }
182
183
        $info = __('turbosms::turbosms.response_status.'.$answer['response_status']);
184
185
        return [
186
            'success' => true,
187
            'result' => $answer['response_result'],
188
            'info' => $info,
189
        ];
190
    }
191
192
    // =================== SUPPORT ===================
193
194
    /**
195
     * @return string
196
     */
197
    public function getApi(): string
198
    {
199
        if (is_null($this->api)) {
200
            $this->api = (string) config('turbosms.api_key');
201
        }
202
203
        return $this->api;
204
    }
205
206
    /**
207
     * @param  string  $api
208
     * @return $this
209
     */
210
    public function setApi(string $api): self
211
    {
212
        $this->api = $api;
213
214
        return $this;
215
    }
216
217
    /**
218
     * @return string
219
     */
220
    public function getViberSender(): string
221
    {
222
        if (is_null($this->viberSender)) {
223
            $this->viberSender = (string) config('turbosms.viber_sender');
224
        }
225
226
        return $this->viberSender;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->viberSender returns the type mixed which is incompatible with the type-hinted return string.
Loading history...
227
    }
228
229
    /**
230
     * @param  string  $viberSender
231
     * @return $this
232
     */
233
    public function setViberSender(string $viberSender): self
234
    {
235
        $this->viberSender = $viberSender;
236
237
        return $this;
238
    }
239
240
    /**
241
     * @return string
242
     */
243
    public function getSMSSender(): ?string
244
    {
245
        if (is_null($this->smsSender)) {
246
            $this->smsSender = config('turbosms.sms_sender');
247
        }
248
249
        return $this->smsSender;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->smsSender returns the type mixed which is incompatible with the type-hinted return null|string.
Loading history...
250
    }
251
252
    /**
253
     * @param  string  $smsSender
254
     * @return $this
255
     */
256
    public function setSMSSender(string $smsSender): self
257
    {
258
        $this->smsSender = $smsSender;
259
260
        return $this;
261
    }
262
263
    /**
264
     * Убираем у телефонов пробелы, скобки, минусы и плюсы.
265
     *
266
     * @param  Collection  $phones
267
     * @return Collection $phones
268
     */
269
    public function phonesTrim(Collection $phones): Collection
270
    {
271
        $phones->transform(function ($item) {
272
            return preg_replace('/[^0-9]/', '', $item);
273
        });
274
275
        return $phones;
276
    }
277
278
    /**
279
     * Формируем $body для SMS.
280
     *
281
     * @param  array  $body
282
     * @param  string  $text
283
     * @return array $body
284
     */
285
    public function bodySMS(array $body, string $text): array
286
    {
287
        $body['sms'] = [
288
            'sender' => $this->smsSender,
289
            'text' => $text,
290
        ];
291
292
        return $body;
293
    }
294
295
    /**
296
     * Формируем $body для Viber.
297
     *
298
     * @param  array  $body
299
     * @param  string  $text
300
     * @return array $body
301
     */
302
    public function bodyViber(array $body, string $text): array
303
    {
304
        $msg = $text;
305
        if ($this->viberReplaceText) {
306
            $msg = $this->viberReplaceText;
307
        }
308
309
        $body['viber'] = [
310
            'sender' => $this->viberSender,
311
            'text' => $msg,
312
        ];
313
314
        if ($this->ttl) {
315
            $body['viber']['ttl'] = $this->ttl;
316
        }
317
        if ($this->imageUrl) {
318
            $body['viber']['image_url'] = $this->imageUrl;
319
        }
320
        if ($this->caption) {
321
            $body['viber']['caption'] = $this->caption;
322
        }
323
        if ($this->action) {
324
            $body['viber']['action'] = $this->action;
325
        }
326
        if ($this->countClicks) {
327
            $body['viber']['count_clicks'] = $this->countClicks;
328
        }
329
        if ($this->isTransactional) {
330
            $body['viber']['is_transactional'] = $this->isTransactional;
331
        }
332
333
        return $body;
334
    }
335
}
336