/**
* @param callable $callback
* @throws NotSubscribedListenerException
* @throws \Exception
* @return void
*/
public function subscribe(callable $callback)
{
$this->callback = $callback;
//Check whether connection open or not
if (!$this->connection->isConnected()) {
$this->connection->connect();
}
/** Declare exchange. In case it is already exists it could change it's options */
$this->declareExchange();
//Binding queue to correct exchange
if (!$this->getQueue()->bind($this->exchangeConfig['name'])) {
throw new NotSubscribedListenerException("Can not bind " . $this->getQueue()->getName() . " to an exchange " . $this->exchangeConfig);
}
$callback = function (\AMQPEnvelope $message) {
switch ($message->getType()) {
//Stop consumer by special event
case 'eventBus.consumer-stop':
$this->getQueue()->ack($message->getDeliveryTag());
call_user_func($this->callback, 'eventBus.consumer-stop');
$this->stopConsumer();
break;
default:
//If publisher is same BC as subscriber, don't proceed
if ($message->getAppId() !== $this->getQueue()->getName()) {
call_user_func($this->callback, $this->unpackMessage($message));
}
}
//Answering to RabbitMQ, that event processed
$this->getQueue()->ack($message->getDeliveryTag());
};
$callback->bindTo($this);
//Listen events
$this->getQueue()->consume($callback);
}