Files

65 lines
1.5 KiB
PHP
Raw Normal View History

2023-06-12 09:30:10 +00:00
<?php
namespace App\Notification;
use Ntfy\Server;
use Ntfy\Message;
use Ntfy\Client;
2023-07-03 13:01:31 +00:00
use Exception;
use InvalidArgumentException;
2023-06-12 09:30:10 +00:00
class Ntfy implements NotificationInterface
{
2023-06-13 08:15:29 +00:00
private Client $client;
2023-06-15 14:10:17 +00:00
private string $topic = 'default';
2023-06-13 08:15:29 +00:00
/**
* Initialize with configuration.
*
* @param string[] $config Configuration
*/
2023-06-15 14:10:17 +00:00
public static function factory(array $config): self
{
$instance = new self(new Client(new Server($config['domain'])));
if (isset($config['topic'])) {
$instance->setTopic($config['topic']);
}
return $instance;
}
public function __construct(Client $client)
2023-06-12 09:30:10 +00:00
{
2023-06-15 14:10:17 +00:00
$this->client = $client;
}
2023-06-12 09:30:10 +00:00
2023-06-15 14:10:17 +00:00
public function setTopic(string $topic): void
{
2023-07-03 13:01:31 +00:00
if (strlen($topic) < 1 || strlen($topic) >= 256) {
throw new InvalidArgumentException("Invalid topic length");
}
2023-06-15 14:10:17 +00:00
$this->topic = $topic;
2023-06-12 09:30:10 +00:00
}
2023-07-03 13:01:31 +00:00
public function getTopic(): string
{
return $this->topic;
}
2023-06-12 09:30:10 +00:00
public function send(string $title, string $message): void
{
2023-07-03 13:01:31 +00:00
if (strlen($title) < 1 || strlen($title) >= 256) {
throw new InvalidArgumentException("Invalid title length");
}
if (strlen($message) < 1 || strlen($message) >= 4096) {
throw new InvalidArgumentException("Invalid message length");
}
2023-06-15 14:10:17 +00:00
2023-06-12 09:30:10 +00:00
$msg = new Message();
2023-07-03 13:01:31 +00:00
$msg->topic($this->getTopic());
2023-06-12 09:30:10 +00:00
$msg->title($title);
$msg->body($message);
$this->client->send($msg);
}
}