-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscription.php
More file actions
101 lines (88 loc) · 2.77 KB
/
Subscription.php
File metadata and controls
101 lines (88 loc) · 2.77 KB
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
98
99
100
101
<?php
declare(strict_types=1);
namespace Keboola\NotificationClient\Responses;
use Keboola\NotificationClient\Exception\ClientException;
use Keboola\NotificationClient\Responses\Recipient\EmailRecipient;
use Keboola\NotificationClient\Responses\Recipient\RecipientInterface;
use Keboola\NotificationClient\Responses\Recipient\WebhookRecipient;
use Throwable;
class Subscription
{
private string $id;
private string $event;
/** @var array<Filter> */
private array $filters;
private RecipientInterface $recipient;
public function __construct(array $data)
{
try {
$this->id = $data['id'];
$this->event = $data['event'];
$this->filters = array_values(array_map(
fn(array $item) => new Filter($item),
$data['filters'],
));
$this->recipient = self::createRecipient($data['recipient']);
} catch (Throwable $e) {
throw new ClientException('Unrecognized response: ' . $e->getMessage(), 0, $e);
}
}
/**
* @param array<string, mixed> $data
*/
private static function createRecipient(array $data): RecipientInterface
{
$channel = self::extractString($data, 'channel');
switch ($channel) {
case EmailRecipient::CHANNEL:
return new EmailRecipient(self::extractString($data, 'address'));
case WebhookRecipient::CHANNEL:
return new WebhookRecipient(self::extractString($data, 'url'));
default:
throw new ClientException(sprintf('Unknown recipient channel "%s"', $channel));
}
}
/**
* @param array<string, mixed> $data
*/
private static function extractString(array $data, string $key): string
{
if (!array_key_exists($key, $data) || !is_string($data[$key])) {
throw new ClientException(sprintf('Recipient field "%s" must be a string', $key));
}
return $data[$key];
}
public function getId(): string
{
return $this->id;
}
public function getEvent(): string
{
return $this->event;
}
/**
* @return array<Filter>
*/
public function getFilters(): array
{
return $this->filters;
}
public function getRecipient(): RecipientInterface
{
return $this->recipient;
}
public function getRecipientChannel(): string
{
return $this->recipient->getChannel();
}
/**
* BC: previously `: string`. Now `: ?string`. Returns null for non-email channels (e.g. webhook).
*/
public function getRecipientAddress(): ?string
{
if ($this->recipient instanceof EmailRecipient) {
return $this->recipient->getAddress();
}
return null;
}
}