public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->delivery_info['routing_key'];
     $method = 'read' . Inflector::camelize($routingKey);
     if (!isset($this->interpreters[$this->exchange])) {
         $interpreter = $this;
     } elseif (class_exists($this->interpreters[$this->exchange])) {
         $interpreter = new $this->interpreters[$this->exchange]();
         if (!$interpreter instanceof AmqpInterpreter) {
             throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->exchange]));
         }
     } else {
         throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->exchange]));
     }
     if (method_exists($interpreter, $method)) {
         $info = ['exchange' => $msg->get('exchange'), 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null];
         $interpreter->{$method}(Json::decode($msg->body, true), $info);
     } else {
         if (!isset($this->interpreters[$this->exchange])) {
             $interpreter = new AmqpInterpreter();
         }
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
 public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->get('routing_key');
     $method = 'read' . Inflector::camelize($routingKey);
     $interpreter = isset($this->interpreters[$this->exchange]) ? $this->interpreters[$this->exchange] : (isset($this->interpreters['*']) ? $this->interpreters['*'] : null);
     if ($interpreter === null) {
         $interpreter = $this;
     } else {
         if (class_exists($interpreter)) {
             $interpreter = new $interpreter();
             if (!$interpreter instanceof AmqpInterpreter) {
                 throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $interpreter));
             }
         } else {
             throw new Exception(sprintf("Interpreter class '%s' was not found.", $interpreter));
         }
     }
     if (method_exists($interpreter, $method) || is_callable([$interpreter, $method])) {
         $info = ['exchange' => $this->exchange, 'routing_key' => $routingKey, 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null, 'delivery_tag' => $msg->get('delivery_tag')];
         try {
             $body = Json::decode($msg->body, true);
         } catch (\Exception $e) {
             $body = $msg->body;
         }
         $interpreter->{$method}($body, $info, $this->amqp->channel);
     } else {
         if (!$interpreter instanceof AmqpInterpreter) {
             $interpreter = new AmqpInterpreter();
         }
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
Example #3
1
 /**
  * Publishes the message and merges additional properties with basic properties
  *
  * @param string $msgBody
  * @param string $routingKey
  * @param array $additionalProperties
  * @param array $headers
  */
 public function publish($msgBody, $routingKey = '', $additionalProperties = array(), array $headers = null)
 {
     if ($this->autoSetupFabric) {
         $this->setupFabric();
     }
     $msg = new AMQPMessage((string) $msgBody, array_merge($this->getBasicProperties(), $additionalProperties));
     if (!empty($headers)) {
         $headersTable = new AMQPTable($headers);
         $msg->set('application_headers', $headersTable);
     }
     $this->getChannel()->basic_publish($msg, $this->exchangeOptions['name'], (string) $routingKey);
     $this->logger->debug('AMQP message published', array('amqp' => array('body' => $msgBody, 'routingkeys' => $routingKey, 'properties' => $additionalProperties, 'headers' => $headers)));
 }
 public function execute(AMQPMessage $msg)
 {
     $infoHeader = $msg->get("application_headers")->getNativeData();
     $response = json_decode($msg->body, true);
     echo "Message: " . $response["response"] . "  Reason (" . $infoHeader['x-death'][0]['reason'] . ")" . PHP_EOL;
     return self::MSG_ACK;
 }
 /**
  * @param AMQPMessage $message
  *
  * @return AMQPTable
  */
 private function getHeaders(AMQPMessage $message)
 {
     if ($message->has('application_headers')) {
         return $message->get('application_headers');
     }
     return new AMQPTable();
 }
 public function execute(AMQPMessage $msg)
 {
     $body = json_decode($msg->body, true);
     if ($msg->has("application_headers")) {
         $nativeData = $msg->get("application_headers")->getNativeData();
     }
     return $this->readMessage($body, isset($nativeData['attempts']) ? $nativeData['attempts'] : 0);
 }
Example #7
0
 public function processMessage(AMQPMessage $msg)
 {
     $messageBody = $msg->body;
     if ($this->expectSerializedResponse) {
         $messageBody = call_user_func($this->unserializer, $messageBody);
     }
     $this->replies[$msg->get('correlation_id')] = $messageBody;
 }
Example #8
0
 /**
  * When a message appears, it checks the correlation_id property. If it
  * matches the value from the request it returns the response to the
  * application.
  *
  * @param AMQPMessage $rep
  */
 public function onResponse(AMQPMessage $rep)
 {
     $this->log->addInfo('Received response');
     if ($rep->get('correlation_id') == $this->corr_id) {
         $this->log->addInfo('Correlation id matches, setting response: ' . $rep->body);
         $this->response = $rep->body;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function execute(AMQPMessage $amqpMessage)
 {
     // Ack message and get event
     $amqpMessage->delivery_info['channel']->basic_ack($amqpMessage->delivery_info['delivery_tag']);
     /** @var Event $event */
     $event = $this->serializer->deserialize($amqpMessage->getBody(), 'Ndewez\\EventsBundle\\Model\\Event', 'json');
     // Process
     $this->listen->listen($event);
 }
Example #10
0
 /**
  * Decodes a message
  *
  * @param \PhpAmqpLib\Message\AMQPMessage $message the message to decode
  *
  * @return bool|array the decoded message, or false if the message content type
  * is unsupported or the message is malformed.
  */
 public function decode($message)
 {
     $contentType = $message->get('content_type');
     if (!stristr($contentType, 'json')) {
         return false;
     }
     $decoded = json_decode($message->body, true);
     return $decoded === null ? false : $decoded;
 }
 public function test_toMessageInterface_withProperRpcRequestTypeAMQMessage_returnsRpcRequestMessage()
 {
     $adaptor = new PhpAmqpLibMessageAdaptor();
     $amqpMessage = new AMQPMessage();
     $amqpMessage->set(MessageInterface::PROPERTY_TYPE, MessageInterface::TYPE_RPC_REQUEST);
     $amqpMessage->set(MessageInterface::PROPERTY_CONTENT_TYPE, MessageInterface::CONTENT_TYPE_PLAIN_TEXT);
     $message = $adaptor->toMessageInterface($amqpMessage);
     $this->assertTrue($message instanceof RpcRequestMessage, 'Returned value is not an instance of RpcRequestMessage');
 }
Example #12
0
 /**
  * @param AMQPMessage $queueMessage
  *
  * @return $this
  */
 protected function setPropertiesFromMessage($queueMessage)
 {
     foreach ($this->propertyMapping as $mqlibProperty => $amqpProperty) {
         if ($queueMessage->has($amqpProperty) && property_exists($this, $mqlibProperty)) {
             $this->{$mqlibProperty} = $amqpProperty;
         }
     }
     return $this;
 }
 /**
  * Schedule a job in the future
  *
  * @access public
  * @param  Job      $job
  * @param  DateTime $dateTime
  * @return $this
  */
 public function schedule(Job $job, DateTime $dateTime)
 {
     $now = new DateTime();
     $when = clone $dateTime;
     $delay = $when->getTimestamp() - $now->getTimestamp();
     $message = new AMQPMessage($job->serialize(), array('delivery_mode' => 2));
     $message->set('application_headers', new AMQPTable(array('x-delay' => $delay)));
     $this->channel->basic_publish($message, $this->exchange);
     return $this;
 }
 /**
  * @param AMQPMessage $message The message
  * @return mixed false to reject and requeue, any other value to aknowledge
  */
 public function execute(AMQPMessage $message)
 {
     $type = $message->get('type');
     if ('Lw\\Domain\\Model\\User\\UserRegistered' === $type) {
         $event = json_decode($message->body);
         $eventBody = json_decode($event->event_body);
         $this->commandBus->handle(new SignupCommand($eventBody->user_id->id));
         return true;
     }
     return false;
 }
 /**
  * @param AMQPMessage $message
  *
  * @return Request
  *
  * @throws \Exception
  */
 private function createRequest(AMQPMessage $message)
 {
     $topic = $message->delivery_info['routing_key'];
     $headers = $message->has('application_headers') ? $message->get('application_headers')->getNativeData() : [];
     $version = isset($headers['version']) ? $headers['version'] : null;
     $arguments = json_decode($message->getBody(), true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         throw new EncodingException('Unable to decode request: ' . json_last_error_msg());
     }
     return new Request($topic, $version, $arguments, $headers);
 }
 /**
  * Verify if message reached max attemps.
  * @param AMQPMessage $msg
  * @return bool
  */
 protected function hasMaxAttempts(AMQPMessage $msg)
 {
     $AMQPTable = $msg->get("application_headers");
     $properties = $AMQPTable->getNativeData();
     if (isset($properties['attempts'])) {
         $attemps = $properties['attempts'];
         if ($attemps > self::MAX_ATTEMPTS) {
             return true;
         }
     }
     return false;
 }
 /**
  * @param AMQPMessage $message
  * @param string      $exchange
  * @param string      $routingKey
  *
  * @return Invoker\Reply
  *
  * @throws \Exception
  */
 public function call(AMQPMessage $message, $exchange = '', $routingKey = '')
 {
     $this->enqueue($reply = new Invoker\Reply($this));
     try {
         $message->set('reply_to', $this->getReplyQueue());
         $message->set('correlation_id', $reply->id());
         $this->channel->basic_publish($message, $exchange, $routingKey);
     } catch (\Exception $e) {
         $this->dequeue($reply);
         throw $e;
     }
     return $reply;
 }
 public function execute(AMQPMessage $msg)
 {
     //$msg will be an instance of `PhpAmqpLib\Message\AMQPMessage` with the $msg->body being the data sent over RabbitMQ.
     echo "Event: " . $msg->get('routing_key') . PHP_EOL;
     $routingKey = $msg->get('routing_key');
     if ($this->dispatcher->hasListeners($routingKey) && $routingKey != '') {
         $data = $this->serializer->deserialize($msg->body, 'array', 'json');
         var_dump($data);
         $this->dispatcher->dispatch($routingKey, new GenericEvent($routingKey, $data));
         return true;
     }
     return false;
 }
Example #19
0
 public function testFrameOrder()
 {
     $msg = new AMQPMessage('');
     $hdrs = new AMQPTable(array('x-foo' => 'bar'));
     $msg->set('application_headers', $hdrs);
     for ($i = 0; $i < $this->msg_count; $i++) {
         $this->ch->basic_publish($msg, $this->exchange_name, $this->queue_name);
     }
     $this->ch2->basic_consume($this->queue_name, '', false, true, false, false, array($this, 'process_msg'));
     while (count($this->ch2->callbacks)) {
         $this->ch2->wait();
     }
 }
 public static function createAmqpLibMessage(AmqpMessage $message, $persistent = true)
 {
     $amqpLibMessage = new AmqpLibMessage($message->getBody());
     foreach (self::$PROPERTY_MAP as $name => $amqpLibName) {
         $value = $message->{'get' . ucfirst($name)}();
         if ($value !== null) {
             $amqpLibMessage->set($amqpLibName, $value);
         }
     }
     $deliveryMode = $persistent ? self::DELIVERY_MODE_PERSISTENT : self::DELIVERY_MODE_NON_PERSISTENT;
     $amqpLibMessage->set('delivery_mode', $deliveryMode);
     return $amqpLibMessage;
 }
Example #21
0
 public function callback(AMQPMessage $Message)
 {
     try {
         $result = $Message->delivery_info['delivery_tag'];
         // отправляем ответ, если он вообще нужен
         if ($Message->has('reply_to')) {
             $Message->delivery_info['channel']->basic_publish(new AMQPMessage($this->_encode($result), ['correlation_id' => $Message->get('correlation_id')]), '', $Message->get('reply_to'));
         }
         // подтверждаем
         $Message->delivery_info['channel']->basic_ack($Message->delivery_info['delivery_tag']);
     } catch (\Exception $e) {
         $Message->delivery_info['channel']->basic_nack($Message->delivery_info['delivery_tag']);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function execute(AMQPMessage $msg)
 {
     /* @var $message Message */
     $message = $msg->getMessage();
     $serializer = $this->serializer;
     $content = $message->getValue('content');
     $xml = new \SimpleXMLElement($content);
     /** @var \Doctrine\Common\Persistence\ObjectRepository $repository */
     $repository = $this->objectManager->getRepository($this->atomEntryClass);
     try {
         /** @var \Bangpound\Bundle\PubsubBundle\CouchDocument\AtomFeed $feed */
         $feed = $serializer->deserialize($content, 'Bangpound\\Bundle\\PubsubBundle\\CouchDocument\\AtomFeed', 'xml');
         $source = new SourceType();
         $source->setAuthors($feed->getAuthors());
         $source->setBase($feed->getBase());
         $source->setCategories($feed->getCategories());
         $source->setContributors($feed->getContributors());
         $source->setGenerator($feed->getGenerator());
         $source->setIcon($feed->getIcon());
         $source->setLang($feed->getLang());
         $source->setLogo($feed->getLogo());
         $source->setLinks($feed->getLinks());
         $source->setRights($feed->getRights());
         $source->setSubtitle($feed->getSubtitle());
         $source->setTitle($feed->getTitle());
         $source->setUpdated($feed->getUpdated());
         $execute = FALSE;
         /** @var \Bangpound\Bundle\PubsubBundle\CouchDocument\AtomEntry $entry */
         foreach ($feed->getEntries() as $key => $entry) {
             $id = $entry->getId();
             $existing = $repository->findOneBy(['id' => $id]);
             if ($existing) {
                 $this->logger->info(sprintf('Duplicate notification sent for %s - %s', $id, $entry->getTitle()), ['existing' => $existing, 'new' => $entry]);
                 continue;
             }
             $execute = TRUE;
             if (!$entry->getSource()) {
                 $entry->setSource(clone $source);
             }
             $entry->setOriginalData($xml->entry[$key]->asXml(), 'text/xml');
             $this->objectManager->persist($entry);
         }
         if ($execute) {
             $this->objectManager->flush();
         }
         $this->objectManager->clear();
     } catch (RuntimeException $e) {
         throw $e;
     }
 }
 /**
  * @dataProvider propertiesDataProvider
  */
 public function testSerializeProperties(array $expected, array $properties)
 {
     /** @var AMQPReader $reader */
     $reader = new AMQPReader(null);
     /** @var AMQPMessage $message */
     $message = new AMQPMessage('', $properties);
     /** @var string $encodedData */
     $encodedData = $message->serialize_properties();
     // Bypasses the network part and injects the encoded data into the reader
     $reader->reuse($encodedData);
     // Injects the reader into the message
     $message->load_properties($reader);
     $this->assertEquals($expected, $message->get_properties());
 }
Example #24
0
 /**
  * @param string $name
  * @return string
  */
 private function getFromEnvelope(string $name) : string
 {
     if ($this->envelope->has($name)) {
         return $this->envelope->get($name);
     }
     return '';
 }
 /**
  * @param string $title
  * @param string $text
  * @param array  $properties
  */
 public function __construct($title, $text, $identifier = null, array $properties = null)
 {
     if (!is_scalar($title) && !is_scalar($text)) {
         throw new \InvalidArgumentException(sprintf("'title' and 'text' must be a scalar"));
     }
     parent::__construct(json_encode(['title' => $title, 'text' => $text, 'identifier' => $identifier]), $properties);
 }
 /**
  * @param float $value
  * @param array $properties
  */
 public function __construct($value, array $properties = null)
 {
     if (!is_numeric($value)) {
         throw new \InvalidArgumentException("Value needs to be numeric");
     }
     parent::__construct(floatval($value), $properties);
 }
 /**
  * @param string $value
  * @param array  $properties
  */
 public function __construct($value, array $properties = null)
 {
     if (!is_string($value)) {
         throw new \InvalidArgumentException(sprintf("The passed value must be of type string"));
     }
     parent::__construct($value, $properties);
 }
 /**
  * @param string $text
  * @param array  $properties
  */
 public function __construct($text, array $properties = null)
 {
     if (!is_scalar($text)) {
         throw new \InvalidArgumentException(sprintf("'text' must be of a scalar"));
     }
     parent::__construct($text, $properties);
 }
Example #29
0
 /**
  * Callback executed when a message is received. Dumps the message body, delivery_info and properties.
  *
  * @param AMQPMessage $msg The received message.
  *
  * @return void
  */
 public function execute(AMQPMessage $msg)
 {
     echo str_repeat('-', 60) . PHP_EOL;
     echo '[RECV ' . date('c') . ']' . PHP_EOL . '<content>' . PHP_EOL . $msg->body . PHP_EOL . '</content>' . PHP_EOL . PHP_EOL;
     echo "*" . ' INFO ' . PHP_EOL;
     foreach ($msg->{'delivery_info'} as $key => $value) {
         if (is_scalar($value)) {
             echo "** " . $key . ' = ' . $value . PHP_EOL;
         }
     }
     echo "*" . ' PROPERTIES ' . PHP_EOL;
     foreach ($msg->get_properties() as $property => $value) {
         if (is_scalar($value)) {
             echo "** " . $property . ' = ' . $value . PHP_EOL;
         }
     }
 }
 /**
  * @param AMQPMessage $message The message
  * @return mixed false to reject and requeue, any other value to aknowledge
  */
 public function execute(AMQPMessage $message)
 {
     $type = $message->get('type');
     if ('Lw\\Domain\\Model\\Wish\\WishWasMade' === $type) {
         $event = json_decode($message->body);
         $eventBody = json_decode($event->event_body);
         try {
             $this->commandBus->handle(new RewardUserCommand($eventBody->user_id->id, 5));
         } catch (AggregateDoesNotExist $e) {
             // Noop
         }
         return true;
     }
     return false;
 }