public function testBuild()
 {
     $type = 'history';
     $userId = 1;
     $user = $this->getMockBuilder('stdClass')->setMethods(['getId'])->getMock();
     $user->expects($this->once())->method('getId')->will($this->returnValue($userId));
     $token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
     $token->expects($this->once())->method('getUser')->will($this->returnValue($user));
     $this->tokenStorage->expects($this->once())->method('getToken')->will($this->returnValue($token));
     $item = $this->getMock('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationItemInterface');
     $this->factory->expects($this->once())->method('createItem')->with($type, [])->will($this->returnValue($item));
     $repository = $this->getMockBuilder('Oro\\Bundle\\NavigationBundle\\Entity\\Repository\\HistoryItemRepository')->disableOriginalConstructor()->getMock();
     $items = [['id' => 1, 'title' => 'test1', 'url' => '/'], ['id' => 2, 'title' => 'test2', 'url' => '/home']];
     $repository->expects($this->once())->method('getNavigationItems')->with($userId, $type)->will($this->returnValue($items));
     $this->em->expects($this->once())->method('getRepository')->with(get_class($item))->will($this->returnValue($repository));
     $menu = $this->getMockBuilder('Knp\\Menu\\MenuItem')->disableOriginalConstructor()->getMock();
     $childMock = $this->getMock('Knp\\Menu\\ItemInterface');
     $childMock2 = clone $childMock;
     $children = [$childMock, $childMock2];
     $matcher = $this->getMock('\\Knp\\Menu\\Matcher\\Matcher');
     $matcher->expects($this->once())->method('isCurrent')->will($this->returnValue(true));
     $this->builder->setMatcher($matcher);
     $menu->expects($this->exactly(2))->method('addChild');
     $menu->expects($this->once())->method('setExtra')->with('type', $type);
     $menu->expects($this->once())->method('getChildren')->will($this->returnValue($children));
     $menu->expects($this->once())->method('removeChild');
     $n = rand(1, 10);
     $configMock = $this->getMockBuilder('Oro\\Bundle\\ConfigBundle\\Config\\UserConfigManager')->disableOriginalConstructor()->getMock();
     $configMock->expects($this->once())->method('get')->with($this->equalTo('oro_navigation.maxItems'))->will($this->returnValue($n));
     $this->manipulator->expects($this->once())->method('slice')->with($menu, 0, $n);
     $this->builder->setOptions($configMock);
     $this->builder->build($menu, [], $type);
 }
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     /** @var \Claroline\CoreBundle\Entity\User $user */
     $user = $this->tokenStorage->getToken()->getUser();
     $locale = null === $user->getLocale() ? $this->platformConfigHandler->getParameter('locale_language') : $user->getLocale();
     $builder->add('badge', 'zenstruck_ajax_entity', array('attr' => array('class' => 'fullwidth'), 'theme_options' => array('control_width' => 'col-md-3'), 'placeholder' => $this->translator->trans('badge_form_badge_selection', array(), 'icap_badge'), 'class' => 'IcapBadgeBundle:Badge', 'use_controller' => true, 'repo_method' => sprintf('findByNameForAjax'), 'extra_data' => array('userId' => $user->getId(), 'locale' => $locale)));
 }
 /**
  * Sets up the fixture, for example, opens a network connection.
  * This method is called before a test is executed.
  */
 protected function setUp()
 {
     $this->em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     /* @var $conn Connection */
     $conn = $this->getMockBuilder('Doctrine\\DBAL\\Connection')->disableOriginalConstructor()->getMock();
     $conn->expects($this->any())->method('getDatabase')->will($this->returnValue('myDatabase'));
     /* @var $platform AbstractPlatform */
     $platform = $this->getMockForAbstractClass('Doctrine\\DBAL\\Platforms\\AbstractPlatform');
     $conn->expects($this->any())->method('getDatabasePlatform')->will($this->returnValue($platform));
     /* @var $stmt Statement */
     $stmt = $this->getMockForAbstractClass('Kunstmaan\\AdminBundle\\Tests\\Mocks\\StatementMock');
     $conn->expects($this->any())->method('executeQuery')->will($this->returnValue($stmt));
     $this->em->expects($this->any())->method('getConnection')->will($this->returnValue($conn));
     /* @var $conf Configuration */
     $conf = $this->getMockBuilder('Doctrine\\ORM\\Configuration')->disableOriginalConstructor()->getMock();
     /* @var $strat QuoteStrategy */
     $strat = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\QuoteStrategy')->disableOriginalConstructor()->getMock();
     $strat->expects($this->any())->method('getTableName')->will($this->returnValue('rootTable'));
     $conf->expects($this->any())->method('getQuoteStrategy')->will($this->returnValue($strat));
     $conf->expects($this->any())->method('getDefaultQueryHints')->willReturn(array());
     $conf->expects($this->any())->method('isSecondLevelCacheEnabled')->willReturn(false);
     $this->em->expects($this->any())->method('getConfiguration')->will($this->returnValue($conf));
     /* @var $meta ClassMetadata */
     $meta = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadata')->disableOriginalConstructor()->getMock();
     $this->em->expects($this->any())->method('getClassMetadata')->will($this->returnValue($meta));
     $this->tokenStorage = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\Storage\\TokenStorageInterface')->getMock();
     $this->token = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface')->getMock();
     $this->tokenStorage->expects($this->any())->method('getToken')->will($this->returnValue($this->token));
     $this->rh = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Role\\RoleHierarchyInterface')->getMock();
     $this->object = new AclHelper($this->em, $this->tokenStorage, $this->rh);
 }
 function it_returns_locale_of_currently_logged_admin_user(TokenStorageInterface $tokenStorage, TokenInterface $token, AdminUserInterface $admin)
 {
     $admin->getLocaleCode()->willReturn('en_US');
     $token->getUser()->willreturn($admin);
     $tokenStorage->getToken()->willReturn($token);
     $this->getLocaleCode()->shouldReturn('en_US');
 }
 /**
  * Get the attribute collection.
  *
  * TODO This action is only accessible via a GET or POST query, because of too long query URI. To respect standards,
  * a refactor must be done.
  *
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function indexAction(Request $request)
 {
     $options = [];
     $context = ['include_group' => true];
     if ($request->request->has('identifiers')) {
         $options['identifiers'] = explode(',', $request->request->get('identifiers'));
         $context['include_group'] = false;
     }
     if ($request->request->has('types')) {
         $options['types'] = explode(',', $request->request->get('types'));
     }
     if (empty($options)) {
         $options = $request->request->get('options', ['limit' => SearchableRepositoryInterface::FETCH_LIMIT, 'locale' => null]);
     }
     $token = $this->tokenStorage->getToken();
     $options['user_groups_ids'] = $token->getUser()->getGroupsIds();
     if (null !== $this->attributeSearchRepository) {
         $attributes = $this->attributeSearchRepository->findBySearch($request->request->get('search'), $options);
     } else {
         if (isset($options['identifiers'])) {
             $options['code'] = $options['identifiers'];
         }
         $attributes = $this->attributeRepository->findBy($options);
     }
     $normalizedAttributes = $this->normalizer->normalize($attributes, 'internal_api', $context);
     return new JsonResponse($normalizedAttributes);
 }
Example #6
0
 /**
  * Set the username from injected security context
  * @param TokenStorageInterface $securityTokenStorage
  * @param AuditLogManager $auditLogManager
  */
 public function __construct(TokenStorageInterface $securityTokenStorage, AuditLogManager $auditLogManager)
 {
     if (null !== $securityTokenStorage && null !== $securityTokenStorage->getToken()) {
         $this->user = $securityTokenStorage->getToken()->getUser();
     }
     $this->manager = $auditLogManager;
 }
 public function __construct(ItemFactory $navigationItemFactory, TokenStorageInterface $tokenStorage, EntityManager $entityManager, TitleServiceInterface $titleService)
 {
     $this->navItemFactory = $navigationItemFactory;
     $this->user = !$tokenStorage->getToken() || is_string($tokenStorage->getToken()->getUser()) ? null : $tokenStorage->getToken()->getUser();
     $this->em = $entityManager;
     $this->titleService = $titleService;
 }
Example #8
0
 private function getUserFromTokenStorage()
 {
     if (($token = $this->tokenStorage->getToken()) !== null) {
         return $token->getUser();
     }
     throw new \RuntimeException('I don\'t have a token');
 }
 /**
  * @return \Symfony\Component\Security\Core\User\UserInterface
  */
 private function getUser()
 {
     if (is_null($this->user)) {
         $this->user = $this->tokenStorage->getToken()->getUser();
     }
     return $this->user;
 }
 /**
  * {@inheritdoc}
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (null !== ($authorization = $request->headers->get($this->authenticationHeaderName))) {
         $headerParts = array_map('trim', explode(' ', $authorization, 2));
         if (2 === count($headerParts)) {
             $credentialParts = explode(':', $headerParts[1]);
             if (2 === count($credentialParts)) {
                 $token = new HmacUserToken();
                 $token->setServiceLabel($headerParts[0]);
                 $token->setUser($credentialParts[0]);
                 $token->setSignature($credentialParts[1]);
                 $token->setRequest($request);
                 try {
                     $authenticatedToken = $this->authenticationManager->authenticate($token);
                     // Call setToken() on an instance of SecurityContextInterface or TokenStorageInterface (>=2.6)
                     $this->tokenStorage->setToken($authenticatedToken);
                     // Success
                     return;
                 } catch (AuthenticationException $exception) {
                 }
             }
         }
     }
     $event->setResponse(new Response(null, 401));
 }
 /**
  * Merge in dashboard list into runtime configuration.
  *
  * {@inheritdoc}
  */
 public function merge(array $currentConfig)
 {
     /** @var User $user */
     $user = $this->tokenStorage->getToken()->getUser();
     $defaultDashboardNames = [];
     foreach ($this->dashboardMgr->getDefaultDashboards($user) as $dashboard) {
         $defaultDashboardNames[] = $dashboard->getName();
     }
     $isDefaultFound = false;
     $result = array();
     foreach ($this->dashboardMgr->getUserDashboards($user) as $dashboard) {
         if (!$dashboard->isAllowed($this->container)) {
             continue;
         }
         $isDefault = in_array($dashboard->getName(), $defaultDashboardNames);
         if ($isDefault) {
             $isDefaultFound = true;
         }
         $result[] = array_merge($this->serializeDashboard($dashboard), array('default' => $isDefault));
     }
     if (!$isDefaultFound) {
         // if there's no default dashboard available for a given user then we will display a dashboard
         // where user will be able to pick one he/she needs
         $dashboard = new SimpleDashboard('default', 'List of user dashboards', 'Modera.backend.dashboard.runtime.DashboardListDashboardActivity');
         $result[] = array_merge($this->serializeDashboard($dashboard), array('default' => true));
     }
     return array_merge($currentConfig, array('modera_backend_dashboard' => array('dashboards' => $result)));
 }
 /**
  * Constructor.
  *
  * @param TokenStorageInterface $aTokenStorage The token storage
  */
 public function __construct(TokenStorageInterface $aTokenStorage)
 {
     $token = $aTokenStorage->getToken();
     if ($token instanceof TokenInterface) {
         $this->currentUser = $token->getUser() instanceof UserInterface ? $token->getUser() : null;
     }
 }
 public function __construct(TokenStorageInterface $token, ComunidadProvider $comunidadProvider, ControllerResolverInterface $resolver, LoggerInterface $logger)
 {
     $this->token = $token->getToken();
     $this->comunidadProvider = $comunidadProvider;
     $this->resolver = $resolver;
     $this->logger = $logger;
 }
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (empty($request->headers->get("Authorization"))) {
         return;
     }
     $authHeader = $request->headers->get("Authorization");
     if (strpos($authHeader, " ") === false) {
         return;
     }
     list($tokenType, $token) = explode(" ", $authHeader, 2);
     if (strtolower($tokenType) !== "bearer") {
         return;
     }
     // Verify that there is an access_token present
     /*
             if(empty($request->get("access_token"))) {
                 return;
             }
             $token = $request->get("access_token");*/
     $unauthenticatedToken = new OAuthToken();
     $unauthenticatedToken->setToken($token);
     try {
         $authenticatedToken = $this->authenticationManager->authenticate($unauthenticatedToken);
         $this->tokenStorage->setToken($authenticatedToken);
         return;
     } catch (AuthenticationException $e) {
         if ($this->logger !== null) {
             $this->logger->notice("Access token authentication failed");
         }
     }
     $response = new Response();
     $response->setStatusCode(Response::HTTP_FORBIDDEN);
     $event->setResponse($response);
 }
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     //find out if the current request contains any information by which the user might be authenticated
     if (!$request->headers->has('X-WSSE')) {
         return;
     }
     $ae_message = null;
     $this->wsseHeader = $request->headers->get('X-WSSE');
     $wsseHeaderInfo = $this->parseHeader();
     if ($wsseHeaderInfo !== false) {
         $token = new Token($wsseHeaderInfo['Username'], $wsseHeaderInfo['PasswordDigest'], $this->providerKey);
         $token->setAttribute('nonce', $wsseHeaderInfo['Nonce']);
         $token->setAttribute('created', $wsseHeaderInfo['Created']);
         try {
             $returnValue = $this->authenticationManager->authenticate($token);
             if ($returnValue instanceof TokenInterface) {
                 return $this->tokenStorage->setToken($returnValue);
             } else {
                 if ($returnValue instanceof Response) {
                     return $event->setResponse($returnValue);
                 }
             }
         } catch (AuthenticationException $ae) {
             $event->setResponse($this->authenticationEntryPoint->start($request, $ae));
         }
     }
 }
Example #16
0
 /**
  * MenuHelper constructor.
  *
  * @param CorePermissions       $security
  * @param TokenStorageInterface $tokenStorage
  * @param RequestStack          $requestStack
  * @param array                 $mauticParameters
  */
 public function __construct(CorePermissions $security, TokenStorageInterface $tokenStorage, RequestStack $requestStack, array $mauticParameters)
 {
     $this->security = $security;
     $this->user = $tokenStorage->getToken()->getUser();
     $this->mauticParameters = $mauticParameters;
     $this->request = $requestStack->getCurrentRequest();
 }
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $token = $this->tokenStorage->getToken();
     if ($token === null) {
         throw new \LogicException('Unable to get token from security storage for portfolio widget form!');
     }
     $user = $token->getUser();
     if (!$user) {
         throw new \LogicException('Unable to get connected user for portfolio widget form!');
     }
     $builder->add('portfolio_id', 'entity', ['class' => 'IcapPortfolioBundle:Portfolio', 'query_builder' => function (EntityRepository $entityRepository) use($user) {
         return $entityRepository->createQueryBuilder('p')->where('p.user = :user')->setParameter('user', $user);
     }, 'property_path' => 'portfolio'])->add('widget_id', 'entity', ['class' => 'IcapPortfolioBundle:Widget\\AbstractWidget', 'query_builder' => function (EntityRepository $entityRepository) use($user) {
         return $entityRepository->createQueryBuilder('w')->where('w.user = :user')->setParameter('user', $user);
     }, 'property_path' => 'widget'])->add('col', 'integer')->add('row', 'integer')->add('sizeX', 'integer')->add('sizeY', 'integer');
     $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use($user) {
         $form = $event->getForm();
         $choices = [];
         $choiceTypes = $this->widgetTypeManager->getWidgetsTypes();
         foreach ($choiceTypes as $choiceType) {
             $choices[$choiceType['name']] = $choiceType['name'];
         }
         $form->add('widget_type', 'choice', ['choices' => $choices]);
     });
 }
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $object = new \ReflectionObject($controller[0]);
     $method = $object->getMethod($controller[1]);
     $classConfigurations = $this->reader->getClassAnnotations($object);
     $methodConfigurations = $this->reader->getMethodAnnotations($method);
     foreach (array_merge($classConfigurations, $methodConfigurations) as $configuration) {
         if ($configuration instanceof OAuth2) {
             $token = $this->token_storage->getToken();
             // If no access token is found by the firewall, then returns an authentication error
             if (!$token instanceof OAuth2Token) {
                 $this->createAuthenticationException($event, 'OAuth2 authentication required');
                 return;
             }
             foreach ($this->getCheckers() as $checker) {
                 $result = $checker->check($token, $configuration);
                 if (null !== $result) {
                     $this->createAccessDeniedException($event, $result);
                     return;
                 }
             }
         }
     }
 }
 /**
  * @return Item
  */
 private function createRootItem()
 {
     $rootItem = new Item('account');
     $rootItem->setLabel($this->translator->trans('admin.welcome', array('%username%' => $this->tokenStorage->getToken()->getUsername()), 'FSiAdminSecurity'));
     $rootItem->setOptions(array('attr' => array('id' => 'account')));
     return $rootItem;
 }
Example #20
0
 /**
  * AbstractJournalItemMailer constructor.
  * @param OjsMailer $ojsMailer
  * @param RegistryInterface $registry
  * @param TokenStorageInterface $tokenStorage
  * @param RouterInterface $router
  */
 public function __construct(OjsMailer $ojsMailer, RegistryInterface $registry, TokenStorageInterface $tokenStorage, RouterInterface $router)
 {
     $this->ojsMailer = $ojsMailer;
     $this->em = $registry->getManager();
     $this->user = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null;
     $this->router = $router;
 }
Example #21
0
 public function showUser(ShowUserEvent $event)
 {
     if ($this->tokenStorage->getToken()->isAuthenticated()) {
         $user = $this->tokenStorage->getToken()->getUser();
         $event->setUser($user);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function generate(Request $request)
 {
     $token = $this->tokenStorage->getToken();
     $user = null === $token ? 'anon.' : $token->getUser();
     $version = sprintf('u:%s', is_string($user) ? $user : $user->getId());
     return $version;
 }
Example #23
0
 private function generateErrorForException(\Exception $exception)
 {
     if ($exception instanceof CommandInvalidException) {
         $formError = $exception->getForm()->getErrors(true)->current();
         $path = $formError->getOrigin()->getPropertyPath();
         if ($path !== null) {
             // We got PropertyPathInterface or maybe even a string (undocumented).
             $path = (string) $path;
         }
         return new E\Api\BadRequest($formError->getMessage(), $path);
     } elseif ($exception instanceof ConstraintViolationException) {
         return $exception->getError();
     } elseif ($exception instanceof UsernameNotFoundException) {
         return new E\Security\BadCredentials();
     } elseif ($exception instanceof AccessDeniedException) {
         $token = $this->tokenStorage->getToken();
         if ($token && $this->tokenStorage->getToken()->getRoles()) {
             return new E\Security\NotAuthorized();
         } else {
             return new E\Security\NotAuthenticated();
         }
     } elseif ($exception instanceof ProtocolException) {
         return $this->getErrorForOxygenProtocolException($exception);
     } else {
         return new E\Api\UnexpectedError();
     }
 }
 public function handle(GetResponseEvent $event)
 {
     // getting request
     $request = $event->getRequest();
     // getting attributes
     $apiClientToken = $request->attributes->get('apiClientToken');
     $apiUserToken = $request->attributes->get('apiUserToken');
     $apiServerAction = $request->attributes->get('apiAction');
     /* @var $apiServerAction ApiServerAction */
     // cleaning credentials and interface name
     $request->attributes->remove('apiClientToken');
     $request->attributes->remove('apiUserToken');
     // creating token
     $token = new Token($apiServerAction->getApiServerInterface());
     $token->setCredentials([$apiClientToken, $apiUserToken]);
     try {
         // authenticating
         $authenticatedToken = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($authenticatedToken);
         // getting authenticated user
         $user = $authenticatedToken->getUser();
         /* @var $user User */
         // setting request attributes
         $request->attributes->set('apiConnection', $user->getApiConnection());
         $request->attributes->set('apiClient', $user->getApiClient());
         $request->attributes->set('apiUser', $user->getApiUser());
     } catch (\Exception $e) {
         $event->stopPropagation();
         throw new AccessDeniedHttpException(null, $e);
     }
 }
Example #25
0
 /**
  * If user is logged-in in legacy_mode (e.g. legacy admin interface),
  * will inject currently logged-in user in the repository.
  *
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     /** @var \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver */
     $request = $event->getRequest();
     $session = $request->getSession();
     if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST || !$this->configResolver->getParameter('legacy_mode') || !($session->isStarted() && $session->has('eZUserLoggedInID'))) {
         return;
     }
     try {
         $apiUser = $this->repository->getUserService()->loadUser($session->get('eZUserLoggedInID'));
         $this->repository->setCurrentUser($apiUser);
         $token = $this->tokenStorage->getToken();
         if ($token instanceof TokenInterface) {
             $token->setUser(new User($apiUser));
             // Don't embed if we already have a LegacyToken, to avoid nested session storage.
             if (!$token instanceof LegacyToken) {
                 $this->tokenStorage->setToken(new LegacyToken($token));
             }
         }
     } catch (NotFoundException $e) {
         // Invalid user ID, the user may have been removed => invalidate the token and the session.
         $this->tokenStorage->setToken(null);
         $session->invalidate();
     }
 }
Example #26
0
 /**
  * @param EntityManager $em
  * @param RESTResponse $response
  * @param ValidatorInterface $validator
  * @param TokenStorageInterface $tokenStorage
  */
 public function __construct($em, $response, $validator, $tokenStorage)
 {
     $this->em = $em;
     $this->response = $response;
     $this->validator = $validator;
     $this->user = $tokenStorage->getToken()->getUser();
 }
Example #27
0
 /**
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     if (null !== $this->tokenStorage->getToken()) {
         return;
     }
     $request = $event->getRequest();
     $token = new PluginToken($this->providerKey, $request->get('integration', null));
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         if ($authToken instanceof PluginToken) {
             $response = $authToken->getResponse();
             if ($authToken->isAuthenticated()) {
                 $this->tokenStorage->setToken($authToken);
                 if ('api' != $this->providerKey) {
                     $response = $this->onSuccess($request, $authToken, $response);
                 }
             } elseif (empty($response)) {
                 throw new AuthenticationException('mautic.user.auth.error.invalidlogin');
             }
         }
     } catch (AuthenticationException $exception) {
         if ('api' != $this->providerKey) {
             $response = $this->onFailure($request, $exception);
         }
     }
     if ($response) {
         $event->setResponse($response);
     }
 }
Example #28
0
 public function __construct(EntityManager $oEntityManager, TokenStorageInterface $oUser, Ebay $oEbay)
 {
     $this->oEm = $oEntityManager;
     $this->oEbayProfiles = $this->oEm->getRepository('EparServiceBundle:EbayProfiles');
     $this->oUser = $oUser->getToken()->getUser();
     $this->oEbay = $oEbay;
 }
 /**
  * Returns the context for the given activity class and id
  *
  * @param string $class The FQCN of the activity entity
  * @param        $id
  *
  * @return array
  */
 public function getActivityContext($class, $id)
 {
     $currentUser = $this->securityTokenStorage->getToken()->getUser();
     $userClass = ClassUtils::getClass($currentUser);
     $entity = $this->doctrineHelper->getEntity($class, $id);
     $result = [];
     if (!$entity || !$entity instanceof ActivityInterface) {
         return $result;
     }
     $targets = $entity->getActivityTargetEntities();
     $entityProvider = $this->configManager->getProvider('entity');
     foreach ($targets as $target) {
         $targetClass = ClassUtils::getClass($target);
         $targetId = $target->getId();
         if ($userClass === $targetClass && $currentUser->getId() === $targetId) {
             continue;
         }
         $item = [];
         $config = $entityProvider->getConfig($targetClass);
         $safeClassName = $this->entityClassNameHelper->getUrlSafeClassName($targetClass);
         $item = $this->prepareItemTitle($item, $targetClass, $target, $targetId);
         $item['activityClassAlias'] = $this->entityAliasResolver->getPluralAlias($class);
         $item['entityId'] = $id;
         $item['targetId'] = $targetId;
         $item['targetClassName'] = $safeClassName;
         $item['icon'] = $config->get('icon');
         $item['link'] = $this->getContextLink($targetClass, $targetId);
         $item = $this->dispatchContextTitle($item, $targetClass);
         $result[] = $item;
     }
     return $result;
 }
Example #30
0
 /**
  * {@inheritdoc}
  */
 public function getParameters()
 {
     if (null === $this->tokenStorage->getToken()) {
         return ['settingKey' => self::SETTING_KEY];
     }
     $user = $this->tokenStorage->getToken()->getUser();
     if (!$user instanceof UserInterface) {
         return ['settingKey' => self::SETTING_KEY];
     }
     $result = [];
     $exists = false;
     foreach ($user->getRoleObjects() as $role) {
         if (null === ($setting = $role->getSetting(self::SETTING_KEY))) {
             continue;
         }
         $result = array_merge_recursive($result, $setting->getValue());
         $exists = true;
     }
     if (!$exists) {
         return ['settingKey' => self::SETTING_KEY];
     }
     // array_merge_recursive accepts non-unique values they have to be removed
     foreach (array_keys($result) as $section) {
         $result[$section] = array_values(array_unique($result[$section]));
     }
     return ['settingKey' => self::SETTING_KEY, 'userToolbar' => $result];
 }