Files

84 lines
2.0 KiB
PHP
Raw Normal View History

2023-06-12 09:30:10 +00:00
<?php
declare(strict_types=1);
2023-06-12 09:30:10 +00:00
namespace App\Notification;
use Ntfy\Server;
use Ntfy\Message;
use Ntfy\Client;
2023-07-03 13:01:31 +00:00
use InvalidArgumentException;
2023-06-12 09:30:10 +00:00
2023-09-19 06:34:20 +00:00
/**
* Send a notification through a ntfy server
*/
2023-06-12 09:30:10 +00:00
class Ntfy implements NotificationInterface
{
2025-02-07 10:32:53 +00:00
public const int TOPIC_MAX_LENGTH = 256;
public const int TITLE_MAX_LENGTH = 256;
public const int MESSAGE_MAX_LENGTH = 4096;
2023-06-15 14:10:17 +00:00
private string $topic = 'default';
2023-08-17 07:16:41 +00:00
2023-06-13 08:15:29 +00:00
/**
* Initialize with configuration.
*
2023-09-19 06:34:20 +00:00
* Factory method.
*
2023-06-13 08:15:29 +00:00
* @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;
}
2023-08-15 11:43:12 +00:00
public function __construct(private Client $client)
2023-06-12 09:30:10 +00:00
{
2023-06-15 14:10:17 +00:00
}
2023-06-12 09:30:10 +00:00
2023-09-19 06:34:20 +00:00
/**
* Set the topic of the notification message.
*
2023-11-03 12:02:44 +00:00
* @param string $topic Topic length between 1 and TOPIC_MAX_LENGTH characters.
2023-09-19 06:34:20 +00:00
*/
2023-06-15 14:10:17 +00:00
public function setTopic(string $topic): void
{
2024-02-07 11:00:08 +00:00
if (! strlen($topic) || strlen($topic) > self::TOPIC_MAX_LENGTH) {
2023-07-03 13:01:31 +00:00
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-09-19 06:34:20 +00:00
/**
* Return the currently set topic.
*/
2023-07-03 13:01:31 +00:00
public function getTopic(): string
{
return $this->topic;
}
2023-08-17 07:16:41 +00:00
/**
* Push a message with Ntfy
*/
2023-06-12 09:30:10 +00:00
public function send(string $title, string $message): void
{
2024-02-07 11:00:08 +00:00
if (! strlen($title) || strlen($title) > self::TITLE_MAX_LENGTH) {
2023-07-03 13:01:31 +00:00
throw new InvalidArgumentException("Invalid title length");
}
2024-02-07 11:00:08 +00:00
if (! strlen($message) || strlen($message) > self::MESSAGE_MAX_LENGTH) {
2023-07-03 13:01:31 +00:00
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);
}
}