/**
  * @Route("/{applicationId}")
  * @Method({"GET", "POST"})
  * @Template()
  * @param Request $request
  * @param $applicationId
  * @return array
  */
 public function indexAction(Request $request, $applicationId)
 {
     // Validate the $applicationId, throws Exception if invalid.
     $application = $this->getApplication($this->irisEntityManager, $applicationId);
     // Get the Case for this Tenant and put in the session, as it's needed throughout
     $case = $this->getCase($this->irisEntityManager, $application->getCaseId());
     $request->getSession()->set('submitted-case', serialize($case));
     // Create an empty ReferencingGuarantor object.
     $guarantor = new ReferencingGuarantor();
     $guarantor->setCaseId($application->getCaseId());
     // Build the form.
     $form = $this->createForm($this->formType, $guarantor, array('guarantor_decorator' => $this->referencingGuarantorDecoratorBridgeSubscriber->getGuarantorDecorator(), 'attr' => array('id' => 'generic_step_form', 'class' => 'referencing branded individual-guarantor-form', 'novalidate' => 'novalidate')));
     // Process a client round trip, if necessary
     if ($request->isXmlHttpRequest()) {
         $form->submit($request);
         return $this->render('BarbonHostedApiLandlordReferenceBundle:NewReference/Guarantor/Validate:index.html.twig', array('form' => $form->createView()));
     }
     // Submit the form.
     $form->handleRequest($request);
     if ($form->isValid()) {
         $case = $this->getCase($this->irisEntityManager, $application->getCaseId());
         // Dispatch the new guarantor reference event.
         $this->eventDispatcher->dispatch(NewReferenceEvents::GUARANTOR_REFERENCE_CREATED, new NewGuarantorReferenceEvent($case, $application, $guarantor));
         // Send the user to the success page.
         return $this->redirectToRoute('barbon_hostedapi_landlord_reference_newreference_guarantor_confirmation_index', array('applicationId' => $applicationId));
     }
     return array('form' => $form->createView());
 }
 /**
  * @param PostFlushEventArgs $args
  */
 public function postFlush(PostFlushEventArgs $args)
 {
     foreach ($this->sources as $source) {
         $this->dispatcher->dispatch(IoEvents::SOURCE_PROCESS, new SourceEvent($source));
     }
     $this->sources = [];
 }
Example #3
0
 private function bindRequestListeners(Application $app, EventDispatcherInterface $dispatcher)
 {
     $dispatcher->addSubscriber($app['alchemy_rest.decode_request_listener']);
     $dispatcher->addSubscriber($app['alchemy_rest.paginate_request_listener']);
     $dispatcher->addSubscriber($app['alchemy_rest.sort_request_listener']);
     $dispatcher->addSubscriber($app['alchemy_rest.date_request_listener']);
 }
 /**
  * {@inheritdoc}
  */
 public function visitResult(DatagridConfiguration $config, ResultsObject $result)
 {
     $rows = $result->offsetGetByPath('[data]');
     if (!is_array($rows)) {
         throw new UnexpectedTypeException($rows, 'array');
     }
     $mappingConfig = $this->mapper->getMappingConfig();
     $rows = array_map(function (ResultRecordInterface $record) use($mappingConfig) {
         $entityClass = $record->getValue('entityName');
         $entityId = $record->getValue('recordId');
         $entityConfig = array_key_exists($entityClass, $mappingConfig) ? $entityConfig = $this->mapper->getEntityConfig($entityClass) : [];
         return new ResultItem($this->em, $entityClass, $entityId, null, null, $entityConfig);
     }, $rows);
     $entities = $this->resultFormatter->getResultEntities($rows);
     $resultRows = [];
     /** @var ResultItem $item */
     foreach ($rows as $item) {
         $entityClass = $item->getEntityName();
         $entityId = $item->getRecordId();
         $entity = $entities[$entityClass][$entityId];
         $this->dispatcher->dispatch(PrepareResultItemEvent::EVENT_NAME, new PrepareResultItemEvent($item, $entity));
         $resultRows[] = new ResultRecord(['entity' => $entity, 'indexer_item' => $item]);
     }
     $result->offsetSet('data', $resultRows);
 }
 /**
  * {@inheritdoc}
  */
 public function matchAll(LineItemInterface $line_item, array $line_items)
 {
     $purchased_entity = $line_item->getPurchasedEntity();
     if (empty($purchased_entity)) {
         // Don't support combining line items without a purchased entity.
         return [];
     }
     $comparison_fields = ['type', 'purchased_entity'];
     $event = new LineItemComparisonFieldsEvent($comparison_fields, $line_item);
     $this->event_dispatcher->dispatch(CartEvents::LINE_ITEM_COMPARISON_FIELDS, $event);
     $comparison_fields = $event->getComparisonFields();
     $matched_line_items = [];
     /** @var \Drupal\commerce_order\Entity\LineItemInterface $existing_line_item */
     foreach ($line_items as $existing_line_item) {
         foreach ($comparison_fields as $comparison_field) {
             if (!$existing_line_item->hasField($comparison_field) || !$line_item->hasField($comparison_field)) {
                 // The field is missing on one of the line items.
                 continue 2;
             }
             if ($existing_line_item->get($comparison_field)->getValue() !== $line_item->get($comparison_field)->getValue()) {
                 // Line item doesn't match.
                 continue 2;
             }
         }
         $matched_line_items[] = $existing_line_item;
     }
     return $matched_line_items;
 }
 /**
  * Checks if a node's type requires a redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
 {
     $route_options = $this->routeMatch->getRouteObject()->getOptions();
     $isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
     if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
         $node_type = $this->entityStorage->load($entity->bundle());
         $purl_settings = $node_type->getThirdPartySettings('purl');
         if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
             $url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
             try {
                 $redirect_response = new TrustedRedirectResponse($url->toString());
                 $redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
                 $modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
                 $new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
                 $dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
                 $event->setResponse($new_event->getResponse());
                 return;
             } catch (RedirectLoopException $e) {
                 \Drupal::logger('redirect')->warning($e->getMessage());
                 $response = new Response();
                 $response->setStatusCode(503);
                 $response->setContent('Service unavailable');
                 $event->setResponse($response);
                 return;
             }
         }
     }
 }
 /**
  * @param SiteEvent $event
  */
 public function onSettingUpSite(SiteEvent $event)
 {
     $drupal = $event->getDrupal();
     $this->eventDispatcher->dispatch(WritingSiteSettingsFile::NAME, $settings = new WritingSiteSettingsFile($drupal));
     $this->filesystem->mkdir($drupal->getSitePath());
     file_put_contents($drupal->getSitePath() . '/settings.php', '<?php ' . $settings->getSettings());
 }
 /**
  * Iterate over two-factor providers and ask for two-factor authentication.
  * Each provider can return a response. The first response will be returned.
  *
  * @param AuthenticationContextInterface $context
  *
  * @return Response|null
  */
 public function requestAuthenticationCode(AuthenticationContextInterface $context)
 {
     $token = $context->getToken();
     // Iterate over two-factor providers and ask for completion
     /** @var TwoFactorProviderInterface $provider */
     foreach ($this->providers as $providerName => $provider) {
         if ($this->flagManager->isNotAuthenticated($providerName, $token)) {
             $response = $provider->requestAuthenticationCode($context);
             // Set authentication completed
             if ($context->isAuthenticated()) {
                 $this->eventDispatcher->dispatch(TwoFactorAuthenticationEvents::SUCCESS, new TwoFactorAuthenticationEvent());
                 $this->flagManager->setComplete($providerName, $token);
             } else {
                 if ($context->getRequest()->get($this->authRequestParameter) !== null) {
                     $this->eventDispatcher->dispatch(TwoFactorAuthenticationEvents::FAILURE, new TwoFactorAuthenticationEvent());
                 }
             }
             // Return response
             if ($response instanceof Response) {
                 return $response;
             }
         }
     }
     return null;
 }
 /**
  * {@inheritdoc}
  */
 public function dispatch($eventName, $eventContext = null)
 {
     $symfonyEvent = $this->convertResqueEvent($eventContext);
     $this->symfonyDispatcher->dispatch($eventName, $symfonyEvent);
     // @todo if Resque events ever have mutable context, you would translate the Symfony event changes back
     //       in to the Resque event here.
 }
Example #10
0
 public function onRequest(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher)
 {
     $request = $event->getRequest();
     $modifiers = $this->getModifiers();
     $matches = array();
     foreach ($modifiers as $modifier) {
         $provider = $modifier->getProvider();
         $modifierKey = $modifier->getModifierKey();
         $method = $modifier->getMethod();
         if ($method->contains($request, $modifierKey)) {
             $matches[$provider->getProviderId()] = array('method' => $method, 'modifier' => $modifierKey, 'provider_key' => $provider->getProviderId(), 'provider' => $modifier->getProvider(), 'value' => $modifier->getValue());
         }
     }
     foreach ($matches as $match) {
         if (!$match['method'] instanceof RequestAlteringInterface) {
             continue;
         }
         $match['method']->alterRequest($request, $match['modifier']);
         $this->reinitializeRequest($request);
     }
     foreach ($matches as $match) {
         $event = new ModifierMatchedEvent($request, $match['provider_key'], $match['method'], $match['modifier'], $match['value']);
         $dispatcher->dispatch(PurlEvents::MODIFIER_MATCHED, $event);
         $this->matchedModifiers->add($event);
     }
     $request->attributes->set('purl.matched_modifiers', $matches);
 }
 /**
  * {@inheritdoc}
  *
  * Override to do a massive save for the products
  */
 public function saveAll(array $products, array $options = [])
 {
     if (empty($products)) {
         return;
     }
     $this->collection = $this->objectManager->getDocumentCollection($this->productClass);
     $this->eventDispatcher->dispatch(StorageEvents::PRE_SAVE_ALL, new GenericEvent($products));
     $allOptions = $this->optionsResolver->resolveSaveAllOptions($options);
     // TODO check the "schedule" options to remove the completeness or not
     // TODO manage the "recalculate" options
     $productsToInsert = [];
     $productsToUpdate = [];
     foreach ($products as $product) {
         if (null === $product->getId()) {
             $productsToInsert[] = $product;
             $product->setId($this->mongoFactory->createMongoId());
         } else {
             $productsToUpdate[] = $product;
         }
     }
     $insertDocs = $this->getDocsFromProducts($productsToInsert);
     $updateDocs = $this->getDocsFromProducts($productsToUpdate);
     if (count($insertDocs) > 0) {
         $this->insertDocuments($insertDocs);
     }
     if (count($updateDocs) > 0) {
         $this->updateDocuments($updateDocs);
     }
     $this->versionPersister->bulkPersist($products);
     $this->eventDispatcher->dispatch(StorageEvents::POST_SAVE_ALL, new GenericEvent($products));
 }
 public function collectRuntimeJavaScripts(CollectAssetsEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
 {
     if ($eventName == ThemePlusEvents::COLLECT_HEAD_JAVASCRIPT_ASSETS && $event->getLayout()->theme_plus_default_javascript_position != 'head' || $eventName == ThemePlusEvents::COLLECT_BODY_JAVASCRIPT_ASSETS && $event->getLayout()->theme_plus_default_javascript_position != 'body') {
         return;
     }
     if (is_array($GLOBALS['TL_JAVASCRIPT']) && !empty($GLOBALS['TL_JAVASCRIPT'])) {
         foreach ($GLOBALS['TL_JAVASCRIPT'] as $javaScript) {
             if ($javaScript instanceof AssetInterface) {
                 $event->append($javaScript);
             } else {
                 list($javaScript, $mode) = explode('|', $javaScript);
                 $stripStaticDomainEvent = new StripStaticDomainEvent($event->getRenderMode(), $event->getPage(), $event->getLayout(), $javaScript);
                 $eventDispatcher->dispatch(ThemePlusEvents::STRIP_STATIC_DOMAIN, $stripStaticDomainEvent);
                 $javaScript = $stripStaticDomainEvent->getUrl();
                 $asset = new ExtendedFileAsset(TL_ROOT . '/' . $javaScript, [], TL_ROOT, $javaScript);
                 $asset->setStandalone($mode != 'static');
                 $generateAssetPathEvent = new GenerateAssetPathEvent($event->getRenderMode(), $event->getPage(), $event->getLayout(), $asset, $event->getDefaultFilters(), 'js');
                 $eventDispatcher->dispatch(ThemePlusEvents::GENERATE_ASSET_PATH, $generateAssetPathEvent);
                 $asset->setTargetPath($generateAssetPathEvent->getPath());
                 $event->append($asset);
             }
         }
         $GLOBALS['TL_JAVASCRIPT'] = [];
     }
 }
 public function load($data)
 {
     if (!$this->supports($data)) {
         throw new \InvalidArgumentException(sprintf('NodeLoader can only handle data implementing NodeInterface, "%s" given.', is_object($data) ? get_class($data) : gettype($data)));
     }
     $event = new CreateMenuItemFromNodeEvent($data);
     $this->dispatcher->dispatch(Events::CREATE_ITEM_FROM_NODE, $event);
     if ($event->isSkipNode()) {
         if ($data instanceof Menu) {
             // create an empty menu root to avoid the knp menu from failing.
             return $this->menuFactory->createItem('');
         }
         return;
     }
     $item = $event->getItem() ?: $this->menuFactory->createItem($data->getName(), $data->getOptions());
     if (empty($item)) {
         return;
     }
     if ($event->isSkipChildren()) {
         return $item;
     }
     foreach ($data->getChildren() as $childNode) {
         if ($childNode instanceof NodeInterface) {
             $child = $this->load($childNode);
             if (!empty($child)) {
                 $item->addChild($child);
             }
         }
     }
     return $item;
 }
Example #14
0
 /**
  * Create, configure and build datagrid
  *
  * @param DatagridConfiguration $config
  * @param ParameterBag          $parameters
  *
  * @return DatagridInterface
  */
 public function build(DatagridConfiguration $config, ParameterBag $parameters)
 {
     /**
      * @TODO: should be refactored in BAP-6849
      */
     $minified = $parameters->get(ParameterBag::MINIFIED_PARAMETERS);
     if (is_array($minified) && array_key_exists('g', $minified) && is_array($minified['g'])) {
         $gridParams = [];
         foreach ($minified['g'] as $gridParamName => $gridParamValue) {
             $gridParams[$gridParamName] = $gridParamValue;
         }
         $parameters->add($gridParams);
     }
     /**
      * @TODO: should be refactored in BAP-6826
      */
     $event = new PreBuild($config, $parameters);
     $this->eventDispatcher->dispatch(PreBuild::NAME, $event);
     $class = $config->offsetGetByPath(self::BASE_DATAGRID_CLASS_PATH, $this->baseDatagridClass);
     $name = $config->getName();
     /** @var DatagridInterface $datagrid */
     $datagrid = new $class($name, $config, $parameters);
     $datagrid->setScope($config->offsetGetOr('scope'));
     $event = new BuildBefore($datagrid, $config);
     $this->eventDispatcher->dispatch(BuildBefore::NAME, $event);
     $acceptor = $this->createAcceptor($config, $parameters);
     $datagrid->setAcceptor($acceptor);
     $this->buildDataSource($datagrid, $config);
     $acceptor->processConfiguration();
     $event = new BuildAfter($datagrid);
     $this->eventDispatcher->dispatch(BuildAfter::NAME, $event);
     return $datagrid;
 }
 public function subscribe(Container $app, EventDispatcherInterface $dispatcher)
 {
     $dispatcher->addSubscriber(new ResponseListener($app['charset']));
     $dispatcher->addSubscriber(new MiddlewareListener($app['app']));
     $dispatcher->addSubscriber(new ConverterListener($app['routes'], $app['callback_resolver']));
     $dispatcher->addSubscriber(new StringToResponseListener());
 }
Example #16
0
 protected function getElement(NodeInterface $node)
 {
     $this->eventDispatcher->dispatch(Events::preRender($node));
     // XML fragment?
     if ($node instanceof FragmentInterface) {
         return $this->appendXML($node->getNodeValue());
     }
     // Create
     $element = $this->document->createElement($node->getNodeName());
     // Value
     if ($node->getNodeValue() !== null) {
         $element->appendChild($this->document->createTextNode($node->getNodeValue()));
     }
     // Attributes
     foreach ($node->getAttributes() as $name => $value) {
         $element->setAttribute($name, $value);
     }
     // Children
     foreach ($node->getChildren() as $child) {
         $subelement = $this->getElement($child);
         $element->appendChild($subelement);
     }
     $this->eventDispatcher->dispatch(Events::postRender($node));
     return $element;
 }
Example #17
0
 /**
  * @param OrderInterface  $order
  * @param BasketInterface $basket
  *
  * @return BasketInterface
  */
 public function transformIntoBasket(OrderInterface $order, BasketInterface $basket)
 {
     $event = new OrderTransformEvent($order);
     $this->eventDispatcher->dispatch(TransformerEvents::PRE_ORDER_TO_BASKET_TRANSFORM, $event);
     // we reset the current basket
     $basket->reset(true);
     $basket->setCurrency($order->getCurrency());
     $basket->setLocale($order->getLocale());
     // We are free to convert !
     foreach ($order->getOrderElements() as $orderElement) {
         /*
          * @var $orderElement OrderElementInterface
          */
         $provider = $this->productPool->getProvider($orderElement->getProductType());
         $manager = $this->productPool->getManager($orderElement->getProductType());
         $product = $manager->findOneBy(array('id' => $orderElement->getProductId()));
         if (!$product) {
             continue;
         }
         $basketElement = $provider->createBasketElement($product, $orderElement->getOptions());
         $basketElement->setQuantity($orderElement->getQuantity());
         $provider->basketAddProduct($basket, $product, $basketElement);
     }
     $basket->setCustomer($order->getCustomer());
     $basket->buildPrices();
     $event = new BasketTransformEvent($basket);
     $this->eventDispatcher->dispatch(TransformerEvents::POST_ORDER_TO_BASKET_TRANSFORM, $event);
     return $basket;
 }
 /**
  * {@inheritDoc}
  */
 public function visitMetadata(DatagridConfiguration $config, MetadataObject $data)
 {
     $params = $this->getParameters()->get(ParameterBag::ADDITIONAL_PARAMETERS, []);
     $currentView = isset($params[self::VIEWS_PARAM_KEY]) ? $params[self::VIEWS_PARAM_KEY] : null;
     $data->offsetAddToArray('initialState', ['gridView' => '__all__']);
     $data->offsetAddToArray('state', ['gridView' => $currentView]);
     $allLabel = null;
     if (isset($config['options']) && isset($config['options']['gridViews']) && isset($config['options']['gridViews']['allLabel'])) {
         $allLabel = $this->translator->trans($config['options']['gridViews']['allLabel']);
     }
     /** @var AbstractViewsList $list */
     $list = $config->offsetGetOr(self::VIEWS_LIST_KEY, false);
     $gridViews = ['choices' => [['label' => $allLabel, 'value' => '__all__']], 'views' => [(new View('__all__'))->getMetadata()]];
     if ($list !== false) {
         $configuredGridViews = $list->getMetadata();
         $configuredGridViews['views'] = array_merge($gridViews['views'], $configuredGridViews['views']);
         $configuredGridViews['choices'] = array_merge($gridViews['choices'], $configuredGridViews['choices']);
         $gridViews = $configuredGridViews;
     }
     if ($this->eventDispatcher->hasListeners(GridViewsLoadEvent::EVENT_NAME)) {
         $event = new GridViewsLoadEvent($config->getName(), $gridViews);
         $this->eventDispatcher->dispatch(GridViewsLoadEvent::EVENT_NAME, $event);
         $gridViews = $event->getGridViews();
     }
     $gridViews['gridName'] = $config->getName();
     $gridViews['permissions'] = $this->getPermissions();
     $data->offsetSet('gridViews', $gridViews);
 }
Example #19
0
 /**
  * Create, configure and build datagrid
  *
  * @param DatagridConfiguration $config
  *
  * @return DatagridInterface
  */
 public function build(DatagridConfiguration $config)
 {
     $class = $config->offsetGetByPath(self::BASE_DATAGRID_CLASS_PATH, $this->baseDatagridClass);
     $name = $config->getName();
     /** @var Acceptor $acceptor */
     $acceptor = new $this->acceptorClass($config);
     /** @var DatagridInterface $datagrid */
     $datagrid = new $class($name, $acceptor);
     $event = new BuildBefore($datagrid, $config);
     $this->eventDispatcher->dispatch(BuildBefore::NAME, $event);
     // duplicate event dispatch with grid name
     $this->eventDispatcher->dispatch(BuildBefore::NAME . '.' . $name, $event);
     $this->buildDataSource($datagrid, $config);
     foreach ($this->extensions as $extension) {
         if ($extension->isApplicable($config)) {
             $acceptor->addExtension($extension);
         }
     }
     $acceptor->processConfiguration();
     $event = new BuildAfter($datagrid);
     $this->eventDispatcher->dispatch(BuildAfter::NAME, $event);
     // duplicate event dispatch with grid name
     $this->eventDispatcher->dispatch(BuildAfter::NAME . '.' . $name, $event);
     return $datagrid;
 }
Example #20
0
 /**
  * Attempts to log the authenticated CAS user into Drupal.
  *
  * This method should be used to login a user after they have successfully
  * authenticated with the CAS server.
  *
  * @param CasPropertyBag $property_bag
  *   CasPropertyBag containing username and attributes from CAS.
  *
  * @throws CasLoginException
  */
 public function loginToDrupal(CasPropertyBag $property_bag, $ticket)
 {
     $this->eventDispatcher->dispatch(CasHelper::CAS_PROPERTY_ALTER, new CasPropertyEvent($property_bag));
     $account = $this->userLoadByName($property_bag->getUsername());
     if (!$account) {
         $config = $this->settings->get('cas.settings');
         if ($config->get('user_accounts.auto_register') === TRUE) {
             if (!$property_bag->getRegisterStatus()) {
                 $_SESSION['cas_temp_disable'] = TRUE;
                 throw new CasLoginException("Cannot register user, an event listener denied access.");
             }
             $account = $this->registerUser($property_bag->getUsername());
         } else {
             throw new CasLoginException("Cannot login, local Drupal user account does not exist.");
         }
     }
     $this->eventDispatcher->dispatch(CasHelper::CAS_USER_ALTER, new CasUserEvent($account, $property_bag));
     $account->save();
     if (!$property_bag->getLoginStatus()) {
         $_SESSION['cas_temp_disable'] = TRUE;
         throw new CasLoginException("Cannot login, an event listener denied access.");
     }
     $this->userLoginFinalize($account);
     $this->storeLoginSessionData($this->sessionManager->getId(), $ticket);
 }
 /**
  * GET /order/{orderId}
  *
  * @param $orderId
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function getDetails($orderId)
 {
     $event = new OrderEvent();
     $event->setOrderId($orderId);
     $this->eventDispatcher->dispatch(OrderEvent::GET_DETAILS, $event);
     return new JsonResponse($event->getOrder());
 }
Example #22
0
 /**
  * Builds the JSON-LD context for the given resource.
  *
  * @param ResourceInterface|null $resource
  *
  * @return array
  */
 public function getContext(ResourceInterface $resource = null)
 {
     $context = $this->getBaseContext();
     $event = new ContextBuilderEvent($context, $resource);
     $this->eventDispatcher->dispatch(Event\Events::CONTEXT_BUILDER, $event);
     return $event->getContext();
 }
 /**
  * {@inheritdoc}
  */
 protected function sendInternalRequests(array $internalRequests, $success, $error)
 {
     if (!empty($internalRequests)) {
         $this->eventDispatcher->dispatch(Events::MULTI_PRE_SEND, $multiPreSendEvent = new MultiPreSendEvent($this, $internalRequests));
         $internalRequests = $multiPreSendEvent->getRequests();
     }
     $exceptions = array();
     try {
         $responses = $this->decorate('sendRequests', array($internalRequests));
     } catch (MultiHttpAdapterException $e) {
         $responses = $e->getResponses();
         $exceptions = $e->getExceptions();
     }
     if (!empty($responses)) {
         $this->eventDispatcher->dispatch(Events::MULTI_POST_SEND, $postSendEvent = new MultiPostSendEvent($this, $responses));
         $exceptions = array_merge($exceptions, $postSendEvent->getExceptions());
         $responses = $postSendEvent->getResponses();
     }
     if (!empty($exceptions)) {
         $this->eventDispatcher->dispatch(Events::MULTI_EXCEPTION, $exceptionEvent = new MultiExceptionEvent($this, $exceptions));
         $responses = array_merge($responses, $exceptionEvent->getResponses());
         $exceptions = $exceptionEvent->getExceptions();
     }
     foreach ($responses as $response) {
         call_user_func($success, $response);
     }
     foreach ($exceptions as $exception) {
         call_user_func($error, $exception);
     }
 }
 /**
  * Returns the image sizes for the given user suitable for widgets.
  *
  * @param BackendUser $user
  *
  * @return array
  */
 public function getOptionsForUser(BackendUser $user)
 {
     $this->loadOptions();
     $event = new ImageSizesEvent($user->isAdmin ? $this->options : $this->filterOptions(\StringUtil::deserialize($user->imageSizes, true)), $user);
     $this->eventDispatcher->dispatch(ContaoCoreEvents::IMAGE_SIZES_USER, $event);
     return $event->getImageSizes();
 }
 /**
  * @param ExampleNode $example
  *
  * @return int
  */
 public function run(ExampleNode $example)
 {
     $startTime = microtime(true);
     $this->dispatcher->dispatch('beforeExample', new ExampleEvent($example));
     try {
         $this->executeExample($example->getSpecification()->getClassReflection()->newInstance(), $example);
         $status = ExampleEvent::PASSED;
         $exception = null;
     } catch (ExampleException\PendingException $e) {
         $status = ExampleEvent::PENDING;
         $exception = $e;
     } catch (ExampleException\SkippingException $e) {
         $status = ExampleEvent::SKIPPED;
         $exception = $e;
     } catch (ProphecyException\Prediction\PredictionException $e) {
         $status = ExampleEvent::FAILED;
         $exception = $e;
     } catch (ExampleException\FailureException $e) {
         $status = ExampleEvent::FAILED;
         $exception = $e;
     } catch (Exception $e) {
         $status = ExampleEvent::BROKEN;
         $exception = $e;
     }
     if ($exception instanceof PhpSpecException) {
         $exception->setCause($example->getFunctionReflection());
     }
     $runTime = microtime(true) - $startTime;
     $this->dispatcher->dispatch('afterExample', $event = new ExampleEvent($example, $runTime, $status, $exception));
     return $event->getResult();
 }
 public function subscribe(Container $container, EventDispatcherInterface $dispatcher)
 {
     $dispatcher->addSubscriber($container['session.listener']);
     if ($container['session.test']) {
         $container['event_dispatcher']->addSubscriber($container['session.listener.test']);
     }
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function runTasks()
 {
     $executions = $this->taskExecutionRepository->findScheduled();
     foreach ($executions as $execution) {
         $handler = $this->taskHandlerFactory->create($execution->getHandlerClass());
         $start = microtime(true);
         $execution->setStartTime(new \DateTime());
         $execution->setStatus(TaskStatus::RUNNING);
         $this->taskExecutionRepository->save($execution);
         try {
             $this->eventDispatcher->dispatch(Events::TASK_BEFORE, new TaskExecutionEvent($execution->getTask(), $execution));
             $result = $handler->handle($execution->getWorkload());
             $execution->setStatus(TaskStatus::COMPLETED);
             $execution->setResult($result);
             $this->eventDispatcher->dispatch(Events::TASK_PASSED, new TaskExecutionEvent($execution->getTask(), $execution));
         } catch (\Exception $ex) {
             $execution->setException($ex->__toString());
             $execution->setStatus(TaskStatus::FAILED);
             $this->eventDispatcher->dispatch(Events::TASK_FAILED, new TaskExecutionEvent($execution->getTask(), $execution));
         }
         $execution->setEndTime(new \DateTime());
         $execution->setDuration(microtime(true) - $start);
         $this->eventDispatcher->dispatch(Events::TASK_FINISHED, new TaskExecutionEvent($execution->getTask(), $execution));
         $this->taskExecutionRepository->save($execution);
     }
 }
 /**
  * This will save the entity to the database as well as
  * dispatch the event `bitcoin_wallet.update`
  *
  * @param BitcoinWallet $wallet
  *
  * @return BitcoinWallet
  */
 public function update(BitcoinWallet $wallet)
 {
     $this->dispatcher->dispatch('bitcoin_wallet.update', new GenericEvent($wallet));
     $this->em->persist($wallet);
     $this->em->flush();
     return $wallet;
 }
 public function testShouldDispatchEvents()
 {
     $notification = Email::create();
     $notifyArg = Argument::allOf(Argument::type(Email::class), Argument::that(function ($arg) use($notification) {
         return $arg !== $notification;
     }));
     $handler = $this->prophesize(NotificationHandlerInterface::class);
     $handler->getName()->willReturn('default');
     $handler->supports(Argument::any())->willReturn(true);
     $handler->notify($notifyArg)->willReturn();
     $handler2 = $this->prophesize(NotificationHandlerInterface::class);
     $handler2->getName()->willReturn('default');
     $handler2->supports(Argument::any())->willReturn(true);
     $handler2->notify($notifyArg)->willReturn();
     $this->dispatcher->dispatch('notifire.pre_notify', Argument::type(PreNotifyEvent::class))->shouldBeCalled();
     $this->dispatcher->dispatch('notifire.notify', Argument::that(function ($arg) use($notification) {
         if (!$arg instanceof NotifyEvent) {
             return false;
         }
         $not = $arg->getNotification();
         return $not !== $notification;
     }))->shouldBeCalledTimes(2);
     $this->dispatcher->dispatch('notifire.post_notify', Argument::type(PostNotifyEvent::class))->shouldBeCalled();
     $this->manager->addHandler($handler->reveal());
     $this->manager->addHandler($handler2->reveal());
     $this->manager->notify($notification);
 }
Example #30
0
 /**
  * Connects to the database.
  *
  * @return boolean
  */
 public function connect()
 {
     if ($connected = $this->connection->connect()) {
         $this->events->dispatch(Events::postConnect, new Event\ConnectionEvent($this));
     }
     return $connected;
 }