Skip to content

Commit

Permalink
added event filters
Browse files Browse the repository at this point in the history
Added the capability of specifying an array of filters during event registration.
Filters are specified as regular expressions.

Example:
$client->registerEventListener(
    function($event) {var_dump($event);},
    array(
        'event' => '/Hangup/',
        'channel' => '/Local\/27.*/',
   )
);

Cherry-Picked b442e8c from @sctt (marcelog#107)
  • Loading branch information
root authored and dkgroot committed Apr 23, 2019
1 parent 85823d2 commit 78f99f2
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/PAMI/Client/Impl/ClientImpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,12 @@ protected function dispatch(IncomingMessage $message)
foreach ($this->eventListeners as $data) {
$listener = $data[0];
$predicate = $data[1];
if (is_callable($predicate) && !call_user_func($predicate, $message)) {

if (!$this->evaluatePredicate($predicate, $message))
{
continue;
}

if ($listener instanceof \Closure) {
$listener($message);
} elseif (is_array($listener)) {
Expand All @@ -350,6 +353,33 @@ protected function dispatch(IncomingMessage $message)
}
}

/**
* Evaluate a predicate for a message.
*
* @param $predicate a closure or an array of filters.
* @param \PAMI\Message\IncomingMessage $message Message to compare.
*
* @return bool
*/
protected function evaluatePredicate($predicate, IncomingMessage $message)
{
if (is_callable($predicate)) {
return call_user_func($predicate, $message);
}

if (!is_array($predicate)) {
return true;
}

foreach ($predicate as $key => $value) {
if (!preg_match($value, $message->getKey($key))) {
return false;
}
}

return true;
}

/**
* Returns a ResponseMessage from a raw string that came from asterisk.
*
Expand Down

0 comments on commit 78f99f2

Please sign in to comment.