CmsmsClient::send()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 18
ccs 6
cts 7
cp 0.8571
rs 9.9666
cc 3
nc 4
nop 2
crap 3.0261
1
<?php
2
3
declare(strict_types=1);
4
5
namespace NotificationChannels\Cmsms;
6
7
use GuzzleHttp\Client as GuzzleClient;
8
use Illuminate\Support\Arr;
9
use NotificationChannels\Cmsms\Exceptions\CouldNotSendNotification;
10
use SimpleXMLElement;
11
12
class CmsmsClient
13
{
14
    const GATEWAY_URL = 'https://sgw01.cm.nl/gateway.ashx';
15
16
    /** @var GuzzleClient */
17
    protected $client;
18
19
    /** @var string */
20
    protected $productToken;
21
22
    /**
23
     * @param GuzzleClient $client
24
     * @param string       $productToken
25
     */
26 4
    public function __construct(GuzzleClient $client, string $productToken)
27
    {
28 4
        $this->client = $client;
29 4
        $this->productToken = $productToken;
30 4
    }
31
32
    /**
33
     * @param CmsmsMessage $message
34
     * @param string       $recipient
35
     *
36
     * @throws CouldNotSendNotification
37 1
     */
38
    public function send(CmsmsMessage $message, string $recipient)
39 1
    {
40
        if (is_null(Arr::get($message->toXmlArray(), 'FROM'))) {
41
            $message->originator(config('services.cmsms.originator'));
42
        }
43 1
44 1
        $response = $this->client->request('POST', static::GATEWAY_URL, [
45
            'body'    => $this->buildMessageXml($message, $recipient),
46
            'headers' => [
47
                'Content-Type' => 'application/xml',
48
            ],
49
        ]);
50
51
        // API returns an empty string on success
52 1
        // On failure, only the error string is passed
53 1
        $body = $response->getBody()->getContents();
54 1
        if (!empty($body)) {
55
            throw CouldNotSendNotification::serviceRespondedWithAnError($body);
56
        }
57
    }
58
59
    /**
60
     * @param CmsmsMessage $message
61
     * @param string       $recipient
62
     *
63 2
     * @return string
64
     */
65 2
    public function buildMessageXml(CmsmsMessage $message, string $recipient): string
66
    {
67 2
        $xml = new SimpleXMLElement('<MESSAGES/>');
68 2
69
        $xml->addChild('AUTHENTICATION')
70 2
            ->addChild('PRODUCTTOKEN', $this->productToken);
71 1
72
        if ($tariff = $message->getTariff()) {
73
            $xml->addChild('TARIFF', (string) $tariff);
74 2
        }
75 2
76 2
        $msg = $xml->addChild('MSG');
77
        foreach ($message->toXmlArray() as $name => $value) {
78 2
            $msg->addChild($name, (string) $value);
79
        }
80 2
        $msg->addChild('TO', $recipient);
81
82
        return $xml->asXML();
83
    }
84
}
85