/** * @param Response\ResponseInterface $response * @param string $command */ public function postDispatch(Response\ResponseInterface $response, $command) { $eventName = sprintf('beanstalk.post.dispatch.%s', str_replace('-', '.', $command)); if (!is_null($this->dispatcher) && $this->dispatcher->hasListeners($eventName)) { $this->dispatcher->dispatch($eventName, new Event\PostDispatchEvent($response)); } }
/** * {@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); }
/** * @@inheritdoc */ public function readLine() { $read = parent::readLine(); if (!is_null($this->dispatcher) && $this->dispatcher->hasListeners(BeanstalkEvents::STREAM_READ)) { $this->dispatcher->dispatch(BeanstalkEvents::STREAM_READ, new StreamReadEvent($read, $this->getTimeStamp())); } return $read; }
/** * @param array $options * * @return array */ public function updateSegmentConditionBuilderOptions(array $options) { if (!$this->dispatcher->hasListeners(ConditionBuilderOptionsLoadEvent::EVENT_NAME)) { return $options; } $event = new ConditionBuilderOptionsLoadEvent($options); $this->dispatcher->dispatch(ConditionBuilderOptionsLoadEvent::EVENT_NAME, $event); return $event->getOptions(); }
/** * Form validated and can be processed. */ protected function onSuccess() { /** @var Mailbox $mailbox */ $mailbox = $this->form->getData(); $this->getEntityManager()->persist($mailbox); $this->getEntityManager()->flush(); if ($this->dispatcher->hasListeners(MailboxSaved::NAME)) { $this->dispatcher->dispatch(MailboxSaved::NAME, new MailboxSaved($mailbox)); } }
/** * @param FormView $view * * @return array */ public function getThemes(FormView $view) { $themes = [static::DEFAULT_THEME]; if (!$this->dispatcher->hasListeners(LoadIntegrationThemesEvent::NAME)) { return $themes; } $event = new LoadIntegrationThemesEvent($view, $themes); $this->dispatcher->dispatch(LoadIntegrationThemesEvent::NAME, $event); return $event->getThemes(); }
protected function renderNotifications($notificationsViews) { $views = []; $colorChooser = $this->buildColorChooser(); $unviewedNotificationIds = []; foreach ($notificationsViews as $notificationView) { $notification = $notificationView->getNotification(); $iconKey = $notification->getIconKey(); if (!empty($iconKey)) { $notificationColor = $colorChooser->getColorForName($iconKey); $notification->setIconColor($notificationColor); } $eventName = 'create_notification_item_' . $notification->getActionKey(); $event = new NotificationCreateDelegateViewEvent($notificationView, $this->platformName); /* @var EventDispatcher $eventDispatcher */ if ($this->eventDispatcher->hasListeners($eventName)) { $event = $this->eventDispatcher->dispatch($eventName, $event); $views[$notificationView->getId() . ''] = $event->getResponseContent(); } if ($notificationView->getStatus() === false) { array_push($unviewedNotificationIds, $notificationView->getId()); } } $this->markNotificationsAsViewed($unviewedNotificationIds); return ['views' => $views, 'colors' => $colorChooser->getColorObjectArray()]; }
/** * {@inheritdoc} */ public function visitMetadata(DatagridConfiguration $config, MetadataObject $data) { $currentViewId = $this->getCurrentViewId($config->getName()); $this->setDefaultParams($config->getName()); $data->offsetAddToArray('initialState', ['gridView' => self::DEFAULT_VIEW_ID]); $data->offsetAddToArray('state', ['gridView' => $currentViewId]); $allLabel = null; if (isset($config['options'], $config['options']['gridViews'], $config['options']['gridViews']['allLabel'])) { $allLabel = $this->translator->trans($config['options']['gridViews']['allLabel']); } /** @var AbstractViewsList $list */ $list = $config->offsetGetOr(self::VIEWS_LIST_KEY, false); $systemGridView = new View(self::DEFAULT_VIEW_ID); $systemGridView->setDefault($this->getDefaultViewId($config->getName()) === null); $gridViews = ['choices' => [['label' => $allLabel, 'value' => self::DEFAULT_VIEW_ID]], 'views' => [$systemGridView->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->offsetAddToArray('gridViews', $gridViews); }
/** * @deprecated since 1.9. Should be removed together with deprecated events * @see Oro\Bundle\EntityConfigBundle\Event\Events * * @param string $eventName * * @return bool */ private function hasListeners($eventName) { if (!isset($this->hasListenersCache[$eventName])) { $this->hasListenersCache[$eventName] = $this->eventDispatcher->hasListeners($eventName); } return $this->hasListenersCache[$eventName]; }
/** * Dispatches an event to all registered listeners. * * @param string $eventName The name of the event to dispatch * @param Event $event The event to pass to the event handlers/listeners. */ private function dispatchEvent($eventName, Event $event) { if (!$this->dispatcher->hasListeners($eventName)) { return; } $this->dispatcher->dispatch($eventName, $event); }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param $providerKey * * @return UsernamePasswordToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $authenticated = false; $authenticationService = null; $response = null; $failedAuthMessage = null; $user = $token->getUser(); $authenticatingService = $token instanceof PluginToken ? $token->getAuthenticatingService() : null; if (!$user instanceof User) { try { $user = $userProvider->loadUserByUsername($token->getUsername()); } catch (UsernameNotFoundException $e) { } // Will try with the given password unless the plugin explicitly failed authentication $tryWithPassword = true; // Try authenticating with a plugin first if ($this->dispatcher->hasListeners(UserEvents::USER_FORM_AUTHENTICATION)) { $integrations = $this->integrationHelper->getIntegrationObjects($authenticatingService, ['sso_form'], false, null, true); $authEvent = new AuthenticationEvent($user, $token, $userProvider, $this->request, false, $authenticatingService, $integrations); $this->dispatcher->dispatch(UserEvents::USER_FORM_AUTHENTICATION, $authEvent); if ($authenticated = $authEvent->isAuthenticated()) { $user = $authEvent->getUser(); $authenticatingService = $authEvent->getAuthenticatingService(); } elseif ($authEvent->isFailed()) { $tryWithPassword = false; } $response = $authEvent->getResponse(); $failedAuthMessage = $authEvent->getFailedAuthenticationMessage(); } if (!$authenticated && $tryWithPassword && $user instanceof User) { // Try authenticating with local password $authenticated = $this->encoder->isPasswordValid($user, $token->getCredentials()); } } else { // Assume the user is authenticated although the token will tell for sure $authenticated = true; } if ($authenticated) { return new PluginToken($providerKey, $authenticatingService, $user, $user->getPassword(), $user->getRoles(), $response); } elseif ($response) { return new PluginToken($providerKey, $authenticatingService, $user, '', [], $response); } if ($failedAuthMessage) { throw new AuthenticationException($failedAuthMessage); } throw new BadCredentialsException(); }
/** * Get the event name for the loop depending of the event name and the loop name. * * This function also checks if there are services that listen to this event. * If not the function returns null. * * @param string $eventName the event name (`TheliaEvents::LOOP_EXTENDS_ARG_DEFINITIONS`, * `TheliaEvents::LOOP_EXTENDS_INITIALIZE_ARGS`, ...) * @return null|string The event name for the loop if listeners exist, otherwise null is returned */ protected function getDispatchEventName($eventName) { $customEventName = TheliaEvents::getLoopExtendsEvent($eventName, $this->loopName); if (!isset(self::$dispatchCache[$customEventName])) { self::$dispatchCache[$customEventName] = $this->dispatcher->hasListeners($customEventName); } return self::$dispatchCache[$customEventName] ? $customEventName : null; }
/** * {@inheritdoc} * * @param Request $request * * @return Response never null */ public function logout(Request $request, Response $response, TokenInterface $token) { $this->userModel->setOnlineStatus('offline'); if ($this->dispatcher->hasListeners(UserEvents::USER_LOGOUT)) { $event = new LogoutEvent($this->user, $request); $this->dispatcher->dispatch(UserEvents::USER_LOGOUT, $event); } // Clear session $session = $request->getSession(); $session->clear(); if (isset($event)) { $sessionItems = $event->getPostSessionItems(); foreach ($sessionItems as $key => $value) { $session->set($key, $value); } } // Note that a logout occurred $session->set('post_logout', true); }
/** * {@inheritdoc} */ public function resolveCommand(RawArgs $args) { if ($this->dispatcher && $this->dispatcher->hasListeners(ConsoleEvents::PRE_RESOLVE)) { $event = new PreResolveEvent($args, $this); $this->dispatcher->dispatch(ConsoleEvents::PRE_RESOLVE, $event); if ($resolvedCommand = $event->getResolvedCommand()) { return $resolvedCommand; } } return $this->config->getCommandResolver()->resolveCommand($args, $this); }
/** * * @param type $sql * @param array $parameters * @return PDOStatement */ public function createQuery($sql, array $parameters = array()) { $statement = $this->getPDO()->prepare($sql); $statement->setFetchMode(PDO::FETCH_ASSOC); $statement->execute($parameters); if ($this->dispatcher->hasListeners(Events::QUERY)) { $event = new QueryEvent($statement, $parameters); $this->dispatcher->dispatch(Events::QUERY, $event); } return $statement; }
public function showTasksAction() { if (!$this->dispatcher->hasListeners(CantigaEvents::UI_TASKS)) { return ''; } $listEvent = $this->dispatcher->dispatch(CantigaEvents::UI_TASKS, new ShowTasksEvent()); if (!$listEvent->hasTasks()) { return ''; } return $this->tpl->render('CantigaCoreBundle:Components:task-list.html.twig', array('tasks' => $listEvent->getTasks())); }
/** * @param string $widgetName * @throws InvalidConfigurationException * @return array */ public function getWidgetConfig($widgetName) { if (!$this->hasWidgetConfig($widgetName)) { throw new InvalidConfigurationException($widgetName); } $config = $this->copyConfigurationArray($this->configs[self::NODE_WIDGET][$widgetName]); if ($this->eventDispatcher->hasListeners(WidgetConfigurationLoadEvent::EVENT_NAME)) { $event = new WidgetConfigurationLoadEvent($config); $this->eventDispatcher->dispatch(WidgetConfigurationLoadEvent::EVENT_NAME, $event); $config = $event->getConfiguration(); } return $config; }
/** * @param TokenInterface $token * * @return Response|PluginToken */ public function authenticate(TokenInterface $token) { if (!$this->supports($token)) { return null; } $user = $token->getUser(); $authenticatingService = $token->getAuthenticatingService(); $response = null; if (!$user instanceof User) { $authenticated = false; // Try authenticating with a plugin if ($this->dispatcher->hasListeners(UserEvents::USER_PRE_AUTHENTICATION)) { $integrations = $this->integrationHelper->getIntegrationObjects($authenticatingService, ['sso_service'], false, null, true); $loginCheck = 'mautic_sso_login_check' == $this->request->attributes->get('_route'); $authEvent = new AuthenticationEvent(null, $token, $this->userProvider, $this->request, $loginCheck, $authenticatingService, $integrations); $this->dispatcher->dispatch(UserEvents::USER_PRE_AUTHENTICATION, $authEvent); if ($authenticated = $authEvent->isAuthenticated()) { $eventToken = $authEvent->getToken(); if ($eventToken !== $token) { // A custom token has been set by the plugin so just return it return $eventToken; } $user = $authEvent->getUser(); $authenticatingService = $authEvent->getAuthenticatingService(); } $response = $authEvent->getResponse(); if (!$authenticated && $loginCheck && !$response) { // Set an empty JSON response $response = new JsonResponse([]); } } if (!$authenticated && empty($response)) { throw new AuthenticationException('mautic.user.auth.error.invalidlogin'); } } return new PluginToken($this->providerKey, $authenticatingService, $user, $user instanceof User ? $user->getPassword() : '', $user instanceof User ? $user->getRoles() : [], $response); }
/** * {@inheritdoc} */ public function clearRootAssetMappings() { $mappings = array(); $hasListener = $this->dispatcher && $this->dispatcher->hasListeners(PuliEvents::POST_REMOVE_ASSET_MAPPING); if ($hasListener) { // Query the mappings for the event $mappings = $this->getRootAssetMappings(); } $this->discoveryManager->removeRootBindingDescriptors($this->exprBuilder->buildExpression()); if ($hasListener) { foreach ($mappings as $mapping) { $this->dispatcher->dispatch(PuliEvents::POST_REMOVE_ASSET_MAPPING, new RemoveAssetMappingEvent($mapping)); } } }
/** * {@inheritdoc} */ public function buildRepository() { $this->assertMappingsLoaded(); if ($this->dispatcher->hasListeners(PuliEvents::PRE_BUILD_REPOSITORY)) { $event = new BuildRepositoryEvent($this); $this->dispatcher->dispatch(PuliEvents::PRE_BUILD_REPOSITORY, $event); if ($event->isBuildSkipped()) { return; } } $this->populateRepository()->execute(); if ($this->dispatcher->hasListeners(PuliEvents::POST_BUILD_REPOSITORY)) { $this->dispatcher->dispatch(PuliEvents::POST_BUILD_REPOSITORY, new BuildRepositoryEvent($this)); } }
/** * @param $widgetName * @param $widgetId * @return array */ public function getWidgetItemsData($widgetName, $widgetId) { $widgetConfig = $this->configProvider->getWidgetConfig($widgetName); $widgetOptions = $this->getWidgetOptions($widgetId); $items = isset($widgetConfig['data_items']) ? $widgetConfig['data_items'] : []; $items = $this->filterWidgets($items); if ($this->eventDispatcher->hasListeners(WidgetItemsLoadDataEvent::EVENT_NAME)) { $event = new WidgetItemsLoadDataEvent($items, $widgetConfig, $widgetOptions); $this->eventDispatcher->dispatch(WidgetItemsLoadDataEvent::EVENT_NAME, $event); $items = $event->getItems(); } foreach ($items as $itemName => $config) { $items[$itemName]['value'] = $this->resolver->resolve([$config['data_provider']], ['widgetOptions' => $widgetOptions])[0]; } return $items; }
/** * Dispatch event to any listeners. * * @param string $type Either MembersEvents::MEMBER_LOGIN' or MembersEvents::MEMBER_LOGOUT * @param Authorisation $authorisation */ protected function dispatchEvent($type, Authorisation $authorisation) { if (!$this->dispatcher->hasListeners($type)) { return; } $event = new MembersLoginEvent(); $event->setAccount($authorisation->getAccount()); try { $this->dispatcher->dispatch($type, $event); } catch (\Exception $e) { if ($this->config->isDebug()) { dump($e); } $this->logger->critical('Members event dispatcher had an error', ['event' => 'exception', 'exception' => $e]); } }
/** * Create/update user from authentication plugins. * * @param User $user * @param bool|true $createIfNotExists * * @return User */ public function saveUser(User $user, $createIfNotExists = true) { $isNew = !$user->getId(); if ($isNew) { // Check if user exists and create one if applicable try { $user = $this->loadUserByUsername($user->getUsername(), $user->getEmail()); } catch (UsernameNotFoundException $exception) { if (!$createIfNotExists) { throw new BadCredentialsException(); } } } // Validation for User objects returned by a plugin if (!$user->getRole()) { throw new AuthenticationException('mautic.integration.sso.error.no_role'); } if (!$user->getUsername()) { throw new AuthenticationException('mautic.integration.sso.error.no_username'); } if (!$user->getEmail()) { throw new AuthenticationException('mautic.integration.sso.error.no_email'); } if (!$user->getFirstName() || !$user->getLastName()) { throw new AuthenticationException('mautic.integration.sso.error.no_name'); } // Check for plain password $plainPassword = $user->getPlainPassword(); if ($plainPassword) { // Encode plain text $user->setPassword($this->encoder->getEncoder($user)->encodePassword($plainPassword, $user->getSalt())); } elseif (!($password = $user->getPassword())) { // Generate and encode a random password $user->setPassword($this->encoder->getEncoder($user)->encodePassword(EncryptionHelper::generateKey(), $user->getSalt())); } $event = new UserEvent($user, $isNew); if ($this->dispatcher->hasListeners(UserEvents::USER_PRE_SAVE)) { $event = $this->dispatcher->dispatch(UserEvents::USER_PRE_SAVE, $event); } $this->userRepository->saveEntity($user); if ($this->dispatcher->hasListeners(UserEvents::USER_POST_SAVE)) { $this->dispatcher->dispatch(UserEvents::USER_POST_SAVE, $event); } return $user; }
/** * Get the condition through event dispatcher. * * @param FormInterface $form * @param AbstractType $formType * @param QueryInterface $filterQuery * @param string $alias * @return ConditionInterface|null */ protected function getFilterCondition(FormInterface $form, AbstractType $formType, QueryInterface $filterQuery, $alias) { $values = $this->prepareFilterValues($form, $formType); $values += array('alias' => $alias); $field = $values['alias'] . '.' . $form->getName(); $condition = null; // build a complete form name including parents $completeName = $form->getName(); $parentForm = $form; do { $parentForm = $parentForm->getParent(); if (!is_numeric($parentForm->getName())) { // skip collection numeric index $completeName = $parentForm->getName() . '.' . $completeName; } } while (!$parentForm->isRoot()); // apply the filter by using the closure set with the 'apply_filter' option $callable = $form->getConfig()->getAttribute('apply_filter'); if (false === $callable) { return null; } if ($callable instanceof \Closure) { $condition = $callable($filterQuery, $field, $values); } elseif (is_callable($callable)) { $condition = call_user_func($callable, $filterQuery, $field, $values); } else { // trigger a specific or a global event name $eventName = sprintf('lexik_form_filter.apply.%s.%s', $filterQuery->getEventPartName(), $completeName); if (!$this->dispatcher->hasListeners($eventName)) { $eventName = sprintf('lexik_form_filter.apply.%s.%s', $filterQuery->getEventPartName(), is_string($callable) ? $callable : $formType->getName()); } $event = new GetFilterConditionEvent($filterQuery, $field, $values); $this->dispatcher->dispatch($eventName, $event); $condition = $event->getCondition(); } // set condition path if ($condition instanceof ConditionInterface) { $condition->setName(trim(substr($completeName, strpos($completeName, '.')), '.')); } return $condition; }
/** * @param ContextInterface $context * @param \ArrayAccess $container * @param string $expression * @param string $eventErrorToRaise * @return bool * @throws InvalidRunnableExpressionException * @throws \Exception */ protected function runCommand(ContextInterface $context, \ArrayAccess $container, $expression, $eventErrorToRaise) { if (!preg_match('/' . self::REGEX_DEFINITION . '^\\s*(?<service>[\\w\\.]+):(?<method>[\\w]+)(?:\\((?<method_arguments>(?&arguments)?)\\))?\\s*$/x', $expression, $serviceMatch)) { throw new InvalidRunnableExpressionException($expression); } $parameters = [$context]; if (isset($serviceMatch['method_arguments'])) { $parameters = array_merge($parameters, json_decode('[' . $serviceMatch['method_arguments'] . ']', true)); } try { $result = call_user_func_array([$container[$serviceMatch['service']], $serviceMatch['method']], $parameters); } catch (\Exception $e) { if ($this->eventDispatcher->hasListeners($eventErrorToRaise)) { $this->eventDispatcher->dispatch($eventErrorToRaise, new WorkflowExceptionEvent($context, $e, $expression)); $result = false; } else { throw new \Exception($e->getMessage() . ' when running ' . $expression, 0, $e); } } return $result; }
/** * Apply the condition through event dispatcher. * * @param FormInterface $form * @param AbstractType $formType * @param QueryInterface $filterQuery * @param string $alias */ protected function applyFilterCondition(FormInterface $form, AbstractType $formType, QueryInterface $filterQuery, $alias) { $config = $form->getConfig(); $values = $this->prepareFilterValues($form, $formType); $values += array('alias' => $alias); $field = $values['alias'] . '.' . $form->getName(); // apply the filter by using the closure set with the 'apply_filter' option $callable = $config->getAttribute('apply_filter'); if ($callable instanceof \Closure) { $callable($filterQuery, $field, $values); } else { if (is_callable($callable)) { call_user_func($callable, $filterQuery, $field, $values); } else { // build specific event name including all form parent names $name = $form->getName(); $parentForm = $form; do { $parentForm = $parentForm->getParent(); $name = $parentForm->getName() . '.' . $name; } while (!$parentForm->isRoot()); // trigger specific or global event name $eventName = sprintf('lexik_form_filter.apply.%s.%s', $filterQuery->getEventPartName(), $name); if (!$this->dispatcher->hasListeners($eventName)) { $eventName = sprintf('lexik_form_filter.apply.%s.%s', $filterQuery->getEventPartName(), is_string($callable) ? $callable : $formType->getName()); } $event = new ApplyFilterEvent($filterQuery, $field, $values); $this->dispatcher->dispatch($eventName, $event); if ($this->dispatcher->hasListeners('lexik_filter.get')) { $type = $this->getFilterType($form->getConfig(), $filterQuery->getQueryBuilder()); if ($type instanceof FilterInterface) { $type->applyFilter($filterQuery->getQueryBuilder(), new Expr(), $field, $values); } } } } }
/** * Checks whether an event has any registered listeners. * * @param string $eventName The name of the event * * @return bool true if the specified event has any listeners, false otherwise */ public function hasListeners($eventName = null) { return $this->symfonyDispatcher->hasListeners($eventName) || $this->laravelDispatcher->hasListeners($eventName); }
/** * Checks whether an event has any registered listeners. * * @param string $eventName The name of the event. * * @return Boolean true if the specified event has any listeners, false otherwise */ public function hasListeners($eventName = null) { return $this->realDispatcher->hasListeners($eventName); }
/** * @inheritdoc */ public function hasListeners($eventName) { return $this->dispatcher->hasListeners($eventName); }
/** * @param string $eventName * @return boolean */ protected function hasListeners($eventName) { return $this->eventDispatcher !== null && $this->eventDispatcher->hasListeners($eventName); }