1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Illuminate\Notifications\Channels; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as HttpClient; |
6
|
|
|
use Illuminate\Notifications\Notification; |
7
|
|
|
use Illuminate\Notifications\Messages\SlackMessage; |
8
|
|
|
use Illuminate\Notifications\Messages\SlackAttachment; |
9
|
|
|
|
10
|
|
|
class SlackWebhookChannel |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* The HTTP client instance. |
14
|
|
|
* |
15
|
|
|
* @var \GuzzleHttp\Client |
16
|
|
|
*/ |
17
|
|
|
protected $http; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Create a new Slack channel instance. |
21
|
|
|
* |
22
|
|
|
* @param \GuzzleHttp\Client $http |
23
|
|
|
* @return void |
|
|
|
|
24
|
|
|
*/ |
25
|
1 |
|
public function __construct(HttpClient $http) |
26
|
|
|
{ |
27
|
1 |
|
$this->http = $http; |
28
|
1 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Send the given notification. |
32
|
|
|
* |
33
|
|
|
* @param mixed $notifiable |
34
|
|
|
* @param \Illuminate\Notifications\Notification $notification |
35
|
|
|
* @return void |
36
|
|
|
*/ |
37
|
1 |
|
public function send($notifiable, Notification $notification) |
38
|
|
|
{ |
39
|
1 |
|
if (! $url = $notifiable->routeNotificationFor('slack')) { |
40
|
|
|
return; |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
$message = $notification->toSlack($notifiable); |
|
|
|
|
44
|
|
|
|
45
|
1 |
|
$this->http->post($url, [ |
46
|
|
|
'json' => [ |
47
|
1 |
|
'text' => $message->content, |
48
|
1 |
|
'attachments' => $this->attachments($message), |
49
|
|
|
], |
50
|
|
|
]); |
51
|
1 |
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Format the message's attachments. |
55
|
|
|
* |
56
|
|
|
* @param \Illuminate\Notifications\Messages\SlackMessage $message |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
1 |
|
protected function attachments(SlackMessage $message) |
60
|
|
|
{ |
61
|
|
|
return collect($message->attachments)->map(function ($attachment) use ($message) { |
62
|
1 |
|
return array_filter([ |
63
|
1 |
|
'color' => $message->color(), |
64
|
1 |
|
'title' => $attachment->title, |
65
|
1 |
|
'text' => $attachment->content, |
66
|
1 |
|
'title_link' => $attachment->url, |
67
|
1 |
|
'fields' => $this->fields($attachment), |
68
|
|
|
]); |
69
|
1 |
|
})->all(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Format the attachment's fields. |
74
|
|
|
* |
75
|
|
|
* @param \Illuminate\Notifications\Messages\SlackAttachment $attachment |
76
|
|
|
* @return array |
77
|
|
|
*/ |
78
|
|
|
protected function fields(SlackAttachment $attachment) |
79
|
|
|
{ |
80
|
1 |
|
return collect($attachment->fields)->map(function ($value, $key) { |
81
|
1 |
|
return ['title' => $key, 'value' => $value, 'short' => true]; |
82
|
1 |
|
})->values()->all(); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
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.