Skip to content

Commit

Permalink
Merge pull request #24 from SergiX44/add-fallback-hook
Browse files Browse the repository at this point in the history
Add fallback listener
  • Loading branch information
cheeghi committed Dec 27, 2020
2 parents d90f782 + 84ebd52 commit c22f565
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Zanzara/Listener/ListenerCollector.php
Expand Up @@ -56,6 +56,11 @@ abstract class ListenerCollector
*/
protected $listeners = [];

/**
* @var Listener
*/
protected $fallbackListener;

/**
* @var ContainerInterface
*/
Expand Down Expand Up @@ -421,6 +426,21 @@ public function onUpdate($callback): MiddlewareCollector
return $listener;
}

/**
* If no listener matches the current update, this listener will be called if specified.
*
* @param $callback
* @return MiddlewareCollector
* @throws DependencyException
* @throws NotFoundException
*/
public function fallback($callback): MiddlewareCollector
{
$listener = new Listener($callback, $this->container);
$this->fallbackListener = $listener;
return $listener;
}

/**
* Define a middleware that will be executed for every listener function and before listener-specific middleware.
*
Expand Down
6 changes: 6 additions & 0 deletions src/Zanzara/Listener/ListenerResolver.php
Expand Up @@ -120,6 +120,12 @@ private function findListenerAndPush(array &$listeners, string $listenerType, st
return $listener;
}
}

if ($this->fallbackListener !== null) {
$listeners[] = $this->fallbackListener;
return $this->fallbackListener;
}

return null;
}

Expand Down
20 changes: 20 additions & 0 deletions tests/Listener/UpdateTest.php
Expand Up @@ -33,4 +33,24 @@ public function testUpdate()
$bot->run();
}

/**
*
*/
public function testFallback()
{
$config = new Config();
$config->setUpdateMode(Config::WEBHOOK_MODE);
$config->setUpdateStream(__DIR__ . '/../update_types/command.json');
$bot = new Zanzara("test", $config);

$bot->onText('testCommand', function (Context $ctx){});

$bot->fallback(function (Context $ctx) {
$update = $ctx->getUpdate();
$this->assertSame(52259544, $update->getUpdateId());
});

$bot->run();
}

}

0 comments on commit c22f565

Please sign in to comment.