From 72c50d4cb5d7418f75bac4a6c521885f97d21717 Mon Sep 17 00:00:00 2001 From: fadrian06 Date: Thu, 1 Feb 2024 19:34:27 -0400 Subject: [PATCH] Throws an E_USER_NOTICE for invalid filter type --- flight/core/Dispatcher.php | 17 +++++++++++++---- tests/DispatcherTest.php | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/flight/core/Dispatcher.php b/flight/core/Dispatcher.php index 3be1de0..f7d2a8a 100644 --- a/flight/core/Dispatcher.php +++ b/flight/core/Dispatcher.php @@ -21,6 +21,7 @@ class Dispatcher { public const FILTER_BEFORE = 'before'; public const FILTER_AFTER = 'after'; + private const FILTER_TYPES = [self::FILTER_BEFORE, self::FILTER_AFTER]; /** @var array Mapped events. */ protected array $events = []; @@ -121,13 +122,15 @@ class Dispatcher */ public function clear(?string $name = null): void { - if (null !== $name) { + if ($name !== null) { unset($this->events[$name]); unset($this->filters[$name]); - } else { - $this->events = []; - $this->filters = []; + + return; } + + $this->events = []; + $this->filters = []; } /** @@ -141,6 +144,12 @@ class Dispatcher */ public function hook(string $name, string $type, callable $callback): self { + if (!in_array($type, self::FILTER_TYPES, true)) { + $noticeMessage = "Invalid filter type '$type', use " . join('|', self::FILTER_TYPES); + + trigger_error($noticeMessage, E_USER_NOTICE); + } + $this->filters[$name][$type][] = $callback; return $this; diff --git a/tests/DispatcherTest.php b/tests/DispatcherTest.php index 1d754bf..0be7235 100644 --- a/tests/DispatcherTest.php +++ b/tests/DispatcherTest.php @@ -175,6 +175,25 @@ class DispatcherTest extends TestCase restore_error_handler(); } + public function testItThrowsNoticeForInvalidFilterTypes(): void + { + set_error_handler(function (int $errno, string $errstr): void { + $this->assertSame(E_USER_NOTICE, $errno); + $this->assertStringStartsWith("Invalid filter type 'invalid', use ", $errstr); + }); + + $this->dispatcher + ->set('myMethod', function (): string { + return 'Original'; + }) + ->hook('myMethod', 'invalid', function (array &$params, $output): void { + $output = 'Overriden'; + }); + + $this->assertSame('Original', $this->dispatcher->run('myMethod')); + restore_error_handler(); + } + public function testCallFunction4Params(): void { $myFunction = function ($param1, $param2, $param3, $param4) {