Completed
Push — master ( af7c86...2260a0 )
by Kazi Mainuddin
03:11
created

Smsir::getResponseData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 4
nc 3
nop 1
1
<?php
2
3
namespace Tzsk\Sms\Drivers;
4
5
use GuzzleHttp\Client;
6
use Tzsk\Sms\Abstracts\Driver;
7
8
class Smsir extends Driver
9
{
10
    /**
11
     * Smsir Settings.
12
     *
13
     * @var null|object
14
     */
15
    protected $settings;
16
17
    /**
18
     * Smsir Client.
19
     *
20
     * @var null|Client
21
     */
22
    protected $client;
23
24
    /**
25
     * Construct the class with the relevant settings.
26
     *
27
     * SendSmsInterface constructor.
28
     * @param $settings object
29
     */
30
    public function __construct($settings)
31
    {
32
        $this->settings = (object) $settings;
33
        $this->client = new Client();
34
    }
35
36
    /**
37
     * Send text message and return response.
38
     *
39
     * @return object
40
     * @throws \GuzzleHttp\Exception\GuzzleException
41
     */
42
    public function send()
43
    {
44
        $token = $this->getToken();
45
        $response = collect();
46
47
        foreach ($this->recipients as $recipient) {
48
            $result = $this->client->request(
49
                'POST',
50
                $this->settings->url.'api/MessageSend',
51
                $this->payload($recipient, $token)
52
            );
53
            $response->put($recipient, $result);
54
        }
55
56
        return (count($this->recipients) == 1) ? $response->first() : $response;
57
    }
58
59
    /**
60
     * @param string $recipient
61
     * @param string $token
62
     * @return array
63
     */
64
    protected function payload($recipient, $token)
65
    {
66
        return [
67
            'json' => [
68
                'Messages' => [$this->body],
69
                'MobileNumbers' => [$recipient],
70
                'LineNumber' => $this->settings->from,
71
            ],
72
            'headers' => [
73
                'x-sms-ir-secure-token' => $token
74
            ],
75
            'connect_timeout' => 30
76
        ];
77
    }
78
79
    /**
80
     * Get token.
81
     *
82
     * @throws \Exception
83
     * @return string
84
     */
85
    protected function getToken()
86
    {
87
        $body = [
88
            'UserApiKey' => $this->settings->apiKey,
89
            'SecretKey' => $this->settings->secretKey,
90
        ];
91
        $response = $this->client->post(
92
            $this->settings->url.'api/Token',
93
            ['json' => $body, 'connect_timeout' => 30]
94
        );
95
96
        $body = json_decode((string) $response->getBody(), true);
97
        if (empty($body['TokenKey'])) {
98
            throw new \Exception('Smsir token could not be generated.');
99
        }
100
101
        return $body['TokenKey'];
102
    }
103
}
104