TwilioSMS   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 86
ccs 0
cts 42
cp 0
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A isValid() 0 13 4
A send() 0 26 3
1
<?php
2
3
namespace Messenger\SMSProviders;
4
5
use Twilio\Rest\Client;
6
7
class TwilioSMS implements SMSProvider
8
{
9
    /**
10
     * @var Client
11
     */
12
    var $client;
13
14
    /**
15
     * @var string
16
     */
17
    var $sid;
18
19
    /**
20
     * @var string
21
     */
22
    var $number;
23
24
    /**
25
     * TwilioMessage constructor.
26
     *
27
     * @param $sid
28
     * @param $token
29
     * @param $number
30
     * @throws \Twilio\Exceptions\ConfigurationException
31
     */
32
    public function __construct($sid, $token, $number)
33
    {
34
        $this->client = new Client($sid, $token);
35
        $this->sid = $sid;
36
        $this->number = $number;
37
    }
38
39
    /**
40
     * Sends an sms message.
41
     *
42
     * @param string $to
43
     * @param string $message
44
     * @return array
45
     */
46
    public function send(string $to, string $message)
47
    {
48
        try {
49
            $result = $this
50
                ->client
51
                ->messages
52
                ->create($to, ['from' => $this->number, 'body' => $message]);
53
54
            $sid = $result->sid;
55
        } catch (\Exception $e) {
56
            return [
57
                'error' => 'Error sending SMS: ' . $e->getMessage(),
58
                'sent' => false,
59
            ];
60
        }
61
62
        if (empty($sid)) {
63
            return [
64
                'error' => 'Error sending SMS: Unknown error',
65
                'sent' => false,
66
            ];
67
        }
68
69
        return [
70
            'message_id' => $sid,
71
            'sent' => true,
72
        ];
73
    }
74
75
    /**
76
     * Checks providers credentials.
77
     *
78
     * @return bool
79
     */
80
    public function isValid()
81
    {
82
        try {
83
            $account = $this->client->api->v2010->accounts($this->sid)->fetch();
84
85
            if ($account->friendlyName && $account->sid) {
86
                return true;
87
            }
88
        } catch (\Exception $e) {
89
            return false;
90
        }
91
92
        return false;
93
    }
94
}