Chaining method definitions in Dispatcher::set()

pull/538/head
fadrian06 12 months ago
parent 28b6c99561
commit e35fc32a97

@ -69,10 +69,14 @@ class Dispatcher
* *
* @param string $name Event name * @param string $name Event name
* @param callable $callback Callback function * @param callable $callback Callback function
*
* @return $this
*/ */
public function set(string $name, callable $callback): void public function set(string $name, callable $callback): self
{ {
$this->events[$name] = $callback; $this->events[$name] = $callback;
return $this;
} }
/** /**

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace tests; namespace tests;
use Closure;
use Exception; use Exception;
use flight\core\Dispatcher; use flight\core\Dispatcher;
use tests\classes\Hello; use tests\classes\Hello;
@ -21,54 +22,49 @@ class DispatcherTest extends TestCase
// Map a closure // Map a closure
public function testClosureMapping() public function testClosureMapping()
{ {
$this->dispatcher->set('map1', function () { $closure = Closure::fromCallable(function (): string {
return 'hello'; return 'hello';
}); });
$result = $this->dispatcher->run('map1'); $this->dispatcher->set('map1', $closure);
$result = $this->dispatcher->run('map1');
self::assertEquals('hello', $result); self::assertEquals('hello', $result);
} }
// Map a function // Map a function
public function testFunctionMapping() public function testFunctionMapping()
{ {
$this->dispatcher->set('map2', function () { $this->dispatcher->set('map2', function (): string {
return 'hello'; return 'hello';
}); });
$result = $this->dispatcher->run('map2'); $result = $this->dispatcher->run('map2');
self::assertEquals('hello', $result); self::assertEquals('hello', $result);
} }
public function testHasEvent() public function testHasEvent()
{ {
$this->dispatcher->set('map-event', function () { $this->dispatcher->set('map-event', function (): void {
return 'hello';
}); });
$result = $this->dispatcher->has('map-event'); $result = $this->dispatcher->has('map-event');
$this->assertTrue($result); $this->assertTrue($result);
} }
public function testClearAllRegisteredEvents() public function testClearAllRegisteredEvents()
{ {
$this->dispatcher->set('map-event', function () { $customFunction = $anotherFunction = function (): void {
return 'hello'; };
});
$this->dispatcher->set('map-event-2', function () { $this->dispatcher
return 'there'; ->set('map-event', $customFunction)
}); ->set('map-event-2', $anotherFunction);
$this->dispatcher->clear(); $this->dispatcher->clear();
$result = $this->dispatcher->has('map-event'); $this->assertFalse($this->dispatcher->has('map-event'));
$this->assertFalse($result); $this->assertFalse($this->dispatcher->has('map-event-2'));
$result = $this->dispatcher->has('map-event-2');
$this->assertFalse($result);
} }
public function testClearDeclaredRegisteredEvent() public function testClearDeclaredRegisteredEvent()

Loading…
Cancel
Save