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
|
42 |
|
public function __construct(Client $client) |
18
|
|
|
{ |
19
|
42 |
|
$this->client = $client; |
20
|
42 |
|
} |
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
|
42 |
|
public function send($notifiable, Notification $notification) |
31
|
|
|
{ |
32
|
42 |
|
if (! $routing_key = $notifiable->routeNotificationFor('PagerDuty')) { |
33
|
6 |
|
return; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** @var PagerDutyMessage $data */ |
37
|
36 |
|
$data = $notification->toPagerDuty($notifiable); |
38
|
36 |
|
$data->setRoutingKey($routing_key); |
39
|
|
|
|
40
|
|
|
try { |
41
|
36 |
|
$response = $this->client->post('https://events.pagerduty.com/v2/enqueue', [ |
42
|
36 |
|
'body' => json_encode($data->toArray()), |
43
|
12 |
|
]); |
44
|
16 |
|
} catch (\Exception $e) { |
45
|
6 |
|
throw CouldNotSendNotification::create($e); |
46
|
|
|
} |
47
|
|
|
|
48
|
30 |
|
$this->handleResponse($response); |
49
|
6 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param \Psr\Http\Message\ResponseInterface $response |
53
|
|
|
* |
54
|
|
|
* @throws ApiError |
55
|
|
|
*/ |
56
|
30 |
|
public function handleResponse($response) |
57
|
|
|
{ |
58
|
30 |
|
switch ($response->getStatusCode()) { |
59
|
30 |
|
case 200: |
60
|
26 |
|
case 201: |
61
|
26 |
|
case 202: |
62
|
6 |
|
return; |
63
|
24 |
|
case 400: |
64
|
12 |
|
throw ApiError::serviceBadRequest($response->getBody()); |
65
|
12 |
|
case 429: |
66
|
6 |
|
throw ApiError::rateLimit(); |
67
|
2 |
|
default: |
68
|
6 |
|
throw ApiError::unknownError($response->getStatusCode()); |
69
|
2 |
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|