/**
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  * @throws \Exception
  */
 public function __invoke(Request $request)
 {
     $user = $this->getUser();
     if (!$user) {
         throw $this->createAccessDeniedException();
     }
     $createWalletCommand = $this->createCreateWalletCommand();
     $createWalletForm = $this->walletFormFactory->createCreateForm($createWalletCommand);
     $createWalletForm->handleRequest($request);
     if (!$createWalletForm->isValid()) {
         $validationMsg = $this->getAllFormErrorMessagesAsString($createWalletForm);
         $this->addFlash('error', $this->trans('create_transaction_form.flash.invalid_form') . ' ' . $validationMsg);
     } else {
         /** @var CreateWalletCommand $createWalletCommand */
         $createWalletCommand = $createWalletForm->getData();
         $createWalletCommand->setWalletOwnerId($user->getId()->getValue());
         $createWalletCommand->setToken($user->getBlockCypherToken());
         try {
             $commandValidator = new CreateWalletCommandValidator();
             $commandValidator->validate($createWalletCommand);
             $this->commandBus->handle($createWalletCommand);
             $this->addFlash('success', $this->trans('wallet.flash.create_successfully'));
             $url = $this->router->generate('bc_app_wallet_wallet.index');
             return new RedirectResponse($url);
         } catch (\Exception $e) {
             $this->addFlash('error', $e->getMessage());
         }
     }
     return $this->renderWalletShowNew($request, $createWalletForm->createView());
 }
 /**
  * @param Request $request
  * @return Response
  * @throws \Exception
  */
 public function __invoke(Request $request)
 {
     $walletId = $request->get('walletId');
     $walletDto = $this->walletServiceFacade->getWallet($walletId);
     $this->checkAuthorizationForWallet($walletDto);
     $createTransactionCommand = $this->createCreateTransactionCommand($walletId);
     $user = $this->getUser();
     $createTransactionForm = $this->transactionFormFactory->createCreateForm($createTransactionCommand, $user->getId()->getValue());
     $createTransactionForm->handleRequest($request);
     if (!$createTransactionForm->isValid()) {
         $validationMsg = $this->getAllFormErrorMessagesAsString($createTransactionForm);
         $this->addFlash('error', $this->trans('create_transaction_form.flash.invalid_form') . ' ' . $validationMsg);
     } else {
         /** @var CreateTransactionCommand $createTransactionCommand */
         $createTransactionCommand = $createTransactionForm->getData();
         try {
             $commandValidator = new CreateTransactionCommandValidator();
             $commandValidator->validate($createTransactionCommand);
             $this->commandBus->handle($createTransactionCommand);
             $this->addFlash('success', $this->trans('transaction.flash.create_successfully'));
             $url = $this->router->generate('bc_app_wallet_transaction.index', array('walletId' => $createTransactionCommand->getWalletId()));
             return new RedirectResponse($url);
         } catch (\Exception $e) {
             $this->addFlash('error', $e->getMessage());
         }
     }
     $walletDto = $this->walletServiceFacade->getWallet($walletId);
     return $this->renderTransactionShowNew($request, $createTransactionForm->createView(), $walletDto);
 }
 /**
  * @param LogicInterface $logic
  * @param array          $parameters
  *
  * @return mixed
  * @throws \Exception
  */
 public function handle(LogicInterface $logic, $parameters)
 {
     if (count($logic->getRules()) > 0) {
         foreach ($logic->getRules() as $rule) {
             $result = $this->language->evaluate($rule->getExpression(), $parameters);
             foreach ($rule->getActions() as $action) {
                 if ($result == $action->getResult()) {
                     switch ($action->getType()) {
                         case ActionInterface::EXCEPTION:
                             throw new \Exception($action->getParameter());
                             break;
                         case ActionInterface::COMMAND:
                             $command = $this->createCommand($action, $parameters);
                             $this->commandBus->handle($command);
                             break;
                         case ActionInterface::EVENT:
                             $event = $this->createEvent($action, $parameters);
                             $this->eventBus->handle($event);
                             break;
                         default:
                             throw new \Exception("Unkown type");
                             break;
                     }
                 }
             }
         }
     }
 }
Exemple #4
0
 public function orderAction($id)
 {
     $query = new GetOrderByIdQuery($id);
     $this->queryBus->handle($query);
     if (!$this->checker->isGranted('read', $query->getResult())) {
         throw new AccessDeniedException();
     }
     return new Response($this->engine->render(':order:order.html.twig', ['order' => $query->getResult()]));
 }
 /**
  * @param string $serializedEnvelope
  */
 public function consume($serializedEnvelope)
 {
     // Unserialize
     $envelope = $this->messageInEnvelopeSerializer->unwrapAndDeserialize($serializedEnvelope);
     // Tell the world
     $this->dispathcer->dispatch(PreHandleMessage::NAME, new PreHandleMessage($envelope));
     // Handle the message
     $this->messageBus->handle($envelope->message());
 }
Exemple #6
0
 public function updateProfile(UpdateProfileCommand $command)
 {
     $user = $this->getActualUser();
     $address = $command->getAddress();
     $user->changeAddress(new Address($address->getCountry(), $address->getCity(), $address->getStreet(), $address->getZipCode()));
     $this->repository->save($user);
     $event = new ProfileUpdatedEvent($user);
     $this->eventBus->handle($event);
 }
Exemple #7
0
 public function verifyRequest(VerifyRequestCommand $command)
 {
     $token = $this->requestVerifier->verify($command->getRequest());
     $gateway = $this->registry->getGateway($token->getGatewayName());
     $gateway->execute($status = new GetHumanStatus($token));
     $payment = $status->getFirstModel();
     $this->requestVerifier->invalidate($token);
     $event = new RequestVerifiedEvent($status, $payment);
     $this->eventBus->handle($event);
 }
 /**
  * @param object   $message
  * @param callable $next
  */
 public function handle($message, callable $next)
 {
     $this->logger->debug('NotifiesDomainEvents calls next before collect events');
     $next($message);
     $events = $this->collectsEventsFromEntities->recordedMessages();
     $this->collectsEventsFromEntities->eraseMessages();
     $this->logger->debug('NotifiesDomainEvents notifies ' . count($events) . ' events');
     foreach ($events as $event) {
         $this->eventBus->handle($event);
     }
 }
Exemple #9
0
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $request
  * @param \Slim\Http\Response                      $response
  *
  * @return \Slim\Http\Response
  * @throws \livetyping\hermitage\app\exceptions\BadRequestException
  */
 public function __invoke(Request $request, Response $response) : Response
 {
     $mime = (string) current($request->getHeader('Content-Type'));
     $binary = (string) $request->getBody();
     if (empty($mime) || empty($binary) || !in_array($mime, Util::supportedMimeTypes())) {
         throw new BadRequestException('Invalid mime-type or body.');
     }
     $command = new StoreImageCommand($mime, $binary);
     $this->bus->handle($command);
     return $response->withStatus(201)->withJson(['filename' => $command->getPath()]);
 }
Exemple #10
0
 public function registerAction(Request $request)
 {
     $form = $this->formFactory->create('Shop\\Presentation\\Form\\UserType');
     $form->handleRequest($request);
     if ($form->isValid() && $form->isSubmitted()) {
         $command = $form->getData();
         $this->commandBus->handle($command);
         return new RedirectResponse('/');
     }
     return new Response($this->engine->render(':security:register.html.twig', ['form' => $form->createView()]));
 }
 /**
  * @Route("/dodaj", name="pracownik.dodaj")
  * @Template()
  *
  * @param Request $request
  * @return array
  */
 public function dodajAction(Request $request)
 {
     $form = $this->createForm(PracownikType::class, $this->dodajPracownikaCommand);
     $form->handleRequest($request);
     if ($form->isValid()) {
         $this->commandBus->handle($this->dodajPracownikaCommand);
         $this->unitOfWork->commit();
         return new RefererRedirectResponse($request);
     }
     return ['form' => $form->createView()];
 }
 public function run()
 {
     try {
         $requestWithParsedBody = $this->requestBodyParser->enrichRequestWithParsedBody($this->requestKnowledge->getRequest());
         $this->requestKnowledge->setRequest($requestWithParsedBody);
         $command = $this->router->getCommand();
         $this->commandBus->handle($command);
     } catch (HttpException $e) {
         $this->exceptionHandler->handle($e);
     }
 }
 public function handle($message, callable $next)
 {
     try {
         $next($message);
     } catch (Exception $exception) {
         $this->messageRecorder->eraseMessages();
         throw $exception;
     }
     $recordedMessages = $this->messageRecorder->recordedMessages();
     $this->messageRecorder->eraseMessages();
     foreach ($recordedMessages as $recordedMessage) {
         $this->messageBus->handle($recordedMessage);
     }
 }
Exemple #14
0
 public function createOrder(CreateOrderCommand $command)
 {
     $cart = $this->cartRepository->getCart();
     if ($cart->getLineItems()->count() === 0) {
         throw new \RuntimeException("The cart is empty");
     }
     $address = $command->getAddress();
     $order = new Order(new UuidIdentity(Uuid::uuid4()), $this->tokenStorage->getToken()->getUser(), new Address($address->getCountry(), $address->getCity(), $address->getStreet(), $address->getZipCode()));
     foreach ($cart->getLineItems() as $lineItem) {
         $order->addProduct($lineItem->getProduct(), $lineItem->getQuantity());
     }
     $this->orderRepository->save($order);
     $event = new OrderCreatedEvent($order, $command->getGatewayName());
     $this->eventBus->handle($event);
 }
Exemple #15
0
 public function handleChangeUserEmail(ChangeUserEmail $changeUserEmail)
 {
     $user = $this->userManager->find($changeUserEmail->userId());
     $oldEmail = $user->getEmail();
     $newEmail = $changeUserEmail->newEmail();
     // perform action only if email address has changed
     if (false === $newEmail->equals($oldEmail)) {
         $user->setEmail($changeUserEmail->newEmail());
         // normally we would call something like:
         // $this->userManager->save($user);
         // but we are changing in-memory value
         // notify subscribers using specific event
         $changedUserEmailEvent = new ChangedUserEmail($changeUserEmail->userId(), $oldEmail, $newEmail);
         $this->eventBus->handle($changedUserEmailEvent);
     }
 }
 /**
  * Shoot the create dojo command into the command bus
  *
  * @param $externalDojo
  */
 private function createDojo($externalDojo)
 {
     $this->progressBar->setMessage('Creating new dojo');
     $this->commandBus->handle($externalDojo);
     $this->progressBar->advance();
     $this->countNew++;
 }
Exemple #17
0
 private function getCategoryById($id)
 {
     if ($id) {
         $query = new GetCategoryByIdQuery($id);
         if ($query->getId()) {
             $this->queryBus->handle($query);
         }
         return $query->getResult();
     }
     return null;
 }
Exemple #18
0
 /**
  * Post a new search request
  *
  * @ApiDoc(
  * parameters={
  *      {
  *          "name"="queryString",
  *          "dataType"="string",
  *          "format"="non-empty string",
  *          "required"=true,
  *          "description"="Search string"
  *      }
  *  },
  * requirements={
  *      {
  *          "name"="_format",
  *          "dataType"="string",
  *          "requirement"="json|xml",
  *          "description"="Response format"
  *      }
  *  },
  * )
  *
  * @param Request $request
  * @return array
  * @View()
  */
 public function postSearchAction(Request $request)
 {
     $queryString = $request->request->get('queryString', '');
     // Check if the queryString is not empty
     if (!empty($queryString)) {
         $command = new SaveSearchRequestCommand($queryString);
         $this->commandBus->handle($command);
         return $this->getResultsAction($queryString);
     }
     throw new BadRequestHttpException('You must provide a (non empty) query string');
 }
 /**
  * @param MessageBus                  $commandBus
  * @param PersistentMessage           $command
  * @param PersistentCommandRepository $commandRepository
  */
 protected function handleCommandAndAssertTraced(MessageBus $commandBus, PersistentMessage $command, PersistentCommandRepository $commandRepository)
 {
     $commandBus->handle($command);
     $this->assertInstanceOf(Identity::class, $command->getId());
     $foundCommand = $commandRepository->get($command->getId());
     $this->assertSame($command, $foundCommand);
     if (!$command instanceof TraceableCommand) {
         $this->fail(sprintf('The message %s is not Traceable', get_class($command)));
     }
     $this->assertInstanceOf(Trace::class, $trace = $command->getTrace());
     $this->assertInstanceOf(Context::class, $trace->getContext());
 }
 public function viewAction($id, Request $request)
 {
     $query = new GetProductByIdQuery($id);
     $this->queryBus->handle($query);
     /** @var ProductView $product */
     $product = $query->getResult();
     $command = new UpdateProductCommand($product->getId(), $product->getName(), $product->getPrice(), $product->getCategory()->getId(), $product->getDescription(), $product->isAvailable(), $product->getImageUrl());
     $command->setProductOptions(array_map(function (ProductOptionView $optionView) {
         $productOption = new ProductOption();
         $productOption->setOption($optionView->getOption()->getId());
         $productOption->setValue($optionView->getValue());
         return $productOption;
     }, $product->getProductOptions()));
     $form = $this->formFactory->create('Shop\\Presentation\\Form\\ProductType', $command);
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         $this->commandBus->handle($command);
         return new RedirectResponse($this->router->generate('admin_product', ['id' => $command->getId()]));
     }
     return new Response($this->engine->render(':admin/product:form.html.twig', ['form' => $form->createView()]));
 }
Exemple #21
0
 public function updateProduct(UpdateProductCommand $command)
 {
     $product = $this->repository->findByIdentity(new UuidIdentity($command->getId()));
     $category = $this->categoryRepository->findByIdentity(new UuidIdentity($command->getCategory()));
     $product->updateInfo($command->getName(), new Money($command->getPrice()), $category, $command->getDescription(), $command->isAvailable(), $command->getImageUrl());
     $productOptions = $command->getProductOptions();
     foreach ($product->getProductOptions() as $key => $productOption) {
         if (isset($productOptions[$key])) {
             $productOption->changeValue($productOptions[$key]->getValue());
             unset($productOptions[$key]);
         } else {
             $product->getProductOptions()->remove($key);
         }
     }
     foreach ($productOptions as $productOption) {
         $option = $this->optionRepository->getReference(new UuidIdentity($productOption->getOption()));
         $product->addOption($option, $productOption->getValue());
     }
     $this->repository->save($product);
     $event = new ProductSavedEvent($product);
     $this->eventBus->handle($event);
 }
Exemple #22
0
 /**
  * @param string $filename
  *
  * @throws \livetyping\hermitage\foundation\exceptions\ImageNotFoundException
  */
 protected function makeVersion(string $filename)
 {
     $original = Util::original($filename);
     $command = new MakeImageVersionCommand($original, Util::version($filename));
     $this->bus->handle($command);
 }
Exemple #23
0
 public function navAction()
 {
     $query = new GetCartQuery();
     $this->queryBus->handle($query);
     return new Response($this->engine->render(':profile:nav.html.twig', ['cart' => $query->getResult()]));
 }
Exemple #24
0
 public function removeProductAction($id)
 {
     $command = new RemoveProductCommand($id);
     $this->commandBus->handle($command);
     return new Response('', Response::HTTP_NO_CONTENT);
 }
 public function run(OutputInterface $output)
 {
     $output->writeln('**********************************');
     $output->writeln('Starting sync for Events');
     $progressbar = $this->newProgressBar($output);
     $zenIds = $this->doctrine->getRepository('CoderDojoWebsiteBundle:Dojo')->getZenIds();
     $externalEvents = $this->zen->getEvents($zenIds);
     $progressbar->start(count($externalEvents));
     $progressbar->setMessage('Iterating Events...');
     $countNew = 0;
     $countUpdated = 0;
     $countNoMatch = 0;
     foreach ($externalEvents as $externalEvent) {
         $progressbar->setMessage('Handling ' . $externalEvent->getName());
         $internalEvent = $this->doctrine->getRepository('CoderDojoWebsiteBundle:DojoEvent')->findOneBy(['zenId' => $externalEvent->getZenId()]);
         /** @var Dojo $dojo */
         $internalDojo = $this->doctrine->getRepository('CoderDojoWebsiteBundle:Dojo')->findOneBy(['zenId' => $externalEvent->getZenDojoId()]);
         if (null === $internalDojo) {
             $progressbar->setMessage('No internal dojo found!');
             $progressbar->advance();
             $countNoMatch++;
             continue;
         }
         if (null === $internalEvent) {
             $progressbar->setMessage('No internal event found');
             $command = new CreateEventCommand($internalDojo->getId(), $externalEvent->getName(), $externalEvent->getStartTime(), $internalDojo->getZenUrl(), $externalEvent->getZenId(), DojoEvent::TYPE_ZEN);
             $this->commandBus->handle($command);
             $progressbar->advance();
             $countNew++;
         } else {
             $progressbar->setMessage('Internal event found');
             $internalEvent->setName($externalEvent->getName());
             $internalEvent->setDate($externalEvent->getStartTime());
             $internalEvent->setUrl($internalDojo->getZenUrl());
             $progressbar->advance();
             $countUpdated++;
         }
     }
     $progressbar->setMessage('Flushing');
     $this->doctrine->flush();
     $progressbar->setMessage('Finished syncing Events!');
     $progressbar->finish();
     $output->writeln($countNew . ' New events added');
     $output->writeln($countUpdated . ' Existing events updated');
     $output->writeln($countNoMatch . ' events could not be matched with a dojo');
     $message = "Zen synchronizer just handled events.";
     $attachments = [];
     $attachment = new Attachment();
     $attachment->setFallback($countNew . " events added.");
     $attachment->setText($countNew . " events added.");
     $attachment->setColor('good');
     $attachments[] = $attachment;
     $attachment = new Attachment();
     $attachment->setFallback($countUpdated . " events updated.");
     $attachment->setText($countUpdated . " events updated.");
     $attachment->setColor('warning');
     $attachments[] = $attachment;
     $attachment = new Attachment();
     $attachment->setFallback($countNoMatch . " events not matched.");
     $attachment->setText($countNoMatch . " events not matched.");
     $attachment->setColor('danger');
     $attachments[] = $attachment;
     $this->slackService->sendToChannel('#website-nl', $message, $attachments);
 }
 public function consume($serializedEnvelope)
 {
     $envelope = $this->messageInEnvelopeSerializer->unwrapAndDeserialize($serializedEnvelope);
     $this->messageBus->handle($envelope->message());
 }
 function it_handles_a_command(MessageBus $messageBus, $command)
 {
     $messageBus->handle($command)->shouldBeCalled();
     $this->handle($command);
 }
Exemple #28
0
 public function doneAction(Request $request)
 {
     $command = new VerifyRequestCommand($request);
     $this->commandBus->handle($command);
     return new RedirectResponse($this->router->generate('homepage'));
 }
Exemple #29
0
 /**
  * @param string                                   $filename
  * @param \Psr\Http\Message\ServerRequestInterface $request
  * @param \Psr\Http\Message\ResponseInterface      $response
  *
  * @return \Psr\Http\Message\ResponseInterface
  * @throws \livetyping\hermitage\foundation\exceptions\ImageNotFoundException
  */
 public function __invoke(string $filename, Request $request, Response $response) : Response
 {
     $command = new DeleteImageCommand($filename);
     $this->bus->handle($command);
     return $response->withStatus(204);
 }