Пример #1
1
 /**
  * @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());
 }
 /**
  * Bulk generates and inserts full version records for the provided versionable entities
  * in MongoDB.
  * Return an array of ids of documents that have really changed since the last version.
  *
  * @param array $versionables
  *
  * @return array
  */
 public function bulkPersist(array $versionables)
 {
     $versions = [];
     $changedDocIds = [];
     $author = VersionManager::DEFAULT_SYSTEM_USER;
     $event = $this->eventDispatcher->dispatch(BuildVersionEvents::PRE_BUILD, new BuildVersionEvent());
     if (null !== $event && null !== $event->getUsername()) {
         $author = $event->getUsername();
     }
     foreach ($versionables as $versionable) {
         $previousVersion = $this->getPreviousVersion($versionable);
         $context = $this->versionContext->getContextInfo(get_class($versionable));
         $newVersion = $this->versionBuilder->buildVersion($versionable, $author, $previousVersion, $context);
         if (count($newVersion->getChangeSet()) > 0) {
             $versions[] = $newVersion;
             $changedDocIds[] = $versionable->getId();
         }
         if (null !== $previousVersion) {
             $this->documentManager->detach($previousVersion);
         }
     }
     $mongodbVersions = [];
     foreach ($versions as $version) {
         $mongodbVersions[] = $this->normalizer->normalize($version, VersionNormalizer::FORMAT);
     }
     if (count($mongodbVersions) > 0) {
         $collection = $this->documentManager->getDocumentCollection($this->versionClass);
         $collection->batchInsert($mongodbVersions);
     }
     return $changedDocIds;
 }
Пример #3
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);
     }
 }
 /**
  * @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();
 }
 /**
  * {@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);
     }
 }
 /**
  * @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;
 }
Пример #8
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;
 }
Пример #9
0
 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;
 }
Пример #10
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;
 }
 /**
  * @param PostFlushEventArgs $args
  */
 public function postFlush(PostFlushEventArgs $args)
 {
     foreach ($this->sources as $source) {
         $this->dispatcher->dispatch(IoEvents::SOURCE_PROCESS, new SourceEvent($source));
     }
     $this->sources = [];
 }
Пример #12
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;
 }
Пример #13
0
 /**
  * Renders an editor.
  *
  * @param  string $name
  * @param  string $value
  * @param  array  $attributes
  * @param  array  $parameters
  * @return string
  */
 public function render($name, $value, array $attributes = [], $parameters = [])
 {
     if ($editor = $this->events->dispatch('editor.load', new EditorLoadEvent())->getEditor()) {
         return $editor->render($value, array_merge($attributes, compact('name')));
     }
     return __('Editor not found.');
 }
 /**
  * @param GetResponseForExceptionEvent $event
  */
 public function onException(GetResponseForExceptionEvent $event)
 {
     if (!$event->isMasterRequest()) {
         return;
     }
     $this->eventDispatcher->dispatch(Events::REQUEST_ENDS, new RequestEnded($event->getRequest(), $event->getResponse(), $event->getException()));
 }
 /**
  * Transforms an order into an invoice
  *
  * @param OrderInterface   $order
  * @param InvoiceInterface $invoice
  */
 public function transformFromOrder(OrderInterface $order, InvoiceInterface $invoice)
 {
     $event = new OrderTransformEvent($order);
     $this->eventDispatcher->dispatch(TransformerEvents::PRE_ORDER_TO_INVOICE_TRANSFORM, $event);
     $invoice->setName($order->getBillingName());
     $invoice->setAddress1($order->getBillingAddress1());
     $invoice->setAddress2($order->getBillingAddress2());
     $invoice->setAddress3($order->getBillingAddress3());
     $invoice->setCity($order->getBillingCity());
     $invoice->setCountry($order->getBillingCountryCode());
     $invoice->setPostcode($order->getBillingPostcode());
     $invoice->setEmail($order->getBillingEmail());
     $invoice->setFax($order->getBillingFax());
     $invoice->setMobile($order->getBillingMobile());
     $invoice->setPhone($order->getBillingPhone());
     $invoice->setReference($order->getReference());
     $invoice->setCurrency($order->getCurrency());
     $invoice->setCustomer($order->getCustomer());
     $invoice->setTotalExcl($order->getTotalExcl());
     $invoice->setTotalInc($order->getTotalInc());
     $invoice->setPaymentMethod($order->getPaymentMethod());
     $invoice->setLocale($order->getLocale());
     foreach ($order->getOrderElements() as $orderElement) {
         $invoiceElement = $this->createInvoiceElementFromOrderElement($orderElement);
         $invoiceElement->setInvoice($invoice);
         $invoice->addInvoiceElement($invoiceElement);
     }
     if ($order->getDeliveryCost() > 0) {
         $this->addDelivery($invoice, $order);
     }
     $invoice->setStatus(InvoiceInterface::STATUS_OPEN);
     $event = new InvoiceTransformEvent($invoice);
     $this->eventDispatcher->dispatch(TransformerEvents::POST_ORDER_TO_INVOICE_TRANSFORM, $event);
 }
 /**
  * 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;
 }
Пример #17
0
 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);
 }
 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'] = [];
     }
 }
Пример #19
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}
  *
  * 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));
 }
Пример #21
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;
 }
Пример #22
0
 /**
  * {@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.
 }
Пример #23
0
 /**
  * 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());
 }
Пример #24
0
 /**
  * {@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);
 }
Пример #25
0
 /**
  * {@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;
 }
Пример #26
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);
 }
Пример #27
0
 /**
  * {@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);
 }
Пример #28
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();
 }
Пример #29
0
 /**
  * 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();
 }
Пример #30
0
 /**
  * Start the backup.
  *
  * @return bool
  */
 public function execute()
 {
     $successful = true;
     try {
         // Dump all databases
         $this->databaseManager->dump();
         // Backup folders if specified
         $this->logger->info('[dizda-backup] Copying folders.');
         $this->processorManager->copyFolders();
         // Compress everything
         $this->logger->info(sprintf('[dizda-backup] Compressing to archive using %s', $this->processorManager->getName()));
         $this->processorManager->compress();
         // Transfer with all clients
         $this->clientManager->upload($this->processorManager->getArchivePath());
     } catch (\Exception $e) {
         // Write log
         $this->logger->critical('[dizda-backup] Unexpected exception.', array('exception' => $e));
         $successful = false;
     }
     try {
         // If we catch an exception or not, we would still like to try cleaning up after us
         $this->logger->info('[dizda-backup] Cleaning up after us.');
         $this->processorManager->cleanUp();
     } catch (IOException $e) {
         $this->logger->error('[dizda-backup] Cleaning up failed.', array('exception' => $e));
         return false;
     }
     if ($successful) {
         $this->eventDispatcher->dispatch(BackupEvent::BACKUP_COMPLETED, new BackupEvent());
     }
     return $successful;
 }