SnsSMS::send()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 42
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 42
ccs 0
cts 38
cp 0
rs 9.1768
c 0
b 0
f 0
cc 5
nc 7
nop 2
crap 30
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
            if (empty($this->sender)) {
42
                return [
43
                    'error' => 'Error sending SMS: Unknown error',
44
                    'sent' => false,
45
                ];
46
            }
47
48
            $data = $this->client->publish([
49
                'Message' => $message,
50
                'PhoneNumber' => $to,
51
                'MessageAttributes' => [
52
                    'AWS.SNS.SMS.SenderID' => [
53
                        'DataType' => 'String',
54
                        'StringValue' => $this->sender
55
                    ],
56
                    'AWS.SNS.SMS.SMSType'  => [
57
                        'DataType'    => 'String',
58
                        'StringValue' => 'Transactional',
59
                    ]
60
                ]
61
            ]);
62
63
            $data = $data->toArray();
64
65
            if (empty($data) || empty($data['MessageId'])) {
66
                return [
67
                    'error' => 'Error sending SMS: Unknown error',
68
                    'sent' => false,
69
                ];
70
            }
71
72
            return [
73
                'message_id' => $data['MessageId'],
74
                'sent' => true,
75
            ];
76
        } catch (\Exception $e) {
77
            return [
78
                'error' => 'Error sending SMS: ' . $e->getMessage(),
79
                'sent' => false,
80
            ];
81
        }
82
    }
83
84
    /**
85
     * Checks providers credentials.
86
     *
87
     * @return bool
88
     */
89
    public function isValid()
90
    {
91
        if (empty($this->client->listSubscriptions())) {
92
            return false;
93
        }
94
95
        return true;
96
    }
97
}