Completed
Push — master ( 6db363...e3ebaa )
by Michel
11s
created

CmsmsClient::send()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0987

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 7
cts 9
cp 0.7778
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 4
nop 2
crap 3.0987
1
<?php
2
3
declare(strict_types=1);
4
5
namespace NotificationChannels\Cmsms;
6
7
use SimpleXMLElement;
8
use Illuminate\Support\Arr;
9
use GuzzleHttp\Client as GuzzleClient;
10
use NotificationChannels\Cmsms\Exceptions\CouldNotSendNotification;
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
     * @throws CouldNotSendNotification
36
     */
37 1
    public function send(CmsmsMessage $message, string $recipient)
38
    {
39 1
        if (is_null(Arr::get($message->toXmlArray(), 'FROM'))) {
40
            $message->originator(config('services.cmsms.originator'));
41
        }
42
43 1
        $response = $this->client->request('POST', static::GATEWAY_URL, [
44 1
            'body' => $this->buildMessageXml($message, $recipient),
45
            'headers' => [
46
                'Content-Type' => 'application/xml',
47
            ],
48
        ]);
49
50
        // API returns an empty string on success
51
        // On failure, only the error string is passed
52 1
        $body = $response->getBody()->getContents();
53 1
        if (! empty($body)) {
54 1
            throw CouldNotSendNotification::serviceRespondedWithAnError($body);
55
        }
56
    }
57
58
    /**
59
     * @param CmsmsMessage $message
60
     * @param string $recipient
61
     * @return string
62
     */
63 2
    public function buildMessageXml(CmsmsMessage $message, string $recipient): string
64
    {
65 2
        $xml = new SimpleXMLElement('<MESSAGES/>');
66
67 2
        $xml->addChild('AUTHENTICATION')
68 2
            ->addChild('PRODUCTTOKEN', $this->productToken);
69
70 2
        if ($tariff = $message->getTariff()) {
71 1
            $xml->addChild('TARIFF', (string) $tariff);
72
        }
73
74 2
        $msg = $xml->addChild('MSG');
75 2
        foreach ($message->toXmlArray() as $name => $value) {
76 2
            $msg->addChild($name, (string) $value);
77
        }
78 2
        $msg->addChild('TO', $recipient);
79
80 2
        return $xml->asXML();
81
    }
82
}
83