/** * @param string $queue * @return BackendInterface */ public function getBackend($queue) { $type = null; if ($queue != $this->defaultQueue) { if (!$this->backend instanceof QueueDispatcherInterface) { throw new \RuntimeException(sprintf('Unable to provide sonata backend for queue %s', $queue)); } if ($this->backend instanceof MessageManagerBackendDispatcher) { $queueConfig = $this->getQueueConfig($this->backend, $queue); if (!isset($queueConfig['types']) || !is_array($queueConfig['types']) || empty($queueConfig['types'])) { throw new \RuntimeException('Invalid sonata queue configuration'); } $type = $queueConfig['types'][0]; } elseif ($this->backend instanceof AMQPBackendDispatcher) { $queueConfig = $this->getQueueConfig($this->backend, $queue); if (!isset($queueConfig['routing_key']) || empty($queueConfig['routing_key'])) { throw new \RuntimeException('Invalid sonata queue configuration'); } $type = $queueConfig['routing_key']; } else { throw new \RuntimeException('Unknown backend ' . get_class($this->backend)); } } if ($this->backend instanceof QueueDispatcherInterface) { return $this->backend->getBackend($type); } return $this->backend; }
/** * @return BackendInterface */ protected function getDefaultBackend() { $types = array(); if (!empty($this->dedicatedTypes)) { $types = array('exclude' => $this->dedicatedTypes); } $this->default->setTypes($types); return $this->default; }
/** * {@inheritdoc} */ public function process(ConsumerEvent $event) { $order = $this->getOrder($event); $transaction = $this->getTransaction($event); $orderElements = $order->getOrderElements(); foreach ($orderElements as $orderElement) { $this->backend->createAndPublish('sonata_payment_order_element_process', array('product_id' => $orderElement->getProductId(), 'transaction_status' => $transaction->getStatusCode(), 'order_status' => $order->getStatus(), 'quantity' => $orderElement->getQuantity(), 'product_type' => $orderElement->getProductType())); } }
/** * @param PageInterface $object */ protected function sendMessage($object) { if ($object instanceof BlockInterface && method_exists($object, 'getPage')) { $pageId = $object->getPage()->getId(); } elseif ($object instanceof PageInterface) { $pageId = $object->getId(); } else { return; } $this->backend->createAndPublish('sonata.page.create_snapshot', array('pageId' => $pageId)); }
/** * Hook which sends a notification on a published notification failure * * @param AuthenticationAttemptEvent $event */ public function onAuthenticationFailure(AuthenticationAttemptEvent $event) { $user = $event->getUser(); $report = $event->getReport(); $defaultParameters = ['user' => $user, 'override_locale' => true]; if (1 < ($attempts = $report->getAttempts())) { $defaultParameters['content'] = 'notification.auth.failures'; $defaultParameters['parameters'] = ['translation_defaults' => ['%times%' => $attempts]]; } else { $defaultParameters['content'] = 'notification.auth.single_failure'; } $this->publisher->createAndPublish('sen_mailer', $defaultParameters); }
/** * Publishes a message to the backend. * * @param Message $message * @return void * @throws \RuntimeException If publishing fails */ public function produce(Message $message) { $type = $message->getType(); $body = array('ticket' => $message->getTicket()); try { $this->logger->debug(sprintf('Publish message for job %s to sonata backend', $message->getTicket()), ['type' => $type, 'body' => $body]); $queue = $this->registry->get($message->getType())->getQueue(); $this->backendProvider->getBackend($queue)->createAndPublish($type, $body); } catch (\Exception $e) { $this->logger->error(sprintf('Failed to publish message (Error: %s)', $e->getMessage()), ['exception' => $e]); if (!$e instanceof \RuntimeException) { $e = new \RuntimeException($e->getMessage(), $e->getCode(), $e); } throw $e; } }
/** * Creates snapshots of all pages. * * @ApiDoc( * statusCodes={ * 200="Returned when snapshots are successfully queued for creation", * 400="Returned when an error has occurred while snapshots creation", * } * ) * * @return \FOS\RestBundle\View\View * * @throws NotFoundHttpException */ public function postPagesSnapshotsAction() { $sites = $this->siteManager->findAll(); foreach ($sites as $site) { $this->backend->createAndPublish('sonata.page.create_snapshot', array('siteId' => $site->getId())); } return array('queued' => true); }
public function testConsumeIteratesOverAllMessages() { $queue = 'foobar'; $message = $this->createMock(MessageInterface::class); $iterator = new TestIterator([$message, $message]); $this->backendProvider->expects($this->any())->method('getBackend')->with($queue)->willReturn($this->backend); $this->backend->expects($this->any())->method('getIterator')->willReturn($iterator); $this->backend->expects($this->exactly(2))->method('handle'); // the $iterator does not pop elements so we have to make sure ->tick() does not iterate over the same array multiple times $this->subject->consume($queue, ['stop-when-empty' => true]); }
/** * {@inheritdoc} */ public function getPaymentCallbackResponse(Request $request) { // retrieve the transaction $transaction = $this->createTransaction($request); $order = $this->getValidOrder($transaction); // start the payment callback $response = $this->getPayment($transaction->getPaymentCode())->callback($transaction); $this->transactionManager->save($transaction); $this->orderManager->save($order); $this->notificationBackend->createAndPublish('sonata_payment_order_process', array('order_id' => $order->getId(), 'transaction_id' => $transaction->getId())); return $response; }
protected function tick(BackendInterface $backend, array $options = []) { $this->configure($options); $iterator = $backend->getIterator(); foreach ($iterator as $message) { if ($this->controller->doPause()) { return true; } if ($this->controller->doStop()) { return false; } if (microtime(true) > $this->options['max-runtime']) { return false; } $backend->handle($message, $this->notificationDispatcher); $this->eventDispatcher->dispatch(IterateEvent::EVENT_NAME, new IterateEvent($iterator, $backend, $message)); if (null !== $this->options['max-messages'] && !(bool) --$this->options['max-messages']) { return false; } } return !$this->options['stop-when-empty']; }
/** * Hook at the reset password process * * @param ResetPasswordEvent $event */ public function onPasswordReset(ResetPasswordEvent $event) { $this->publisher->createAndPublish('sen_mailer', ['user' => $event->getUser(), 'content' => 'notification.password_reset', 'parameters' => ['translation_defaults' => ['%new_password%' => $event->getNewRawPassword()]], 'override_locale' => true]); }
/** * {@inheritdoc} */ public function generate(MediaProviderInterface $provider, MediaInterface $media) { $this->backend->createAndPublish('sonata.media.create_thumbnail', array('thumbnailId' => $this->id, 'mediaId' => $media->getId(), 'providerReference' => $media->getProviderReference())); }
/** * {@inheritdoc} */ public function check() { return $this->backend->getStatus(); }
/** * Sends a welcome email on registration * * @param CreateUserEvent $event */ public function postUserRegistration(CreateUserEvent $event) { $user = $event->getUser(); $this->notificationPublisher->createAndPublish('sen_mailer', ['user' => $user, 'config_path' => 'SententiaregumApp:registration', 'parameters' => ['code' => $event->getActivationKey(), 'name' => $event->getUser()->getCredentials()->getUsername()], 'override_locale' => true]); }
/** * @param InputInterface $input * @param OutputInterface $output * @param BackendInterface $backend * @param $showDetails * @param $startMemoryUsage */ protected function iterate(InputInterface $input, OutputInterface $output, BackendInterface $backend, $showDetails, $startMemoryUsage) { $iterator = $backend->getIterator(); foreach ($iterator as $message) { if (!$message instanceof MessageInterface) { throw new \RuntimeException('The iterator must return a MessageInterface instance'); } if (!$message->getType()) { $output->write("<error>Skipping : no type defined </error>"); continue; } $date = new \DateTime(); $output->write(sprintf("[%s] <info>%s</info>", $date->format('r'), $message->getType())); $memoryUsage = memory_get_usage(true); try { $start = microtime(true); $returnInfos = $backend->handle($message, $this->getNotificationDispatcher()); $currentMemory = memory_get_usage(true); $output->writeln(sprintf("<comment>OK! </comment> - %0.04fs, %ss, %s, %s - %s = %s, %0.02f%%", microtime(true) - $start, $date->format('U') - $message->getCreatedAt()->format('U'), $this->formatMemory($currentMemory - $memoryUsage), $this->formatMemory($currentMemory), $this->formatMemory($startMemoryUsage), $this->formatMemory($currentMemory - $startMemoryUsage), ($currentMemory - $startMemoryUsage) / $startMemoryUsage * 100)); if ($showDetails && null !== $returnInfos) { $output->writeln($returnInfos->getReturnMessage()); } } catch (HandlingException $e) { $output->writeln(sprintf("<error>KO! - %s</error>", $e->getPrevious()->getMessage())); } catch (\Exception $e) { $output->writeln(sprintf("<error>KO! - %s</error>", $e->getMessage())); } $this->getEventDispatcher()->dispatch(IterateEvent::EVENT_NAME, new IterateEvent($iterator, $backend, $message)); } }