-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSlackNotificationChannel.php
97 lines (73 loc) · 2.9 KB
/
SlackNotificationChannel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
declare(strict_types=1);
namespace EightLines\SyliusNotificationPlugin\NotificationChannel\Symfony;
use EightLines\SyliusNotificationPlugin\NotificationChannel\NotificationBody;
use EightLines\SyliusNotificationPlugin\NotificationChannel\NotificationChannelInterface;
use EightLines\SyliusNotificationPlugin\NotificationChannel\NotificationContext;
use EightLines\SyliusNotificationPlugin\NotificationChannel\NotificationRecipient;
use Symfony\Component\Notifier\Bridge\Slack\Block\SlackHeaderBlock;
use Symfony\Component\Notifier\Bridge\Slack\Block\SlackSectionBlock;
use Symfony\Component\Notifier\Bridge\Slack\SlackOptions;
use Symfony\Component\Notifier\ChatterInterface;
use Symfony\Component\Notifier\Exception\TransportExceptionInterface;
use Symfony\Component\Notifier\Message\ChatMessage;
final class SlackNotificationChannel implements NotificationChannelInterface
{
private const SLACK_TRANSPORT = 'slack';
public function __construct(
private ChatterInterface $chatter,
) {
}
/**
* @throws TransportExceptionInterface
*/
public function send(
?NotificationRecipient $recipient,
NotificationBody $body,
NotificationContext $context,
): void {
$message = $body->getMessage();
if (null === $message) {
throw new \InvalidArgumentException('The message cannot be null.');
}
$options = $this->buildSlackOptions($body, $context);
$chatMessage = new ChatMessage($message);
$chatMessage->options($options);
$chatMessage->transport(self::SLACK_TRANSPORT);
$this->chatter->send($chatMessage);
}
public static function getIdentifier(): string
{
return 'slack';
}
public static function supportsUnknownRecipient(): bool
{
return true;
}
public static function getConfigurationFormType(): ?string
{
return SlackNotificationChannelFormType::class;
}
private function buildSlackOptions(NotificationBody $body, NotificationContext $context): SlackOptions
{
$message = $body->getMessage();
$configuration = $context->getConfiguration();
if (json_validate($message)) {
$jsonMessage = json_decode($message, true);
if (true === $configuration->hasCustomValue('recipient')) {
$jsonMessage['recipient_id'] = $configuration->getCustomValue('recipient');
}
return new SlackOptions($jsonMessage);
}
$options = new SlackOptions();
if (true === $configuration->hasCustomValue('recipient')) {
$options->recipient($configuration->getCustomValue('recipient'));
}
$subject = $body->getSubject();
if (null !== $subject) {
$options->block(new SlackHeaderBlock($subject));
}
$options->block((new SlackSectionBlock())->text($message));
return $options;
}
}