trans() публичный Метод

public trans ( $id, array $parameters = [], $domain = 'messages', $locale = null )
$parameters array
Пример #1
0
 /**
  * @param ConfigureMenuEvent $event
  */
 public function onNavigationConfigure(ConfigureMenuEvent $event)
 {
     $menu = $event->getMenu();
     $children = array();
     $entitiesMenuItem = $menu->getChild('system_tab')->getChild('entities_list');
     if ($entitiesMenuItem) {
         /** @var ConfigProvider $entityConfigProvider */
         $entityConfigProvider = $this->configManager->getProvider('entity');
         /** @var ConfigProvider $entityExtendProvider */
         $entityExtendProvider = $this->configManager->getProvider('extend');
         $extendConfigs = $entityExtendProvider->getConfigs();
         foreach ($extendConfigs as $extendConfig) {
             if ($this->checkAvailability($extendConfig)) {
                 $config = $entityConfigProvider->getConfig($extendConfig->getId()->getClassname());
                 if (!class_exists($config->getId()->getClassName()) || !$this->securityFacade->hasLoggedUser() || !$this->securityFacade->isGranted('VIEW', 'entity:' . $config->getId()->getClassName())) {
                     continue;
                 }
                 $children[$config->get('label')] = array('label' => $this->translator->trans($config->get('label')), 'options' => array('route' => 'oro_entity_index', 'routeParameters' => array('entityName' => str_replace('\\', '_', $config->getId()->getClassName())), 'extras' => array('safe_label' => true, 'routes' => array('oro_entity_*'))));
             }
         }
         sort($children);
         foreach ($children as $child) {
             $entitiesMenuItem->addChild($child['label'], $child['options']);
         }
     }
 }
 public function handle(FormInterface $form, Request $request)
 {
     $form->handleRequest($request);
     if (!$form->isValid()) {
         return false;
     }
     $data = $form->getData();
     if ($form->isSubmitted()) {
         $user = $this->userManager->findUserByEmail($data['email']);
         if (is_null($user)) {
             $form->addError(new FormError($this->translator->trans('security.resetting.request.errors.email_not_found')));
             return false;
         }
         if ($user->isPasswordRequestNonExpired($this->tokenTll)) {
             $form->addError(new FormError($this->translator->trans('security.resetting.request.errors.password_already_requested')));
             return false;
         }
         if ($user->getConfirmationToken() === null) {
             $user->setConfirmationToken($this->tokenGenerator->generateToken());
         }
         $user->setPasswordRequestedAt(new \DateTime());
         $this->userManager->resettingRequest($user);
     }
     return true;
 }
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $section = $this->section;
     $builder->add('prenom', "text")->add('nom', "text")->add('email', 'email')->add('sexe', 'choice', array('choices' => array('m' => $this->translator->trans('label.male'), 'f' => $this->translator->trans('label.female'))))->add('dob', 'date', array('required' => false, 'input' => 'datetime', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy'))->add('nbmentee', 'choice', array('required' => true, 'multiple' => false, 'empty_value' => $this->translator->trans('label.nbmentee'), 'choices' => array("1" => 1, "2" => 2, "3" => 3)))->add('submit', "submit")->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Le mot de passe doit être indentique à sa confirmation.', 'required' => true))->add('conditionGenerale', 'checkbox', array('required' => true, 'label' => "J'accepte les conditions générales d'utilisations"))->add('nationalite', 'entity', array('label' => 'Status Name', 'required' => true, 'empty_value' => $this->translator->trans('label.form.nationality'), 'class' => 'BuddySystem\\MembersBundle\\Entity\\Nationality', 'property' => 'nationality'))->add('universite', 'entity', array('label' => 'Status Name', 'empty_value' => 'crud.form.university', 'class' => 'BuddySystem\\MembersBundle\\Entity\\Univercity', 'query_builder' => function (UniversityRepository $ur) use($section) {
         return $ur->getUniversitiesBySection($section, true);
     }, 'required' => false))->add('comment');
 }
Пример #4
0
 /**
  * @param $jobs
  * @throws UnauthorizedCommandException
  */
 protected function runJobs($jobs)
 {
     foreach ($jobs as $job) {
         /**
          * @var \WeavingTheWeb\Bundle\ApiBundle\Entity\Job $job
          */
         $command = $job->getValue();
         try {
             $this->validateCommand($command);
             $job->setStatus(JobInterface::STATUS_STARTED);
             $this->updateJob($job);
             $command = $this->getApplication()->get($command);
             $success = $command->run(new ArrayInput(['command' => $command, '--job' => $job->getId()]), $this->output);
             if (intval($success) === 0) {
                 $job->setStatus(JobInterface::STATUS_FINISHED);
             } else {
                 $job->setStatus(JobInterface::STATUS_FAILED);
             }
             $this->updateJob($job);
         } catch (UnauthorizedCommandException $exception) {
             $message = $this->translator->trans('job.run.unauthorized', ['{{ command }}' => $command], 'job');
             $this->logger->error($exception->getMessage());
             $this->output->writeln($message);
             $job->setStatus(JobInterface::STATUS_FAILED);
             $this->updateJob($job);
             continue;
         } catch (\Exception $exception) {
             $this->logger->error($exception->getMessage());
             continue;
         }
     }
 }
 /**
  * @param FormView $formView
  *
  * @return string
  * @author Michaël VEROUX
  */
 public function get(FormView $formView)
 {
     $value = $formView->vars['value'];
     $display = array();
     $expanded = isset($formView->vars['expanded']) && $formView->vars['expanded'];
     $multiple = isset($formView->vars['multiple']) && $formView->vars['multiple'];
     if ($expanded && $multiple) {
         $value = array_filter($value, function ($val) {
             return $val;
         });
         $value = array_keys($value);
     }
     foreach ($formView->vars['choices'] as $key => $choiceView) {
         if ($multiple) {
             if ($expanded) {
                 $compare = $key;
             } else {
                 $compare = $choiceView->value;
             }
             if (in_array($compare, $value)) {
                 $display[] = $this->translator->trans($choiceView->label, array(), $formView->vars['translation_domain']);
             }
         } else {
             if ($value == $choiceView->value) {
                 return $this->translator->trans($choiceView->label, array(), $formView->vars['translation_domain']);
             }
         }
     }
     if (!count($display)) {
         return $formView->vars['placeholder'];
     }
     return implode(PHP_EOL, $display);
 }
Пример #6
0
 /**
  * Get values of merge modes with labels
  *
  * @param array $modes
  * @return array
  */
 protected function getMergeValues(array $modes)
 {
     $result = array();
     foreach ($modes as $mode) {
         $result[$mode] = $this->translator->trans('oro.entity_merge.merge_modes.' . $mode);
     }
     return $result;
 }
 /**
  * Loads the user for the given username.
  *
  * This method must throw UsernameNotFoundException if the user is not
  * found.
  *
  * @param string $username The username
  *
  * @return UserInterface
  *
  * @throws UsernameNotFoundException if the user is not found
  */
 public function loadUserByUsername($username)
 {
     $user = $this->userRepository->findOneBy(['username' => $username]);
     if (!$user) {
         throw new UsernameNotFoundException($this->translator->trans('Username %username% does not exist!', ['%username%' => $username]));
     }
     return $user;
 }
 public function addBackendMenuItems(MenuBuilderEvent $event)
 {
     $menu = $event->getMenu();
     if (isset($menu['content'])) {
         $menu['content']->addChild('webburza_sylius_articles', array('route' => 'webburza_article_index', 'labelAttributes' => array('icon' => 'glyphicon glyphicon-file')))->setLabel($this->translator->trans('webburza.sylius.article.backend.articles'));
         $menu['content']->addChild('webburza_sylius_article_categories', array('route' => 'webburza_article_category_index', 'labelAttributes' => array('icon' => 'glyphicon glyphicon-tags')))->setLabel($this->translator->trans('webburza.sylius.article_category.backend.article_categories'));
     }
 }
 /**
  * @param UserEvent $event
  * @throws \Exception
  * @throws \Twig_Error
  */
 public function onResettingRequestSuccess(UserEvent $event)
 {
     $user = $event->getUser();
     $params = $event->getParams();
     $url = $this->router->generate($params[$event::PARAM_RESETTING_EMAIL_ROUTE], array('token' => $user->getConfirmationToken()), true);
     $message = \Swift_Message::newInstance()->setSubject($this->translator->trans('security.resetting.request.email.subject'))->setFrom($this->parameter->get($params[$event::PARAM_RESETTING_EMAIL_FROM]))->setTo($user->getEmail())->setBody($this->twigEngine->render($params[$event::PARAM_RESETTING_EMAIL_TEMPLATE], array('complete_name' => $event->getSecureArea()->getCompleteName(), 'url' => $url)));
     $this->mailer->send($message);
     $this->flashBag->add(FlashBagEvents::MESSAGE_TYPE_SUCCESS, $this->translator->trans('security.resetting.request.check_email', array('user_email' => $user->getObfuscatedEmail())));
 }
Пример #10
0
 /**
  * {@inheritdoc}
  */
 public function checkCredentials($credentials, UserInterface $user)
 {
     $plainPassword = $credentials['password'];
     $encoder = $this->passwordEncoder;
     if (!$encoder->isPasswordValid($user, $plainPassword)) {
         throw new CustomUserMessageAuthenticationException($this->translator->trans($this->failMessage));
     }
     return true;
 }
Пример #11
0
 /**
  * Add a table with the specified columns to the lookup.
  *
  * The data should be an associative array with the following data:
  * 'display_name' => The translation key to display in the select list
  * 'columns'      => An array containing the table's columns
  *
  * @param string $context   Context for data
  * @param array  $data      Data array for the table
  *
  * @return void
  */
 public function addTable($context, array $data)
 {
     foreach ($data['columns'] as &$d) {
         $d['label'] = $this->translator->trans($d['label']);
     }
     uasort($data['columns'], function ($a, $b) {
         return strnatcmp($a['label'], $b['label']);
     });
     $this->tableArray[$context] = $data;
 }
Пример #12
0
 /**
  * Get Status name use to get a status name a service.
  *
  * @param Service $service
  *
  * @return string
  */
 public function getGlobalServiceStatusName(Service $service)
 {
     switch ($service->getStatus()) {
         case Service::OPERATIONNAL:
             return $this->translator->trans('status_page.service.up');
         case Service::OUTAGE:
             return $this->translator->trans('status_page.service.down');
         default:
             return '';
     }
 }
 public function handle(FormInterface $form, Request $request)
 {
     $form->handleRequest($request);
     if (!$form->isValid()) {
         return false;
     }
     $entity = $form->getData();
     $this->userManager->resettingReset($entity);
     $this->flashBag->add(FlashBagEvents::MESSAGE_TYPE_SUCCESS, $this->translator->trans('security.resetting.reset.success'));
     return true;
 }
 /**
  * @param mixed $value The value in the transformed representation
  * @return mixed The value in the original representation
  * @throws TransformationFailedException When the transformation fails.
  */
 public function reverseTransform($username)
 {
     if (!$username) {
         return null;
     }
     $user = $this->registry->getRepository('AppBundle:User')->findOneBy(array('username' => $username));
     if (!$user) {
         throw new TransformationFailedException($this->translator->trans('user.unknownusername'));
     }
     return $user;
 }
Пример #15
0
 public function getDescription()
 {
     $this->translator = \Siciarek\AdRotatorBundle\SiciarekAdRotatorBundle::getContainer()->get('translator');
     $temp = array();
     if ($this->getMainpage() === true) {
         $temp[] = $this->translator->trans(self::MAINPAGE, array(), 'SiciarekAdRotator');
     }
     if ($this->getSubpages() === true) {
         $temp[] = $this->translator->trans(self::SUBPAGES, array(), 'SiciarekAdRotator');
     }
     return implode(' + ', $temp);
 }
 /**
  * @param array $data
  *
  * @return Notification
  */
 public function create($data)
 {
     $notification = new Notification();
     $notification->setName(Notification::LEADER_FOLLOWS);
     $notification->setContent(array('follower' => $data['follower'], 'followerFullName' => $data['followerFullName'], 'leader' => $data['leader'], 'leaderFullName' => $data['leaderFullName'], 'image' => $data["followerImage"]));
     $followersIds = $this->userRepository->getFollowersIds($data['follower']);
     $translatedMessage = $this->translator->trans($notification->getTranslationKey(), array('%name%' => $data['followerFullName'], '%leader%' => $data['leaderFullName']));
     $notification->setMessage($translatedMessage);
     foreach ($followersIds as $followerId) {
         $this->addPushMessage($notification, $followerId);
     }
     return $notification;
 }
 /**
  * @param TranslatableLabel $label
  * @param Form $form
  */
 protected function managePlural($label, $message, $form, $locale)
 {
     $labelManager = $this->labelManager;
     $explicitRules = array();
     $standardRules = array();
     $labelManager->getPluralForms($message, $standardRules, $explicitRules);
     for ($i = 0; $i < max(2, count($standardRules)); $i++) {
         $form->add(self::PLURAL_FIELD_PREFIX . $i, $labelManager->getValueFieldType($label), array('required' => false, 'label' => sprintf('bigfoot_core.translatable_label.plural.standard_%s', $i), 'data' => isset($standardRules[$i]) ? $standardRules[$i] : '', 'mapped' => false, 'attr' => array('data-locale' => $locale)));
     }
     foreach ($explicitRules as $interval => $value) {
         $form->add(self::PLURAL_FIELD_PREFIX . $labelManager->transformInterval($interval), $labelManager->getValueFieldType($label), array('required' => false, 'label' => $this->translator->trans('bigfoot_core.translatable_label.plural.explicit', array('%interval%' => $interval)), 'data' => $value, 'mapped' => false, 'attr' => array('data-locale' => $locale)));
     }
 }
 /**
  * @param array $data
  *
  * @return Notification
  */
 public function create($data)
 {
     $notification = new Notification();
     $notification->setName(Notification::LEADER_WISH);
     $notification->setContent(array('wish' => $data['wish'], 'userFullName' => $data['userFullName'], 'user' => $data['user'], 'restaurant' => $data['restaurant'], 'restaurantName' => $data['restaurantName'], 'image' => $data['image']));
     $translatedMessage = $this->translator->trans($notification->getTranslationKey(), array('%name%' => $data['userFullName'], '%restaurant%' => $data['restaurantName']));
     $notification->setMessage($translatedMessage);
     $followersIds = $this->userRepository->getFollowersIdsWithWish($data['user'], $data['wish']);
     foreach ($followersIds as $followersId) {
         $this->addPushMessage($notification, $followersId);
     }
     return $notification;
 }
 /**
  * @param array $data
  *
  * @return Notification
  */
 public function create($data)
 {
     $leaderId = $data['leader'];
     $notification = new Notification();
     $notification->setName(Notification::NEW_FOLLOWER);
     $notification->setContent(array('follower' => $data['follower'], 'followerFullName' => $data['followerFullName'], 'image' => $data['followerImage']));
     $translatedMessage = $this->translator->trans($notification->getTranslationKey(), array('%name%' => $data['followerFullName']));
     $notification->setMessage($translatedMessage);
     $pushMessage = new PushMessage();
     $pushMessage->setNotification($notification);
     $pushMessage->setUser($this->entityManager->getReference(User::CLASS_NAME, $leaderId));
     $notification->addPushMessage($pushMessage);
     return $notification;
 }
Пример #20
0
 /**
  * @param string $key
  * @param array $parameters
  * @param bool $case_insensitive
  * @param string $domain
  * @param string $locale
  * @return string
  */
 public function trans($key, $parameters = [], $case_insensitive = false, $domain = 'messages', $locale = null)
 {
     $v = $this->translator->trans($key, $parameters, $domain, $locale);
     if ($case_insensitive) {
         if ($v == $key) {
             $lkey = strtolower($key);
             $v = $this->translator->trans($lkey, $parameters, $domain, $locale);
             if ($v == $lkey) {
                 return $key;
             }
         }
     }
     return $v;
 }
Пример #21
0
 /**
  * @Extra\Route(
  *      "/export",
  *      name="weaving_the_web_api_export_perspectives",
  *      options={"expose"=true}
  * )
  * @Extra\Method({"POST"})
  */
 public function exportAction()
 {
     $command = $this->exportPerspectiveCommand->getName();
     if ($this->jobRepository->idleJobExistsForCommand($command)) {
         $message = $this->translator->trans('perspective.job.existing', [], 'perspective');
         return new JsonResponse(['result' => $message, 'type' => 'error'], 429);
     } else {
         $token = $this->tokenStorage->getToken();
         $job = $this->jobRepository->makeCommandJob($command, $token->getUser());
         $this->entityManager->persist($job);
         $this->entityManager->flush();
         $message = $this->translator->trans('perspective.job.submitted', [], 'perspective');
         return new JsonResponse(['job' => ['entity' => 'job', 'id' => $job->getId(), 'Id' => $job->getId(), 'Status' => $this->jobRepository->getTranslatedStatusMessage($job), 'rlk_Output' => $job->getOutput(), 'Date' => $job->getCreatedAt()->format('Y-m-d H:i')], 'status' => $message, 'type' => 'success']);
     }
 }
 public function onResettingResetInitialize(UserEvent $event)
 {
     $token = $event->getUser()->getConfirmationToken();
     $user = $event->getManager()->findUserByConfirmationToken($token);
     if (is_null($user)) {
         $this->flashBag->add(FlashBagEvents::MESSAGE_TYPE_ERROR, $this->translator->trans('security.resetting.reset.errors.invalid_token'));
         $event->setHasError(true);
     } elseif (!$user->isPasswordRequestNonExpired($this->tokenTll)) {
         $this->flashBag->add(FlashBagEvents::MESSAGE_TYPE_ERROR, $this->translator->trans('security.resetting.reset.errors.expired_token'));
         $event->setHasError(true);
     } else {
         $user->setSalt($event->getUser()->getSalt());
         $event->setUser($user);
     }
 }
Пример #23
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function trans($id, array $parameters = array(), $domain = 'core', $locale = null, $return_default_if_not_available = true, $useFallback = true)
 {
     if (null === $locale) {
         $locale = $this->getLocale();
     }
     if (!isset($this->catalogues[$locale])) {
         $this->loadCatalogue($locale);
     }
     // global translations
     if ($useFallback) {
         $fallbackId = sprintf(self::GLOBAL_FALLBACK_KEY, $domain, (string) $id);
         if ($this->catalogues[$locale]->has($fallbackId, self::GLOBAL_FALLBACK_DOMAIN)) {
             return parent::trans($fallbackId, $parameters, self::GLOBAL_FALLBACK_DOMAIN, $locale);
         }
         if ($this->catalogues[$locale]->has($id, self::GLOBAL_FALLBACK_DOMAIN)) {
             // global translations
             return parent::trans($id, $parameters, self::GLOBAL_FALLBACK_DOMAIN, $locale);
         }
     }
     if ($this->catalogues[$locale]->has((string) $id, $domain)) {
         return parent::trans($id, $parameters, $domain, $locale);
     } else {
         if ($return_default_if_not_available) {
             return strtr($id, $parameters);
         } else {
             return '';
         }
     }
 }
Пример #24
0
 /**
  * @param InputInterface $input
  * @return User
  * @throws AccessDeniedException
  */
 private function userCasTicketVerification(InputInterface $input)
 {
     $cookieTGC = $input->getOption('cookieTGC');
     $username = $input->getArgument('username');
     if (!empty($cookieTGC) && !empty($username)) {
         $user = new User($username, $this->getContainer()->getParameter('api_recolnat_base_uri'), $this->getContainer()->getParameter('api_recolnat_user_path'), []);
         $verifySsl = true;
         $requestOptions = $this->getContainer()->getParameter('request_options');
         if (isset($requestOptions['verify']) && !$requestOptions['verify']) {
             $verifySsl = false;
         }
         try {
             $user->isGrantedByCheckServiceTicket($cookieTGC, $this->getContainer()->getParameter('server_login_url'), $this->getContainer()->getParameter('api_recolnat_server_ticket_path'), $this->getContainer()->getParameter('api_recolnat_auth_service_url'), $verifySsl);
         } catch (\Exception $e) {
             /*$this->log($input->getArgument('username').' '.$this->translator->trans('access.denied.wrongPermission',
               [], 'exceptions'));*/
             throw new AccessDeniedException($this->translator->trans('access.denied.wrongPermission', [], 'exceptions'));
         }
     } else {
         /*$this->log($input->getArgument('username').' '.$this->translator->trans('access.denied.tgc_username', [],
           'exceptions'));*/
         throw new AccessDeniedException($this->translator->trans('access.denied.tgc_username', [], 'exceptions'));
     }
     return $user;
 }
 /**
  * @dataProvider getFlattenedTransTests
  */
 public function testFlattenedTrans($expected, $messages, $id)
 {
     $translator = new Translator('en', new MessageSelector());
     $translator->addLoader('array', new ArrayLoader());
     $translator->addResource('array', $messages, 'fr', '');
     $this->assertEquals($expected, $translator->trans($id, array(), '', 'fr'));
 }
Пример #26
0
 /**
  * @dataProvider getTransTests
  */
 public function testTrans($expected, $id, $translation, $parameters, $locale, $domain)
 {
     $translator = new Translator('en', new MessageSelector());
     $translator->addLoader('array', new ArrayLoader());
     $translator->addResource('array', array($id => $translation), $locale, $domain);
     $this->assertEquals($expected, $translator->trans($id, $parameters, $domain, $locale));
 }
 /**
  * @param array $data
  *
  * @return Notification
  */
 public function create($data)
 {
     $userId = $data['user'];
     $reviewId = $data['review'];
     $newTaggedFriendsIdsString = $data['newTaggedFriends'];
     $notification = new Notification();
     $notification->setName(Notification::NEW_TAGGED_FRIENDS);
     $notification->setContent(array('review' => $reviewId, 'restaurant' => $data['restaurant'], 'restaurantName' => $data['restaurantName'], 'user' => $data['user'], 'userFullName' => $data['userFullName'], 'image' => $data['image']));
     $translatedMessage = $this->translator->trans($notification->getTranslationKey(), array('%name%' => $data['userFullName'], '%restaurant%' => $data['restaurantName']));
     $notification->setMessage($translatedMessage);
     $newTaggedFriendsIds = explode(',', $newTaggedFriendsIdsString);
     foreach ($newTaggedFriendsIds as $newTaggedFriendId) {
         $this->addPushMessage($notification, $newTaggedFriendId);
     }
     return $notification;
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int
  * @throws \Exception
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $baseUrl = $input->getOption(self::OPTION_BASE_URL);
     if (is_null($baseUrl)) {
         throw new \Exception('Invalid base URL');
     }
     $callbackUri = $this->router->generate('weaving_the_web_api_oauth_callback');
     $redirectUrl = $baseUrl . $callbackUri;
     $client = $this->clientRepository->make($redirectUrl);
     $successMessage = $this->translator->trans('oauth.client.authorization_url', ['{{ authorizaton_url }}' => $client->getAuthorizationUrl(), '{{ client_id }}' => $client->getPublicId(), '{{ client_secret }}' => $client->getSecret()], 'authorization');
     $output->writeln($successMessage);
     $successMessage = $this->translator->trans('oauth.client.creation_success', [], 'authorization');
     $output->writeln($successMessage);
     $returnCode = 0;
     return $returnCode;
 }
Пример #29
0
 /**
  * Fetches the user data via adLDAP and stores it in the provided $user.
  *
  * @param AdUser|User $user
  * @param TokenInterface $token
  * @param adLDAP $adLdap
  * @return bool
  * @throws \Exception
  */
 public function fetchData(AdUser $user, TokenInterface $token, adLDAP $adLdap)
 {
     $connected = $adLdap->connect();
     $isAD = $adLdap->authenticate($user->getUsername(), $token->getCredentials());
     if (!$isAD || !$connected) {
         $msg = $this->translator->trans('riper.security.active_directory.ad.bad_response', array('%connection_status%' => var_export($connected, 1), '%is_AD%' => var_export($isAD, 1)));
         throw new \Exception($msg);
     }
     /** @var adLDAPUserCollection $userCollection */
     $userCollection = $adLdap->user()->infoCollection($user->getUsername(), array('*'));
     if ($userCollection) {
         $user->setDisplayName($userCollection->displayName);
         $user->setUuid($adLdap->utilities()->decodeGuid($userCollection->objectguid));
         $user->setEmail($userCollection->mail);
         $user->setPassword($token->getCredentials());
         $roles = ['ROLE_USER'];
         if (in_array($userCollection->mail, $this->config['admin_emails'], true)) {
             $roles[] = 'ROLE_ADMIN';
         }
         $user->setRoles($roles);
         $this->userService->saveLDAPUserData($user);
         return true;
     }
     return false;
 }
Пример #30
0
 /**
  * Fetches the user data via adLDAP and stores it in the provided $user.
  *
  * @param AdUser|User $user
  * @param TokenInterface $token
  * @param adLDAP $adLdap
  * @return bool
  * @throws \Exception
  */
 public function fetchData(AdUser $user, TokenInterface $token, adLDAP $adLdap)
 {
     $connected = $adLdap->connect();
     $isAD = $adLdap->authenticate($user->getUsername(), $token->getCredentials());
     if (!$isAD || !$connected) {
         $msg = $this->translator->trans('riper.security.active_directory.ad.bad_response', array('%connection_status%' => var_export($connected, 1), '%is_AD%' => var_export($isAD, 1)));
         throw new \Exception($msg);
     }
     /** @var adLDAPUserCollection $userCollection */
     $userCollection = $adLdap->user()->infoCollection($user->getUsername(), array('*'));
     if ($userCollection) {
         $groups = $adLdap->user()->groups($user->getUsername(), $this->recursiveGrouproles);
         $sfRoles = array();
         $sfRolesTemp = array();
         foreach ($groups as $r) {
             if (in_array($r, $sfRolesTemp) === false) {
                 $sfRoles[] = 'ROLE_' . strtoupper(str_replace(' ', '_', $r));
                 $sfRolesTemp[] = $r;
             }
         }
         $user->setRoles($sfRoles);
         unset($sfRolesTemp);
         $user->setDisplayName($userCollection->displayName);
         $user->setUuid($adLdap->utilities()->decodeGuid($userCollection->objectguid));
         $user->setEmail($userCollection->mail);
         $user->setRoles(['ROLE_USER']);
         $user->setPassword($token->getCredentials());
         return true;
     }
     return false;
 }