Completed
Push — master ( cc889b...822d3c )
by Luke
03:46
created

PagerDutyChannel::send()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.1406

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 20
ccs 12
cts 16
cp 0.75
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 11
nc 3
nop 2
crap 3.1406
1
<?php
2
3
namespace NotificationChannels\PagerDuty;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Notifications\Notification;
7
use NotificationChannels\PagerDuty\Exceptions\ApiError;
8
use NotificationChannels\PagerDuty\Exceptions\CouldNotSendNotification;
9
10
class PagerDutyChannel
11
{
12
    /**
13
     * @var Client
14
     */
15
    protected $client;
16
17 14
    public function __construct(Client $client)
18
    {
19 14
        $this->client = $client;
20 14
    }
21
22
    /**
23
     * Send the given notification.
24
     *
25
     * @param mixed $notifiable
26
     * @param \Illuminate\Notifications\Notification $notification
27
     *
28
     * @throws \NotificationChannels\PagerDuty\Exceptions\CouldNotSendNotification
29
     */
30 14
    public function send($notifiable, Notification $notification)
31
    {
32 14
        if (! $routing_key = $notifiable->routeNotificationFor('PagerDuty')) {
33 2
            return;
34
        }
35
36
        /** @var PagerDutyMessage $data */
37 12
        $data = $notification->toPagerDuty($notifiable);
38 12
        $data->routingKey($routing_key);
39
40
        try {
41 12
            $response = $this->client->post('https://events.pagerduty.com/v2/enqueue', [
42 12
                'body' => json_encode($data->toArray()),
43 12
            ]);
44 12
        } catch (\Exception $e) {
45 2
            throw CouldNotSendNotification::create($e);
46
        }
47
48 10
        $this->handleResponse($response);
49 2
    }
50
51
    /**
52
     * @param $response
53
     *
54
     * @throws ApiError
55
     */
56 10
    public function handleResponse($response) {
57 10
        switch ($response->getStatusCode()) {
58 10
            case 200:
59 10
            case 201:
60 10
            case 202:
61 2
                return;
62 8
            case 400:
63 4
                throw ApiError::serviceBadRequest($response->getBody());
64 4
            case 429:
65 2
                throw ApiError::rateLimit();
66 2
            default:
67 2
                throw ApiError::unknownError($response->getStatusCode());
68 2
        }
69
    }
70
}
71