Passed
Push — master ( 12ecb2...6f4323 )
by Alan
15:45
created

TwilioSMS::isValid()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 0
dl 0
loc 13
rs 10
c 0
b 0
f 0
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
    function __construct($sid, $token, $number)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
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
        } catch (\Exception $e) {
85
            return false;
86
        }
87
88
        if ($account) {
0 ignored issues
show
introduced by
$account is of type Twilio\Rest\Api\V2010\AccountInstance, thus it always evaluated to true.
Loading history...
89
            return true;
90
        }
91
92
        return false;
93
    }
94
}