Completed
Push — master ( 580342...0890ec )
by Mohamed
08:21
created

GitterChannel::sendMessage()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.7283

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 25
ccs 9
cts 13
cp 0.6923
rs 8.439
cc 5
eloc 15
nc 5
nop 1
crap 5.7283
1
<?php
2
3
namespace NotificationChannels\Gitter;
4
5
use Exception;
6
use GuzzleHttp\Client as HttpClient;
7
use GuzzleHttp\Exception\ClientException;
8
use Illuminate\Notifications\Notification;
9
use NotificationChannels\Gitter\Exceptions\CouldNotSendNotification;
10
11
class GitterChannel
12
{
13
    protected $baseUrl = 'https://api.gitter.im/v1/rooms';
14
15
    /** @var \GuzzleHttp\Client */
16
    protected $httpClient;
17
18 3
    public function __construct(HttpClient $client)
19
    {
20 3
        $this->httpClient = $client;
21 3
    }
22
23
    /**
24
     * Send the given notification.
25
     *
26
     * @param mixed $notifiable
27
     * @param \Illuminate\Notifications\Notification $notification
28
     *
29
     * @throws \NotificationChannels\Gitter\Exceptions\CouldNotSendNotification
30
     */
31 3
    public function send($notifiable, Notification $notification)
32
    {
33
        /** @var GitterMessage $message */
34 3
        $message = $notification->toGitter($notifiable);
35
36 3
        if (empty($message->room)) {
37 1
            $message->room($notifiable->routeNotificationFor('gitter'));
38
        }
39
40 3
        $this->sendMessage($message);
41 1
    }
42
43
    /**
44
     * @param  GitterMessage  $message
45
     *
46
     * @throws CouldNotSendNotification
47
     */
48 3
    protected function sendMessage(GitterMessage $message)
49
    {
50 3
        if (empty($message->room)) {
51 1
            throw CouldNotSendNotification::missingRoom();
52
        }
53
54 2
        if (empty($message->from)) {
55 1
            throw CouldNotSendNotification::missingFrom();
56
        }
57
58
        $options = [
59 1
            'json'    => ['text' => $message->content],
60
            'headers' => [
61 1
                'Authorization' => "Bearer {$message->from}",
62
            ],
63
        ];
64
65
        try {
66 1
            $this->httpClient->post("{$this->baseUrl}/{$message->room}/chatMessages", $options);
67
        } catch (ClientException $exception) {
68
            throw CouldNotSendNotification::gitterRespondedWithAnError($exception);
69
        } catch (Exception $exception) {
70
            throw CouldNotSendNotification::couldNotCommunicateWithGitter($exception);
71
        }
72 1
    }
73
}
74