Files
backupscript/src/Notification/Notification.php

79 lines
1.7 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;
2023-06-13 08:15:29 +00:00
use App\Notification\Ntfy;
2023-08-14 14:24:19 +00:00
use Psr\Log\NullLogger;
2023-06-13 08:15:29 +00:00
2023-06-12 09:30:10 +00:00
class Notification
{
/**
2023-06-13 08:15:29 +00:00
* @var NotificationInterface[] $notifiers
2023-06-12 09:30:10 +00:00
*/
2023-07-03 14:28:53 +00:00
private array $notifiers = array();
2023-06-13 08:15:29 +00:00
2023-08-14 14:24:19 +00:00
public function __construct(private NullLogger $logger = new NullLogger())
{
}
2023-06-13 08:15:29 +00:00
/**
* Load multiple configurations
*
2023-08-17 07:16:41 +00:00
* @param array<string[]> $config Array of notifier configurations.
2023-06-13 08:15:29 +00:00
*/
2023-06-12 09:30:10 +00:00
public function loadMany(array $config): void
{
2023-06-13 08:15:29 +00:00
foreach ($config as $conf) {
$this->loadSingle($conf['type'], $conf);
2023-06-12 09:30:10 +00:00
}
}
2023-06-13 08:15:29 +00:00
/**
* Load a single configuration
*
* @param string $key Notification class
* @param string[] $config Implementation specific configuration
2023-07-03 14:28:53 +00:00
* @SuppressWarnings(PHPMD)
2023-06-13 08:15:29 +00:00
*/
2023-06-12 09:30:10 +00:00
public function loadSingle(string $key, array $config): void
{
2023-06-13 08:15:29 +00:00
switch ($key) {
case 'ntfy':
case 'Ntfy':
case 'NTFY':
2023-07-03 14:28:53 +00:00
$this->addNotifier(Ntfy::factory($config));
2023-06-13 08:15:29 +00:00
break;
default:
break;
}
2023-06-12 09:30:10 +00:00
}
2023-07-03 14:28:53 +00:00
public function addNotifier(NotificationInterface $instance): void
{
$this->notifiers[] = $instance;
}
/**
* Get all active notifiers.
*
* @return NotificationInterface[] All notifiers.
*/
public function getNotifiers(): array
{
return $this->notifiers;
}
2023-06-12 09:30:10 +00:00
public function send(string $title, string $message): void
{
2023-07-03 14:28:53 +00:00
foreach ($this->getNotifiers() as $notifier) {
2023-08-14 14:24:19 +00:00
try {
$notifier->send($title, $message);
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
2023-06-12 09:30:10 +00:00
}
}
}