From b696629bc82d791c55813367621a88436a2d99e8 Mon Sep 17 00:00:00 2001 From: Joseph Date: Mon, 29 Apr 2024 12:21:00 +0000 Subject: [PATCH] Add `Logger` class (#172) --- daemon.php | 13 +-- src/Check.php | 42 ++++++---- src/Feeds.php | 18 +++-- src/Logger.php | 99 +++++++++++++++++++++++ src/Notification/AbstractNotification.php | 14 +++- src/Notification/Gotify.php | 3 +- src/Notification/Ntfy.php | 2 +- src/Notify.php | 54 +++++++------ src/Output.php | 8 -- tests/CheckTest.php | 16 ++-- tests/FeedsTest.php | 19 +++-- tests/LoggerTest.php | 74 +++++++++++++++++ tests/Notification/GotifyTest.php | 15 +++- tests/Notification/NtfyTest.php | 19 +++-- tests/NotifyTest.php | 31 ++++--- tests/OutputTest.php | 10 --- vigilant.php | 26 +++--- 17 files changed, 345 insertions(+), 118 deletions(-) create mode 100644 src/Logger.php create mode 100644 tests/LoggerTest.php diff --git a/daemon.php b/daemon.php index c8a0b50d..926addcc 100644 --- a/daemon.php +++ b/daemon.php @@ -6,6 +6,7 @@ use Vigilant\Fetch; use Vigilant\Notify; use Vigilant\Output; +use Vigilant\Logger; use Vigilant\Version; use Vigilant\Exception\ConfigException; use Vigilant\Exception\AppException; @@ -19,23 +20,25 @@ $config->validate(); $fetch = new Fetch(); - $feeds = new Feeds($config); + $logger = new Logger($config->getTimezone()); + $feeds = new Feeds($config, $logger); /** @phpstan-ignore-next-line */ while (true) { foreach ($feeds->get() as $details) { - $notify = new Notify($details, $config); + $notify = new Notify($details, $config, $logger); $check = new Check( $details, + $fetch, $config, - $fetch + $logger ); if ($check->isDue() === true) { $check->check(); $notify->send($check->getMessages()); - Output::text(sprintf( + $logger->info(sprintf( 'Next check in %s seconds at %s', $details->getInterval(), $check->getNextCheckDate() @@ -46,6 +49,6 @@ sleep(30); } } catch (ConfigException | AppException $err) { - Output::text($err->getMessage()); + Output::text('[Vigilant] ' . $err->getMessage()); exit(1); } diff --git a/src/Check.php b/src/Check.php index 08fb642e..0752b4b8 100644 --- a/src/Check.php +++ b/src/Check.php @@ -9,14 +9,17 @@ final class Check { - /** @var Config */ - private Config $config; + /** @var Feed\Details $details Feed details (name, url, interval and hash) */ + private Feed\Details $details; - /** @var Fetch */ + /** @var Fetch Fetch class instance */ private Fetch $fetch; - /** @var Feed\Details $details Feed details (name, url, interval and hash) */ - private Feed\Details $details; + /** @var Config Config class instance */ + private Config $config; + + /** @var Logger Logger class instance */ + private Logger $logger; /** @var Cache $cache Cache class instance */ private Cache $cache; @@ -29,14 +32,16 @@ final class Check /** * @param Feed\Details $details Feed details - * @param Config $config Script config + * @param Config $config Config class instance * @param Fetch $fetch Fetch class instance + * @param Logger $logger Logger class instance */ - public function __construct(Feed\Details $details, Config $config, Fetch $fetch) + public function __construct(Feed\Details $details, Fetch $fetch, Config $config, Logger $logger) { $this->details = $details; - $this->config = $config; $this->fetch = $fetch; + $this->config = $config; + $this->logger = $logger; $this->cache = new Cache( $this->config->getCachePath(), @@ -78,14 +83,18 @@ public function getNextCheckDate(): string public function check(): void { try { - Output::text('Checking...' . $this->details->getName() . ' (' . $this->details->getUrl() . ')'); + $this->logger->info(sprintf( + 'Checking...%s (%s)', + $this->details->getName(), + $this->details->getUrl() + )); $result = $this->fetch->get($this->details->getUrl()); $this->process($result); $this->cache->resetErrorCount(); } catch (FetchException $err) { - Output::text($err->getMessage()); + $this->logger->error($err->getMessage()); $this->cache->increaseErrorCount(); @@ -129,24 +138,27 @@ private function process(\FeedIo\Reader\Result $result): void if (in_array($hash, $this->cache->getItems()) === false) { $newItems += 1; - Output::text('Found...' . html_entity_decode($item->getTitle()) . ' (' . $hash . ')'); + $title = html_entity_decode($item->getTitle()); + $body = strip_tags(html_entity_decode($item->getContent())); + + $this->logger->info(sprintf('Found...%s (%s)', $title, $hash)); if ($this->cache->isFirstCheck() === false) { $this->messages[] = new Message( - title: html_entity_decode($item->getTitle()), - body: strip_tags(html_entity_decode($item->getContent())), + title: $title, + body: $body, url: $item->getLink() ); } } } - Output::text('Found ' . $newItems . ' new item(s).'); + $this->logger->info(sprintf('Found %s new item(s).', $newItems)); $this->cache->updateItems($itemHashes); if ($newItems > 0 && $this->cache->isFirstCheck() === true) { - Output::text('First feed check, not sending notifications for found items.'); + $this->logger->info('First feed check, not sending notifications for found items.'); } } } diff --git a/src/Feeds.php b/src/Feeds.php index 4fbba40e..15a8a0ad 100644 --- a/src/Feeds.php +++ b/src/Feeds.php @@ -2,7 +2,6 @@ namespace Vigilant; -use Vigilant\Check; use Vigilant\Feed\Feed; use Vigilant\Feed\Details; use Vigilant\Exception\AppException; @@ -17,19 +16,24 @@ final class Feeds */ private Config $config; + /** + * @var Logger + */ + private Logger $logger; + /** * @var array $feeds Feed classes for each feeds.yaml entry */ private array $feeds = []; /** - * Constructor - * - * @param Config $config Feeds filepath + * @param Config $config Config class instance + * @param Logger $logger Logger class instance */ - public function __construct(Config $config) + public function __construct(Config $config, Logger $logger) { $this->config = $config; + $this->logger = $logger; try { $feeds = $this->load($this->config->getFeedsPath()); @@ -60,7 +64,7 @@ public function get(): array private function load(string $path): array { try { - Output::text('Loading feeds.yaml (' . $path . ')'); + $this->logger->debug(sprintf('Loading feeds.yaml (%s)', $path)); return Yaml::parseFile($path); } catch (ParseException $err) { @@ -76,7 +80,7 @@ private function load(string $path): array */ private function validate(array $feeds): void { - Output::text('Validating feeds.yaml'); + $this->logger->debug('Validating feeds.yaml'); if (array_key_exists('feeds', $feeds) === false || is_array($feeds['feeds']) === false) { throw new FeedsException('No feeds in feeds.yaml'); diff --git a/src/Logger.php b/src/Logger.php new file mode 100644 index 00000000..5da2a3e7 --- /dev/null +++ b/src/Logger.php @@ -0,0 +1,99 @@ +setLevel($level); + $this->timezone = new DateTimeZone($timezone); + } + + /** + * Display text in terminal + * + * @param string $text Text string to display + */ + public function info(string $text): void + { + $this->log($text); + } + + /** + * Display error text in terminal + * + * @param string $text Text string to display + */ + public function error(string $text): void + { + $this->log($text); + } + + /** + * Display text in terminal when debugging is enabled + * + * @param string $text Text string to display + */ + public function debug(string $text): void + { + if ($this->logLevel === 2) { + $this->log($text); + } + } + + /** + * Display text in terminal + * + * @param string $text Text string to display + */ + private function log(string $text): void + { + $date = new DateTime('now', $this->timezone); + + echo sprintf( + '[%s] %s %s', + $date->format('Y-m-d h:i:s P'), + $text, + PHP_EOL + ); + } + + /** + * Set logging level + * + * - `1` - Normal + * - `2` - Verbose + * + * @param int $level Logging level + */ + private function setLevel(int $level): void + { + if ($level < 1) { + $this->logLevel = 1; + } elseif ($level > 2) { + $this->logLevel = 2; + } else { + $this->logLevel = $level; + } + } +} diff --git a/src/Notification/AbstractNotification.php b/src/Notification/AbstractNotification.php index a3674abe..03c1a0ff 100644 --- a/src/Notification/AbstractNotification.php +++ b/src/Notification/AbstractNotification.php @@ -2,19 +2,25 @@ namespace Vigilant\Notification; +use Vigilant\Logger; + abstract class AbstractNotification { - /** - * @var array $config Notification config - */ + /** @var array $config Notification config */ protected array $config = []; + /** @var Logger Logger class instance */ + protected Logger $logger; + /** * @param array $config Notification config + * @param Logger $logger Logger class instance */ - public function __construct(array $config) + public function __construct(array $config, Logger $logger) { $this->config = $config; + $this->logger = $logger; + $this->setup(); } diff --git a/src/Notification/Gotify.php b/src/Notification/Gotify.php index ac0eb049..289583e6 100644 --- a/src/Notification/Gotify.php +++ b/src/Notification/Gotify.php @@ -2,7 +2,6 @@ namespace Vigilant\Notification; -use Vigilant\Output; use Vigilant\Notification\AbstractNotification; use Vigilant\Exception\NotificationException; use Gotify\Server; @@ -35,7 +34,7 @@ public function send(string $title, string $body, string $url = ''): void ] ); - Output::text('Sent notification using Gotify'); + $this->logger->info('Sent notification using Gotify'); } catch (EndpointException | GotifyException $err) { throw new NotificationException('[Gotify] ' . $err->getMessage()); } diff --git a/src/Notification/Ntfy.php b/src/Notification/Ntfy.php index c44c8ada..faa588e2 100644 --- a/src/Notification/Ntfy.php +++ b/src/Notification/Ntfy.php @@ -37,7 +37,7 @@ public function send(string $title, string $body, string $url = ''): void $this->client->send($message); - Output::text('Sent notification using Ntfy'); + $this->logger->info('Sent notification using Ntfy'); } catch (EndpointException | NtfyException $err) { throw new NotificationException('[Ntfy] ' . $err->getMessage()); } diff --git a/src/Notify.php b/src/Notify.php index bc7224fc..d9514806 100644 --- a/src/Notify.php +++ b/src/Notify.php @@ -11,18 +11,28 @@ class Notify { private AbstractNotification $service; + /** @var Config Config class instance */ + private Config $config; + + /** @var Logger Logger class instance */ + private Logger $logger; + /** * Create and config Notification class * * @param Feed\Details $details Feed details - * @param Config $config Script config + * @param Config $config Config class instance + * @param Logger $logger Logger class instance */ - public function __construct(Feed\Details $details, Config $config) + public function __construct(Feed\Details $details, Config $config, Logger $logger) { + $this->config = $config; + $this->logger = $logger; + if ($config->getNotificationService() === 'gotify') { - $this->service = $this->createGotify($details, $config); + $this->service = $this->createGotify($details); } else { - $this->service = $this->createNtfy($details, $config); + $this->service = $this->createNtfy($details); } } @@ -40,7 +50,7 @@ public function send(array $messages): void $message->getUrl() ); } catch (NotificationException $err) { - Output::text($err->getMessage()); + $this->logger->error($err->getMessage()); } } } @@ -49,14 +59,13 @@ public function send(array $messages): void * Create and config Gotify instance * * @param Feed\Details $details Feed details - * @param Config $config Script config */ - private function createGotify(Feed\Details $details, Config $config): Gotify + private function createGotify(Feed\Details $details): Gotify { $gotifyConfig = [ - 'server' => $config->getGotifyUrl(), - 'priority' => $config->getGotifyPriority(), - 'token' => $config->getGotifyToken() + 'server' => $this->config->getGotifyUrl(), + 'priority' => $this->config->getGotifyPriority(), + 'token' => $this->config->getGotifyToken() ]; if ($details->hasGotifyPriority() === true) { @@ -67,31 +76,30 @@ private function createGotify(Feed\Details $details, Config $config): Gotify $gotifyConfig['token'] = $details->getGotifyToken(); } - return new Gotify($gotifyConfig); + return new Gotify($gotifyConfig, $this->logger); } /** * Create and config ntfy instance * * @param Feed\Details $details Feed details - * @param Config $config Script config */ - private function createNtfy(Feed\Details $details, Config $config): Ntfy + private function createNtfy(Feed\Details $details): Ntfy { $ntfyConfig = [ - 'server' => $config->getNtfyUrl(), - 'topic' => $config->getNtfyTopic(), - 'priority' => $config->getNtfyPriority(), + 'server' => $this->config->getNtfyUrl(), + 'topic' => $this->config->getNtfyTopic(), + 'priority' => $this->config->getNtfyPriority(), 'auth' => [ - 'method' => $config->getNtfyAuthMethod() + 'method' => $this->config->getNtfyAuthMethod() ] ]; - if ($config->getNtfyAuthMethod() === 'password') { - $ntfyConfig['auth']['username'] = $config->getNtfyUsername(); - $ntfyConfig['auth']['password'] = $config->getNtfyPassword(); - } elseif ($config->getNtfyAuthMethod() === 'token') { - $ntfyConfig['auth']['token'] = $config->getNtfyToken(); + if ($this->config->getNtfyAuthMethod() === 'password') { + $ntfyConfig['auth']['username'] = $this->config->getNtfyUsername(); + $ntfyConfig['auth']['password'] = $this->config->getNtfyPassword(); + } elseif ($this->config->getNtfyAuthMethod() === 'token') { + $ntfyConfig['auth']['token'] = $this->config->getNtfyToken(); } if ($details->hasNtfyToken() === true) { @@ -109,6 +117,6 @@ private function createNtfy(Feed\Details $details, Config $config): Ntfy $ntfyConfig['priority'] = $details->getNtfyPriority(); } - return new Ntfy($ntfyConfig); + return new Ntfy($ntfyConfig, $this->logger); } } diff --git a/src/Output.php b/src/Output.php index e7545565..58d51762 100644 --- a/src/Output.php +++ b/src/Output.php @@ -13,12 +13,4 @@ public static function text(string $text = ''): void { echo $text . "\n"; } - - /** - * Output system newline character in terminal - */ - public static function newline(): void - { - echo PHP_EOL; - } } diff --git a/tests/CheckTest.php b/tests/CheckTest.php index 41a3052c..e043d0dc 100644 --- a/tests/CheckTest.php +++ b/tests/CheckTest.php @@ -6,12 +6,14 @@ use Vigilant\Check; use Vigilant\Feed\Details; use Vigilant\Config; +use Vigilant\Logger; use Vigilant\Fetch; #[CoversClass(Check::class)] #[UsesClass(Details::class)] #[UsesClass(Fetch::class)] #[UsesClass(Config::class)] +#[UsesClass(Logger::class)] #[UsesClass(Vigilant\Cache::class)] #[UsesClass(Vigilant\Output::class)] #[UsesClass(Vigilant\Message::class)] @@ -20,6 +22,7 @@ class CheckTest extends TestCase { private static Config $config; + private static Logger $logger; /** @var array $feed */ private array $feed = [ @@ -46,6 +49,8 @@ public static function setUpBeforeClass(): void $config->method('getCachePath')->willReturn(mockfs::getUrl('/')); $config->method('getTimezone')->willReturn('UTC'); self::$config = $config; + + self::$logger = new Logger('UTC'); } public function setup(): void @@ -59,7 +64,7 @@ public function setup(): void public function testIsDue(): void { $details = new Details($this->feed); - $check = new check($details, self::$config, new Fetch()); + $check = new check($details, new Fetch(), self::$config, self::$logger); $this->assertIsBool($check->isDue()); } @@ -69,7 +74,7 @@ public function testIsDue(): void public function testGetNextCheckDate(): void { $details = new Details($this->feed); - $check = new check($details, self::$config, new Fetch()); + $check = new check($details, new Fetch(), self::$config, self::$logger); $this->assertEquals('1970-01-01 00:00:00', $check->getNextCheckDate()); } @@ -88,7 +93,7 @@ public function testCheckFirstTime(): void ])); $details = new Details($this->feed); - $check = new check($details, self::$config, $fetch); + $check = new check($details, $fetch, self::$config, self::$logger); $this->expectOutputRegex('/First feed check, not sending notifications for found items/'); @@ -113,7 +118,8 @@ public function testCheckWithCache(): void ])); $details = new Details($this->feed); - $check = new check($details, self::$config, $fetch); + $check = new check($details, $fetch, self::$config, self::$logger); + $check = new check($details, $fetch, self::$config, self::$logger); $this->expectOutputRegex('/Found 1 new item\(s\)/'); @@ -143,7 +149,7 @@ public function testCheckFetchErrorMessage(): void 'handler' => GuzzleHttp\HandlerStack::create($mock) ])); $details = new Details($this->feed); - $check = new check($details, self::$config, $fetch); + $check = new check($details, $fetch, self::$config, self::$logger); $this->expectOutputRegex('/Failed to fetch/'); diff --git a/tests/FeedsTest.php b/tests/FeedsTest.php index 95c16196..3975b1c6 100644 --- a/tests/FeedsTest.php +++ b/tests/FeedsTest.php @@ -4,10 +4,12 @@ use PHPUnit\Framework\Attributes\UsesClass; use Vigilant\Feeds; use Vigilant\Config; +use Vigilant\Logger; use Vigilant\Exception\AppException; #[CoversClass(Feeds::class)] #[UsesClass(Config::class)] +#[UsesClass(Logger::class)] #[UsesClass(AppException::class)] #[UsesClass(Vigilant\Output::class)] #[UsesClass(Vigilant\Feed\Feed::class)] @@ -16,18 +18,23 @@ #[UsesClass(Vigilant\Exception\FeedsException::class)] class FeedsTest extends TestCase { + private static Logger $logger; + + public static function setUpBeforeClass(): void + { + self::$logger = new Logger('UTC'); + } + /** * Test get() */ public function testGet(): void { - $this->expectOutputRegex('/Loading feeds.yaml/'); - /** @var PHPUnit\Framework\MockObject\Stub&Config */ $config = $this->createStub(Config::class); $config->method('getFeedsPath')->willReturn(self::getSamplePath('feeds.yaml')); - $feeds = new Feeds($config); + $feeds = new Feeds($config, self::$logger); $this->assertIsArray($feeds->get()); $this->assertContainsOnlyInstancesOf('Vigilant\Feed\Details', $feeds->get()); @@ -44,9 +51,8 @@ public function testNoFeedsException(): void $this->expectException(AppException::class); $this->expectExceptionMessage('No feeds in feeds.yaml'); - $this->expectOutputRegex('/Loading feeds.yaml/'); - new Feeds($config); + new Feeds($config, self::$logger); } /** @@ -60,8 +66,7 @@ public function testInvalidYamlFile(): void $this->expectException(AppException::class); $this->expectExceptionMessage('A colon cannot be used in an unquoted mapping value'); - $this->expectOutputRegex('/Loading feeds.yaml/'); - new Feeds($config); + new Feeds($config, self::$logger); } } diff --git a/tests/LoggerTest.php b/tests/LoggerTest.php new file mode 100644 index 00000000..5dca3a0d --- /dev/null +++ b/tests/LoggerTest.php @@ -0,0 +1,74 @@ +format('Y-m-d h:i:s P'); + + $this->expectOutputString(sprintf( + '[%s] %s %s', + $date, + 'Hello', + PHP_EOL + )); + + $logger = new Logger('UTC', 1); + $logger->info('Hello'); + } + + /** + * Test `error()` + */ + public function testError(): void + { + $this->expectOutputRegex('/Hello/'); + + $logger = new Logger('UTC', 1); + $logger->error('Hello'); + } + + /** + * Test `debug()` + */ + public function testDebug(): void + { + $this->expectOutputRegex('/Hello/'); + + $logger = new Logger('UTC', 2); + $logger->debug('Hello'); + } + + /** + * Test setting log level too low + */ + public function testLogLevelTooLow(): void + { + $logger = new Logger('UTC', -1); + + $reflection = new \ReflectionClass($logger); + $actual = $reflection->getProperty('logLevel')->getValue($logger); + + $this->assertEquals(1, $actual); + } + + /** + * Test setting log level too hight + */ + public function testLogLevelTooHigh(): void + { + $logger = new Logger('UTC', 3); + + $reflection = new \ReflectionClass($logger); + $actual = $reflection->getProperty('logLevel')->getValue($logger); + + $this->assertEquals(2, $actual); + } +} diff --git a/tests/Notification/GotifyTest.php b/tests/Notification/GotifyTest.php index ba9efde4..b5c5d48a 100644 --- a/tests/Notification/GotifyTest.php +++ b/tests/Notification/GotifyTest.php @@ -3,15 +3,19 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\Attributes\DoesNotPerformAssertions; +use Vigilant\Logger; use Vigilant\Notification\Gotify; use Vigilant\Exception\NotificationException; #[CoversClass(Gotify::class)] +#[UsesClass(Logger::class)] #[CoversClass(Vigilant\Notification\AbstractNotification::class)] #[UsesClass(NotificationException::class)] #[UsesClass(Vigilant\Output::class)] class GotifyTest extends TestCase { + private static Logger $logger; + /** @var array $config */ private array $config = [ 'server' => 'https://gotify.example.invalid', @@ -19,13 +23,18 @@ class GotifyTest extends TestCase 'priority' => 0, ]; + public static function setUpBeforeClass(): void + { + self::$logger = new Logger('UTC'); + } + /** * Test `setup()` */ #[DoesNotPerformAssertions] public function testSetup(): void { - new Gotify($this->config); + new Gotify($this->config, self::$logger); } /** @@ -36,7 +45,7 @@ public function testSend(): void $client = self::createStub(\Gotify\Endpoint\Message::class); $client->method('create')->willReturn(new stdClass()); - $gotify = new Gotify($this->config); + $gotify = new Gotify($this->config, self::$logger); $reflection = new ReflectionClass($gotify); $property = $reflection->getProperty('message'); @@ -53,7 +62,7 @@ public function testSendNotificationException(): void $this->expectException(NotificationException::class); $this->expectExceptionMessage('[Notification error] [Gotify]'); - $gotify = new Gotify($this->config); + $gotify = new Gotify($this->config, self::$logger); $gotify->send('Hello World', 'Hello from phpunit'); } } diff --git a/tests/Notification/NtfyTest.php b/tests/Notification/NtfyTest.php index 28bc9033..4eeceda1 100644 --- a/tests/Notification/NtfyTest.php +++ b/tests/Notification/NtfyTest.php @@ -3,15 +3,19 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\UsesClass; use PHPUnit\Framework\Attributes\DoesNotPerformAssertions; +use Vigilant\Logger; use Vigilant\Notification\Ntfy; use Vigilant\Exception\NotificationException; #[CoversClass(Ntfy::class)] +#[UsesClass(Logger::class)] #[CoversClass(Vigilant\Notification\AbstractNotification::class)] #[UsesClass(NotificationException::class)] #[UsesClass(Vigilant\Output::class)] class NtfyTest extends TestCase { + private static Logger $logger; + /** @var array $config */ private array $config = [ 'server' => 'https://ntfy.example.invalid', @@ -22,13 +26,18 @@ class NtfyTest extends TestCase ] ]; + public static function setUpBeforeClass(): void + { + self::$logger = new Logger('UTC'); + } + /** * Test `setup()` with no auth */ #[DoesNotPerformAssertions] public function testSetupWithNoAuth(): void { - new Ntfy($this->config); + new Ntfy($this->config, self::$logger); } /** @@ -41,7 +50,7 @@ public function testSetupWithPasswordAuth(): void $config['auth']['method'] = 'password'; $config['auth']['username'] = 'bob'; $config['auth']['password'] = 'qwerty'; - new Ntfy($config); + new Ntfy($config, self::$logger); } /** @@ -53,7 +62,7 @@ public function testSetupWithTokenAuth(): void $config = $this->config; $config['auth']['method'] = 'token'; $config['auth']['token'] = 'qwerty'; - new Ntfy($config); + new Ntfy($config, self::$logger); } /** @@ -64,7 +73,7 @@ public function testSend(): void $client = self::createStub(\Ntfy\Client::class); $client->method('send')->willReturn(new stdClass()); - $ntfy = new Ntfy($this->config); + $ntfy = new Ntfy($this->config, self::$logger); $reflection = new ReflectionClass($ntfy); $property = $reflection->getProperty('client'); @@ -81,7 +90,7 @@ public function testSendNotificationException(): void $this->expectException(NotificationException::class); $this->expectExceptionMessage('[Notification error] [Ntfy]'); - $ntfy = new Ntfy($this->config); + $ntfy = new Ntfy($this->config, self::$logger); $ntfy->send('Hello World', 'Hello from phpunit'); } } diff --git a/tests/NotifyTest.php b/tests/NotifyTest.php index d02f61fd..6d3a4ce2 100644 --- a/tests/NotifyTest.php +++ b/tests/NotifyTest.php @@ -6,6 +6,7 @@ use Vigilant\Feed\Details; use Vigilant\Config; use Vigilant\Message; +use Vigilant\Logger; use Vigilant\Notification\Gotify; use Vigilant\Notification\Ntfy; @@ -13,6 +14,7 @@ #[UsesClass(Details::class)] #[UsesClass(Config::class)] #[UsesClass(Message::class)] +#[UsesClass(Logger::class)] #[UsesClass(Gotify::class)] #[UsesClass(Ntfy::class)] #[UsesClass(Vigilant\Output::class)] @@ -20,6 +22,8 @@ #[UsesClass(Vigilant\Exception\NotificationException::class)] class NotifyTest extends TestCase { + private static Logger $logger; + /** @var array $feed */ private array $feed = [ 'name' => 'GitHub status', @@ -27,6 +31,11 @@ class NotifyTest extends TestCase 'interval' => 900 ]; + public static function setUpBeforeClass(): void + { + self::$logger = new Logger('UTC'); + } + public function testSend(): void { $this->expectOutputRegex('/Sent notification using Ntfy/'); @@ -42,7 +51,7 @@ public function testSend(): void new Message('Hello World', 'Hello??') ]; - $notify = new notify(new Details($this->feed), $config); + $notify = new notify(new Details($this->feed), $config, self::$logger); $notify->send($messages); } @@ -61,7 +70,7 @@ public function testSendWithNotificationError(): void new Message('Hello World', 'Hello??') ]; - $notify = new notify(new Details($this->feed), $config); + $notify = new notify(new Details($this->feed), $config, self::$logger); $notify->send($messages); } @@ -79,7 +88,7 @@ public function testCreatingGotify(): void $config->method('getGotifyPriority')->willReturn(0); $config->method('getGotifyToken')->willReturn('fake-token'); - $notify = new notify(new Details($this->feed), $config); + new notify(new Details($this->feed), $config, self::$logger); } /** @@ -99,7 +108,7 @@ public function testCreatingGotifyWithPriorityFromFeedDetails(): void $feed = $this->feed; $feed['gotify_priority'] = 5; - $notify = new notify(new Details($feed), $config); + new notify(new Details($feed), $config, self::$logger); } /** @@ -119,7 +128,7 @@ public function testCreatingGotifyWithTokenFromFeedDetails(): void $feed = $this->feed; $feed['gotify_token'] = 'qwerty'; - $notify = new notify(new Details($feed), $config); + new notify(new Details($feed), $config, self::$logger); } /** @@ -135,7 +144,7 @@ public function testCreatingNtfy(): void $config->method('getNtfyUrl')->willReturn('https://ntfy.example.com/'); $config->method('getNtfyPriority')->willReturn(0); - $notify = new notify(new Details($this->feed), $config); + new notify(new Details($this->feed), $config, self::$logger); } /** @@ -154,7 +163,7 @@ public function testCreatingNtfyWithPasswordAuth(): void $config->method('getNtfyUsername')->willReturn('bob'); $config->method('getNtfyPassword')->willReturn('qwerty'); - $notify = new notify(new Details($this->feed), $config); + new notify(new Details($this->feed), $config, self::$logger); } /** @@ -172,7 +181,7 @@ public function testCreatingNtfyWithTokenAuth(): void $config->method('getNtfyToken')->willReturn('fake-token'); $config->method('getNtfyAuthMethod')->willReturn('token'); - $notify = new notify(new Details($this->feed), $config); + new notify(new Details($this->feed), $config, self::$logger); } /** @@ -191,7 +200,7 @@ public function testCreatingNtfyWithTokenFromFeedDetails(): void $feed = $this->feed; $feed['ntfy_token'] = 'qwerty'; - $notify = new notify(new Details($feed), $config); + new notify(new Details($feed), $config, self::$logger); } /** @@ -210,7 +219,7 @@ public function testCreatingNtfyWithTopicFromFeedDetails(): void $feed = $this->feed; $feed['ntfy_topic'] = 'qwerty'; - $notify = new notify(new Details($feed), $config); + new notify(new Details($feed), $config, self::$logger); } /** @@ -229,6 +238,6 @@ public function testCreatingNtfyWithPriorityFromFeedDetails(): void $feed = $this->feed; $feed['ntfy_priority'] = 5; - $notify = new notify(new Details($feed), $config); + new notify(new Details($feed), $config, self::$logger); } } diff --git a/tests/OutputTest.php b/tests/OutputTest.php index d7767413..44a62a30 100644 --- a/tests/OutputTest.php +++ b/tests/OutputTest.php @@ -20,14 +20,4 @@ public function testOutput(): void Output::text($this->text); } - - /** - * Test newline() - */ - public function testNewline(): void - { - $this->expectOutputString(PHP_EOL); - - Output::newline(); - } } diff --git a/vigilant.php b/vigilant.php index 67d24cb4..af697b0d 100644 --- a/vigilant.php +++ b/vigilant.php @@ -6,6 +6,7 @@ use Vigilant\Fetch; use Vigilant\Notify; use Vigilant\Output; +use Vigilant\Logger; use Vigilant\Version; use Vigilant\Exception\ConfigException; use Vigilant\Exception\AppException; @@ -13,33 +14,34 @@ require('vendor/autoload.php'); try { - Output::text(sprintf('Vigilant version %s', Version::get())); - $config = new Config(); $config->validate(); + $logger = new Logger($config->getTimezone()); + $logger->debug(sprintf('Vigilant version %s', Version::get())); + $fetch = new Fetch(); - $feeds = new Feeds($config); - Output::newline(); + $feeds = new Feeds($config, $logger); foreach ($feeds->get() as $details) { - $notify = new Notify($details, $config); + $notify = new Notify($details, $config, $logger); $check = new Check( $details, + $fetch, $config, - $fetch + $logger ); if ($check->isDue() === true) { $check->check(); $notify->send($check->getMessages()); - } - Output::text(sprintf( - 'Next check in %s seconds at %s', - $details->getInterval(), - $check->getNextCheckDate() - )); + $logger->info(sprintf( + 'Next check in %s seconds at %s', + $details->getInterval(), + $check->getNextCheckDate() + )); + } } } catch (ConfigException | AppException $err) { Output::text($err->getMessage());