1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace NotificationChannels\RocketChat; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
use GuzzleHttp\Exception\ClientException; |
9
|
|
|
use Illuminate\Notifications\Notification; |
10
|
|
|
use NotificationChannels\RocketChat\Exceptions\CouldNotSendNotification; |
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
12
|
|
|
|
13
|
|
|
final class RocketChatWebhookChannel |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The HTTP client instance. |
17
|
|
|
* |
18
|
|
|
* @var \NotificationChannels\RocketChat\RocketChat |
19
|
|
|
*/ |
20
|
|
|
private $rocketChat; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Create a new RocketChat channel instance. |
24
|
|
|
* |
25
|
|
|
* @param \NotificationChannels\RocketChat\RocketChat $rocketChat |
26
|
|
|
* @return void |
|
|
|
|
27
|
|
|
*/ |
28
|
4 |
|
public function __construct(RocketChat $rocketChat) |
29
|
|
|
{ |
30
|
4 |
|
$this->rocketChat = $rocketChat; |
31
|
4 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Send the given notification. |
35
|
|
|
* |
36
|
|
|
* @param mixed $notifiable |
37
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
38
|
|
|
* @return void |
39
|
|
|
* |
40
|
|
|
* @throws \NotificationChannels\RocketChat\Exceptions\CouldNotSendNotification |
41
|
|
|
*/ |
42
|
4 |
|
public function send($notifiable, Notification $notification): void |
43
|
|
|
{ |
44
|
|
|
/** @var \NotificationChannels\RocketChat\RocketChatMessage $message */ |
45
|
4 |
|
$message = $notification->toRocketChat($notifiable); |
|
|
|
|
46
|
|
|
|
47
|
4 |
|
$to = $message->channel ?: $notifiable->routeNotificationFor('RocketChat'); |
48
|
4 |
|
if (! $to = $to ?: $this->rocketChat->channel()) { |
49
|
1 |
|
throw CouldNotSendNotification::missingTo(); |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
if (! $from = $message->from ?: $this->rocketChat->token()) { |
53
|
1 |
|
throw CouldNotSendNotification::missingFrom(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
try { |
57
|
2 |
|
$this->sendMessage($to, $message); |
58
|
1 |
|
} catch (ClientException $exception) { |
59
|
|
|
throw CouldNotSendNotification::rocketChatRespondedWithAnError($exception); |
60
|
1 |
|
} catch (Exception $exception) { |
61
|
1 |
|
throw CouldNotSendNotification::couldNotCommunicateWithRocketChat($exception); |
62
|
|
|
} |
63
|
1 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $to |
67
|
|
|
* @param \NotificationChannels\RocketChat\RocketChatMessage $message |
68
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
69
|
|
|
*/ |
70
|
2 |
|
private function sendMessage($to, RocketChatMessage $message): ResponseInterface |
71
|
|
|
{ |
72
|
2 |
|
return $this->rocketChat->sendMessage($to, $message->toArray()); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
Adding a
@return
annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.Please refer to the PHP core documentation on constructors.