Files
backupscript/src/Notification/Notification.php
Jens True 876702473c
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
More documentation
2023-09-19 06:34:20 +00:00

87 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Notification;
use App\Notification\Ntfy;
use Psr\Log\NullLogger;
class Notification
{
/**
* @var NotificationInterface[] $notifiers
*/
private array $notifiers = array();
public function __construct(private NullLogger $logger = new NullLogger())
{
}
/**
* Load multiple configurations
*
* @param array<string[]> $config Array of notifier configurations.
*/
public function loadMany(array $config): void
{
foreach ($config as $conf) {
$this->loadSingle($conf['type'], $conf);
}
}
/**
* Load a single configuration
*
* @param string $key Notification class
* @param string[] $config Implementation specific configuration
* @SuppressWarnings(PHPMD)
*/
public function loadSingle(string $key, array $config): void
{
switch ($key) {
case 'ntfy':
case 'Ntfy':
case 'NTFY':
$this->addNotifier(Ntfy::factory($config));
break;
default:
break;
}
}
/**
* Add a single notifier instance.
*/
public function addNotifier(NotificationInterface $instance): void
{
$this->notifiers[] = $instance;
}
/**
* Get all active notifiers.
*
* @return NotificationInterface[] All notifiers.
*/
public function getNotifiers(): array
{
return $this->notifiers;
}
/**
* Push a notification to all notifiers.
*
* Logs an error if sending fails.
*/
public function send(string $title, string $message): void
{
foreach ($this->getNotifiers() as $notifier) {
try {
$notifier->send($title, $message);
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
}
}