79 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			79 lines
		
	
	
		
			1.7 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;
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
    public function addNotifier(NotificationInterface $instance): void
 | 
						|
    {
 | 
						|
        $this->notifiers[] = $instance;
 | 
						|
    }
 | 
						|
 | 
						|
    /**
 | 
						|
     * Get all active notifiers.
 | 
						|
     *
 | 
						|
     * @return NotificationInterface[] All notifiers.
 | 
						|
     */
 | 
						|
    public function getNotifiers(): array
 | 
						|
    {
 | 
						|
        return $this->notifiers;
 | 
						|
    }
 | 
						|
 | 
						|
    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());
 | 
						|
            }
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 |