Files
Jens True 603c002148
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Update requirements
2025-02-07 10:32:53 +00:00

84 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Notification;
use Ntfy\Server;
use Ntfy\Message;
use Ntfy\Client;
use InvalidArgumentException;
/**
* Send a notification through a ntfy server
*/
class Ntfy implements NotificationInterface
{
public const int TOPIC_MAX_LENGTH = 256;
public const int TITLE_MAX_LENGTH = 256;
public const int MESSAGE_MAX_LENGTH = 4096;
private string $topic = 'default';
/**
* Initialize with configuration.
*
* Factory method.
*
* @param string[] $config Configuration
*/
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(private Client $client)
{
}
/**
* Set the topic of the notification message.
*
* @param string $topic Topic length between 1 and TOPIC_MAX_LENGTH characters.
*/
public function setTopic(string $topic): void
{
if (! strlen($topic) || strlen($topic) > self::TOPIC_MAX_LENGTH) {
throw new InvalidArgumentException("Invalid topic length");
}
$this->topic = $topic;
}
/**
* Return the currently set topic.
*/
public function getTopic(): string
{
return $this->topic;
}
/**
* Push a message with Ntfy
*/
public function send(string $title, string $message): void
{
if (! strlen($title) || strlen($title) > self::TITLE_MAX_LENGTH) {
throw new InvalidArgumentException("Invalid title length");
}
if (! strlen($message) || strlen($message) > self::MESSAGE_MAX_LENGTH) {
throw new InvalidArgumentException("Invalid message length");
}
$msg = new Message();
$msg->topic($this->getTopic());
$msg->title($title);
$msg->body($message);
$this->client->send($msg);
}
}