SmsirClient::send()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 12
c 1
b 0
f 1
dl 0
loc 17
rs 9.8666
cc 3
nc 4
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Rezahmady\Smsir;
6
7
use GuzzleHttp\Client;
8
use Rezahmady\Smsir\Responses\SMSLine;
9
use Psr\Http\Message\ResponseInterface;
10
use Rezahmady\Smsir\Responses\Message;
11
use GuzzleHttp\Exception\GuzzleException;
12
use Rezahmady\Smsir\Responses\SentMessage;
13
use Rezahmady\Smsir\Responses\SendResponse;
14
use Rezahmady\Smsir\Responses\CreditResponse;
15
use Rezahmady\Smsir\Responses\ReceivedMessage;
16
use Rezahmady\Smsir\Responses\SMSLinesResponse;
17
use Rezahmady\Smsir\Responses\SentMessagesResponse;
18
use Rezahmady\Smsir\Responses\VerificationCodeResponse;
19
use Rezahmady\Smsir\Responses\ReceivedMessagesResponse;
20
21
class SmsirClient
22
{
23
    private $userApiKey;
24
    private $secretKey;
25
    private $token;
26
    private $lineNumber;
27
    private $client;
28
29
    /**
30
     * Create a new SMSIR Instance
31
     * @param string $userApiKey
32
     * @param string $secretKey
33
     * @param string $lineNumber
34
     * @param int $timeout
35
     */
36
    public function __construct(string $userApiKey, string $secretKey, string $lineNumber, int $timeout = 10)
37
    {
38
        $this->userApiKey = $userApiKey;
39
        $this->secretKey = $secretKey;
40
        $this->token = "";
41
        $this->lineNumber = $lineNumber;
42
43
        $this->client = new Client([
44
            'base_uri' => 'http://restfulsms.com/api/',
45
            'timeout' => $timeout,
46
        ]);
47
    }
48
49
    /**
50
     * this method return your credit in sms.ir (sms credit, not money)
51
     *
52
     * @return CreditResponse
53
     * @throws GuzzleException
54
     */
55
    public function smsCredit(): CreditResponse
56
    {
57
        $result = $this->executeRequest('credit');
58
        $json = json_decode($result->getBody()->getContents(), true);
59
        return new CreditResponse($json['IsSuccessful'], $json['Message'], $json['Credit']);
60
    }
61
62
    /**
63
     * @param string $route
64
     * @param null $body
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $body is correct as it would always require null to be passed?
Loading history...
65
     * @return ResponseInterface
66
     * @throws GuzzleException
67
     */
68
    private function executeRequest(string $route, $body = null): ResponseInterface
69
    {
70
        if (is_null($body)) {
0 ignored issues
show
introduced by
The condition is_null($body) is always true.
Loading history...
71
            return $this->client->get($route, [
72
                'headers' => [
73
                    'x-sms-ir-secure-token' => $this->getToken(),
74
                ],
75
            ]);
76
        }
77
        return $this->client->post($route, [
78
            'json' => $body,
79
            'headers' => [
80
                'x-sms-ir-secure-token' => $this->getToken(),
81
            ],
82
        ]);
83
    }
84
85
    /**
86
     * this method used in every request to get the token at first.
87
     *
88
     * @return mixed - the Token for use api
89
     * @return string
90
     * @throws GuzzleException
91
     */
92
    private function getToken(): string
93
    {
94
        $body = [
95
            'UserApiKey' => $this->userApiKey,
96
            'SecretKey' => $this->secretKey,
97
        ];
98
        $result = $this->client->post('Token', [
99
            'json' => $body,
100
        ]);
101
        return json_decode($result->getBody()->getContents(), true)['TokenKey'];
102
    }
103
104
    /**
105
     * by this method you can fetch all of your sms lines.
106
     *
107
     * @return SMSLinesResponse
108
     * @throws GuzzleException
109
     */
110
    public function getSMSLines(): SMSLinesResponse
111
    {
112
        $result = $this->executeRequest('SMSLine');
113
        $json = json_decode($result->getBody()->getContents(), true);
114
        $lineArray = [];
115
        foreach ($json['SMSLines'] as $SMSLine) {
116
            $lineArray[] = new SMSLine((int)$SMSLine['ID'], (string)$SMSLine['LineNumber']);
117
        }
118
        return new SMSLinesResponse($json['IsSuccessful'], $json['Message'], $lineArray);
119
    }
120
121
    /**
122
     * Simple send message with sms.ir account and line number
123
     *
124
     * @param array $messages Messages - Count must be equal with $mobileNumbers
125
     * @param array $mobileNumbers Numbers - must be equal with $messages
126
     * @param null $sendDateTime Avoid this param if you want to send message now
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $sendDateTime is correct as it would always require null to be passed?
Loading history...
127
     * @return SendResponse
128
     * @throws GuzzleException
129
     */
130
    public function send(array $messages, array $mobileNumbers, $sendDateTime = null): SendResponse
131
    {
132
        $body = [
133
            'Messages' => $messages,
134
            'MobileNumbers' => $mobileNumbers,
135
            'LineNumber' => $this->lineNumber,
136
        ];
137
        if ($sendDateTime !== null) {
0 ignored issues
show
introduced by
The condition $sendDateTime !== null is always false.
Loading history...
138
            $body['SendDateTime'] = $sendDateTime;
139
        }
140
        $result = $this->executeRequest('MessageSend', $body);
141
        $json = json_decode($result->getBody()->getContents(), true);
142
        $sentMessages = [];
143
        foreach ($json['Ids'] as $sentMessage) {
144
            $sentMessages[] = new SentMessage((int)$sentMessage['ID'], (string)$sentMessage['MobileNo']);
145
        }
146
        return new SendResponse($json['IsSuccessful'], $json['Message'], $json['BatchKey'], $sentMessages);
147
    }
148
149
    /**
150
     * this method send a verification code to your customer. need active the module at panel first.
151
     *
152
     * @param string $code
153
     * @param string $mobileNumber
154
     * @return VerificationCodeResponse
155
     * @throws GuzzleException
156
     */
157
    public function sendVerificationCode(string $code, string $mobileNumber): VerificationCodeResponse
158
    {
159
        $body = [
160
            'Code' => $code,
161
            'MobileNumber' => $mobileNumber,
162
        ];
163
        $result = $this->executeRequest('VerificationCode', $body);
164
        $json = json_decode($result->getBody()->getContents(), true);
165
        return new VerificationCodeResponse(
166
            $json['IsSuccessful'],
167
            $json['Message'],
168
            (string)$json['VerificationCodeId']
169
        );
170
    }
171
172
173
    /**
174
     * @param array $parameters
175
     * @param string $templateId
176
     * @param string $mobileNumber
177
     * @return VerificationCodeResponse
178
     * @throws GuzzleException
179
     */
180
    public function ultraFastSend(array $parameters, string $templateId, string $mobileNumber): VerificationCodeResponse
181
    {
182
        $params = [];
183
        foreach ($parameters as $key => $value) {
184
            $params[] = ['Parameter' => $key, 'ParameterValue' => $value];
185
        }
186
        $body = [
187
            'ParameterArray' => $params,
188
            'TemplateId' => $templateId,
189
            'Mobile' => $mobileNumber,
190
        ];
191
        $result = $this->executeRequest('UltraFastSend', $body);
192
        $json = json_decode($result->getBody()->getContents(), true);
193
        return new VerificationCodeResponse(
194
            $json['IsSuccessful'],
195
            $json['Message'],
196
            (string)$json['VerificationCodeId']
197
        );
198
    }
199
200
    /**
201
     * this method used for fetch your sent messages
202
     *
203
     * @param $fromDate = from date (example: 1399/06/01)
0 ignored issues
show
Documentation Bug introduced by
The doc comment = at position 0 could not be parsed: Unknown type name '=' at position 0 in =.
Loading history...
204
     * @param $toDate = to date (example: 1399/08/25)
205
     * @param int $pageNumber = the page number
206
     * @param int $perPage = how many sms you want to fetch in every page
207
     * @return SentMessagesResponse
208
     * @throws GuzzleException
209
     */
210
    public function getSentMessages($fromDate, $toDate, int $pageNumber = 1, int $perPage = 100): SentMessagesResponse
211
    {
212
        $result = $this->executeRequest("MessageSend?Shamsi_FromDate=$fromDate&Shamsi_ToDate=$toDate&RowsPerPage=$perPage&RequestedPageNumber=$pageNumber");
213
        $json = json_decode($result->getBody()->getContents(), true);
214
        $messages = [];
215
        foreach ($json['Messages'] as $message) {
216
            $messages[] = new Message(
217
                (int)$message['ID'],
218
                (string)$message['LineNumber'],
219
                (string)$message['SMSMessageBody'],
220
                (string)$message['MobileNo'],
221
                (string)$message['TypeOfMessage'],
222
                (string)$message['NativeDeliveryStatus'],
223
                (string)$message['ToBeSentAt'],
224
                (string)$message['SendDateTimeLatin'],
225
                (string)$message['PersianSendDateTime'],
226
                (bool)$message['IsChecked'],
227
                (bool)$message['IsError'],
228
            );
229
        }
230
        return new SentMessagesResponse(
231
            (bool)$json['IsSuccessful'],
232
            $json['Message'],
233
            (int)$json['CountOfAll'],
234
            $messages
235
        );
236
    }
237
238
    /**
239
     * this method used for fetch received messages
240
     *
241
     * @param $fromDate = from date (example: 1399/06/01)
0 ignored issues
show
Documentation Bug introduced by
The doc comment = at position 0 could not be parsed: Unknown type name '=' at position 0 in =.
Loading history...
242
     * @param $toDate = to date (example: 1399/08/25)
243
     * @param int $pageNumber = the page number
244
     * @param int $perPage = how many sms you want to fetch in every page
245
     * @return ReceivedMessagesResponse
246
     * @throws GuzzleException
247
     *
248
     */
249
    public function getReceivedMessages(
250
        $fromDate,
251
        $toDate,
252
        int $pageNumber = 1,
253
        int $perPage = 100
254
    ): ReceivedMessagesResponse {
255
        $result = $this->executeRequest("ReceiveMessage?Shamsi_FromDate=$fromDate&Shamsi_ToDate=$toDate&RowsPerPage=$perPage&RequestedPageNumber=$pageNumber");
256
        $json = json_decode($result->getBody()->getContents(), true);
257
        $messages = [];
258
        foreach ($json['Messages'] as $message) {
259
            $messages[] = new ReceivedMessage(
260
                (int)$message['ID'],
261
                (string)$message['LineNumber'],
262
                (string)$message['SMSMessageBody'],
263
                (string)$message['MobileNo'],
264
                (string)$message['TypeOfMessage'],
265
                (string)$message['LatinReceiveDateTime'],
266
                (string)$message['ReceiveDateTime']
267
            );
268
        }
269
        return new ReceivedMessagesResponse(
270
            (bool)$json['IsSuccessful'],
271
            $json['Message'],
272
            (int)$json['CountOfAll'],
273
            $messages
274
        );
275
    }
276
}
277