Passed
Pull Request — master (#2)
by Alan
03:33
created

SnsSMS::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
namespace Messenger\SMSProviders;
4
5
use Aws\Sns\SnsClient;
6
7
class SnsSMS implements SMSProvider
8
{
9
    /**
10
     * @var SnsClient
11
     */
12
    private $client;
13
14
    /**
15
     * @var string
16
     */
17
    private $sender;
18
19
    /**
20
     * SnsSMS constructor.
21
     *
22
     * @param SnsClient $client
23
     * @param string    $sender
24
     */
25
    function __construct(SnsClient $client, string $sender)
26
    {
27
        $this->client = $client;
28
        $this->sender = $sender;
29
    }
30
31
    /**
32
     * Sends an sms message.
33
     *
34
     * @param string $to
35
     * @param string $message
36
     * @return array
37
     */
38
    public function send(string $to, string $message)
39
    {
40
        try {
41
42
            if (empty($this->sender)) {
43
                return [
44
                    'error' => 'Error sending SMS: Unknown error',
45
                    'sent' => false,
46
                ];
47
            }
48
49
            $data = $this->client->publish([
50
                'Message' => $message,
51
                'PhoneNumber' => '+' . $to,
52
                'MessageAttributes' => [
53
                    'AWS.SNS.SMS.SenderID' => [
54
                        'DataType' => 'String',
55
                        'StringValue' => $this->sender
56
                    ],
57
                    'AWS.SNS.SMS.SMSType'  => [
58
                        'DataType'    => 'String',
59
                        'StringValue' => 'Transactional',
60
                    ]
61
                ]
62
            ]);
63
64
            $data = $data->toArray();
65
66
            if (empty($data) || empty($data['MessageId'])) {
67
                return [
68
                    'error' => 'Error sending SMS: Unknown error',
69
                    'sent' => false,
70
                ];
71
            }
72
73
            return [
74
                'message_id' => $data['MessageId'],
75
                'sent' => true,
76
            ];
77
        } catch (\Exception $e) {
78
            return [
79
                'error' => 'Error sending SMS: ' . $e->getMessage(),
80
                'sent' => false,
81
            ];
82
        }
83
    }
84
85
    /**
86
     * Checks providers credentials.
87
     *
88
     * @return bool
89
     */
90
    public function isValid()
91
    {
92
        $subscriptions = $this->client->listSubscriptions();
93
94
        if (empty($subscriptions)) {
95
            return false;
96
        }
97
98
        return true;
99
    }
100
}