The query bus dispatches a query message to a finder. The query is maybe dispatched async so the bus returns a promise which gets either resolved with the response of the finder or rejected with an exception. Additionally the finder can provide an update status but this is not guaranteed.
Author: Alexander Miertsch (kontakt@codeliner.ws)
Inheritance: extends MessageBus
Example #1
0
 /**
  * @param RequestInterface $request
  * @param ResponseInterface $response
  * @param callable $next
  * @return ResponseInterface
  */
 public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
 {
     $users = [];
     $this->queryBus->dispatch(new GetAllUsers())->then(function ($result) use(&$users) {
         $users = $result;
     });
     return new HtmlResponse($this->templates->render('page::user-list', ['users' => $users]));
 }
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @param callable $next
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $userId = $request->getAttribute('user_id');
     $user = null;
     $this->queryBus->dispatch(new GetUserById($userId))->then(function ($result) use(&$user) {
         $user = $result;
     });
     $todos = null;
     $this->queryBus->dispatch(new GetTodosByAssigneeId($userId))->then(function ($result) use(&$todos) {
         $todos = $result;
     });
     return new HtmlResponse($this->templates->render('page::user-todo-list', ['user' => $user, 'todos' => $todos]));
 }
 /**
  * @interitdoc
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $payload = null;
     $messageName = 'UNKNOWN';
     try {
         $payload = $request->getParsedBody();
         if (is_array($payload) && isset($payload['message_name'])) {
             $messageName = $payload['message_name'];
         }
         MessageDataAssertion::assert($payload);
         $message = $this->messageFactory->createMessageFromArray($payload['message_name'], $payload);
         switch ($message->messageType()) {
             case Message::TYPE_COMMAND:
                 $this->commandBus->dispatch($message);
                 return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED);
             case Message::TYPE_EVENT:
                 $this->eventBus->dispatch($message);
                 return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED);
             case Message::TYPE_QUERY:
                 return $this->responseStrategy->fromPromise($this->queryBus->dispatch($message));
             default:
                 return $next($request, $response, new RuntimeException(sprintf('Invalid message type "%s" for message "%s".', $message->messageType(), $messageName), Middleware::STATUS_CODE_BAD_REQUEST));
         }
     } catch (\Assert\InvalidArgumentException $e) {
         return $next($request, $response, new RuntimeException($e->getMessage(), Middleware::STATUS_CODE_BAD_REQUEST, $e));
     } catch (\Exception $e) {
         return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of message "%s"', $messageName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e));
     }
 }
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @param callable $next
  * @return HtmlResponse
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $userId = $request->getAttribute('user_id');
     $invalidUser = true;
     $user = null;
     if ($userId) {
         $user = null;
         $this->queryBus->dispatch(new GetUserById($userId))->then(function ($result) use(&$user) {
             $user = $result;
         });
         if ($user) {
             $invalidUser = false;
         }
     }
     return new HtmlResponse($this->templates->render('page::user-todo-form', ['invalidUser' => $invalidUser, 'user' => $user]));
 }
 /**
  * @param TodoAssigneeWasReminded $event
  */
 public function __invoke(TodoAssigneeWasReminded $event)
 {
     $user = null;
     $this->queryBus->dispatch(new GetUserById($event->userId()->toString()))->then(function ($result) use(&$user) {
         $user = $result;
     });
     $todo = null;
     $this->queryBus->dispatch(new GetTodoById($event->todoId()->toString()))->then(function ($result) use(&$todo) {
         $todo = $result;
     });
     $mail = new Mail\Message();
     $mail->setBody("Hello {$user->name}. This a reminder for '{$todo->text}'. Don't be lazy!");
     $mail->setFrom('*****@*****.**', 'Proophessor-do');
     $mail->addTo($user->email, $user->name);
     $mail->setSubject('Proophessor-do Todo Reminder');
     $this->mailer->send($mail);
 }
 /**
  * @test
  * @expectedException Prooph\ServiceBus\Exception\RuntimeException
  */
 public function it_throws_exception_if_message_was_not_handled()
 {
     $this->queryBus->getActionEventEmitter()->attachListener(MessageBus::EVENT_INITIALIZE, function (ActionEvent $e) {
         $e->setParam(MessageBus::EVENT_PARAM_MESSAGE_HANDLER, new \stdClass());
     });
     $promise = $this->queryBus->dispatch('throw it');
     $promise->done();
 }
 /**
  * @interitdoc
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $queryName = $request->getAttribute(self::NAME_ATTRIBUTE);
     if (null === $queryName) {
         return $next($request, $response, new RuntimeException(sprintf('Query name attribute ("%s") was not found in request.', self::NAME_ATTRIBUTE), Middleware::STATUS_CODE_BAD_REQUEST));
     }
     $payload = $request->getQueryParams();
     if ($request->getMethod() === 'POST') {
         $payload['data'] = $request->getParsedBody();
     }
     try {
         $query = $this->queryFactory->createMessageFromArray($queryName, ['payload' => $payload, 'metadata' => $this->metadataGatherer->getFromRequest($request)]);
         return $this->responseStrategy->fromPromise($this->queryBus->dispatch($query));
     } catch (\Exception $e) {
         return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of query "%s"', $queryName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e));
     }
 }
Example #8
0
 /**
  * @test
  */
 public function it_can_deactive_an_action_event_listener_aggregate()
 {
     $handler = new Finder();
     $this->queryBus->getActionEventEmitter()->attachListener(MessageBus::EVENT_ROUTE, function (ActionEvent $e) use($handler) {
         if ($e->getParam(MessageBus::EVENT_PARAM_MESSAGE_NAME) === CustomMessage::class) {
             $e->setParam(MessageBus::EVENT_PARAM_MESSAGE_HANDLER, $handler);
         }
     });
     $plugin = new FinderInvokeStrategy();
     $this->queryBus->utilize($plugin);
     $this->queryBus->deactivate($plugin);
     $customMessage = new CustomMessage("foo");
     $promise = $this->queryBus->dispatch($customMessage);
     $this->assertNull($handler->getLastMessage());
     $this->assertInstanceOf(Promise::class, $promise);
     $this->assertNull($handler->getLastDeferred());
 }