1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NotificationChannels\Hooks; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as HttpClient; |
6
|
|
|
use GuzzleHttp\Exception\ClientException; |
7
|
|
|
use GuzzleHttp\RequestOptions; |
8
|
|
|
use NotificationChannels\Hooks\Exceptions\CouldNotSendNotification; |
9
|
|
|
|
10
|
|
|
class Hooks |
11
|
|
|
{ |
12
|
|
|
/** @var HttpClient HTTP Client */ |
13
|
|
|
protected $http; |
14
|
|
|
|
15
|
|
|
/** @var null|string Hooks API Key */ |
16
|
|
|
protected $key = null; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param null $key API Key |
20
|
|
|
* @param HttpClient|null $httpClient |
21
|
|
|
*/ |
22
|
|
|
public function __construct($key = null, HttpClient $httpClient = null) |
23
|
|
|
{ |
24
|
|
|
$this->key = $key; |
25
|
|
|
|
26
|
|
|
$this->http = $httpClient; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Get HttpClient. |
31
|
|
|
* |
32
|
|
|
* @return HttpClient |
33
|
|
|
*/ |
34
|
|
|
protected function httpClient() |
35
|
|
|
{ |
36
|
|
|
return $this->http ?: $this->http = new HttpClient(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Send Notification. |
41
|
|
|
* |
42
|
|
|
* @param array|\JsonSerializable $fields |
43
|
|
|
* |
44
|
|
|
* @var param $alertId |
45
|
|
|
* @var param $message |
46
|
|
|
* @var param $url |
47
|
|
|
* |
48
|
|
|
* @throws CouldNotSendNotification |
49
|
|
|
* |
50
|
|
|
* @return mixed |
51
|
|
|
*/ |
52
|
|
|
public function send($fields) |
53
|
|
|
{ |
54
|
|
|
return $this->api($fields); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Send an API request and return response. |
59
|
|
|
* |
60
|
|
|
* @param $fields |
61
|
|
|
* |
62
|
|
|
* @throws CouldNotSendNotification |
63
|
|
|
* |
64
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
65
|
|
|
*/ |
66
|
|
|
protected function api($fields) |
67
|
|
|
{ |
68
|
|
|
if (empty($this->key)) { |
69
|
|
|
throw CouldNotSendNotification::hooksApiKeyNotProvided('You must provide your Hooks API key to send any notifications.'); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$apiUrl = 'https://api.gethooksapp.com/v1/push/'.$fields['alertId']; |
73
|
|
|
unset($fields['alertId']); |
74
|
|
|
|
75
|
|
|
try { |
76
|
|
|
return $this->httpClient()->post($apiUrl, [ |
77
|
|
|
RequestOptions::JSON => $fields, |
78
|
|
|
RequestOptions::HEADERS => ['Hooks-Authorization' => $this->key], |
79
|
|
|
]); |
80
|
|
|
} catch (ClientException $exception) { |
81
|
|
|
throw CouldNotSendNotification::hooksRespondedWithAnError($exception); |
82
|
|
|
} catch (\Exception $exception) { |
83
|
|
|
throw CouldNotSendNotification::couldNotCommunicateWithHooks($exception); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|