Author: Fabien Potencier (fabien@symfony.com)
Inheritance: implements Symfony\Component\Translation\TranslatorInterface
 /**
  * {@inheritdoc}
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $i18nPath = dirname(dirname(dirname(dirname(dirname(__DIR__))))) . DIRECTORY_SEPARATOR . 'i18n.php';
     foreach (require $i18nPath as $lang => $messages) {
         $this->translator->addResource('array', $messages, $lang, 'output');
     }
 }
 /**
  * @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);
 }
 /**
  * @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;
         }
     }
 }
Exemple #4
0
 /**
  * @dataProvider getTransChoiceTests
  */
 public function testTransChoice($expected, $id, $translation, $number, $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->transChoice($id, $number, $parameters, $domain, $locale));
 }
    public function testDefaultTranslationDomain()
    {
        $templates = array('index' => '
                {%- extends "base" %}

                {%- trans_default_domain "foo" %}

                {%- block content %}
                    {%- trans %}foo{% endtrans %}
                    {%- trans from "custom" %}foo{% endtrans %}
                    {{- "foo"|trans }}
                    {{- "foo"|trans({}, "custom") }}
                    {{- "foo"|transchoice(1) }}
                    {{- "foo"|transchoice(1, {}, "custom") }}
                {% endblock %}
            ', 'base' => '
                {%- block content "" %}
            ');
        $translator = new Translator('en', new MessageSelector());
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foo (messages)'), 'en');
        $translator->addResource('array', array('foo' => 'foo (custom)'), 'en', 'custom');
        $translator->addResource('array', array('foo' => 'foo (foo)'), 'en', 'foo');
        $template = $this->getTemplate($templates, $translator);
        $this->assertEquals('foo (foo)foo (custom)foo (foo)foo (custom)foo (foo)foo (custom)', trim($template->render(array())));
    }
 public function register()
 {
     $di = $this->getContainer();
     $config = $this->getConfig();
     $di->add($config['message_selector_class']);
     foreach ($config['loaders'] as $name => $class) {
         $di->add($class);
         $di->add('translation.loader.' . $name, $class);
     }
     $di->add('Symfony\\Component\\Translation\\Translator', function () use($di, $config) {
         $selector = $di->get($config['message_selector_class']);
         $translator = new Translator($config['locale'], $selector);
         $translator->setFallbackLocales($config['fallback_locales']);
         foreach ($config['loaders'] as $name => $class) {
             $translator->addLoader($name, $di->get('translation.loader.' . $name));
         }
         foreach ($config['resources'] as $locale => $resources) {
             foreach ($resources as $config) {
                 list($loader, $arg, $domain) = $config + ['array', [], 'messages'];
                 $translator->addResource($loader, $arg, $locale, $domain);
             }
         }
         return $translator;
     }, true);
     $di->add('Laasti\\SymfonyTranslationProvider\\TranslationArray')->withArgument('Symfony\\Component\\Translation\\Translator');
 }
Exemple #7
0
 public function render($route, $log = null)
 {
     $template_path = $route->join('/') . '/' . $this->context->template . '.tpl';
     $template_base_path = APP_ROOT . '/Views';
     $cache = false;
     if (isset(\Config\Base::$caching) && \Config\Base::$caching == true) {
         $cache = \Config\Base::$caching['twig'] ? APP_ROOT . '/cache' : false;
     }
     $loader = new \Bacon\Loader($template_base_path, $template_path);
     $twig = new \Twig_Environment($loader, ['cache' => $cache, 'auto_reload' => true]);
     if (!empty($this->context->template_base_paths)) {
         foreach ($this->context->template_base_paths as $path) {
             $loader->addPath($path);
         }
     }
     if (!empty($this->context->filters)) {
         foreach ($this->context->filters->getArrayCopy() as $name => $function) {
             $filter_function = new \Twig_Filter_Function($function, ['is_safe' => ['html']]);
             $twig->addFilter($name, $filter_function);
         }
     }
     if (!empty($this->context->locale)) {
         $locale = $this->context->locale;
         $translator = new Translator($locale, new MessageSelector());
         $translator->addLoader('po', new PoFileLoader());
         $translator->addResource('po', APP_ROOT . '/locales/' . $locale . '/' . $this->context->locale_file . '.po', $locale);
         $twig->addExtension(new \Symfony\Bridge\Twig\Extension\TranslationExtension($translator));
     }
     echo $twig->render($template_path, $this->context->getArrayCopy());
 }
 public function loader($locale = 'es_ES')
 {
     $Translator = new Translator($locale);
     $Translator->addLoader('array', new ArrayLoader());
     $data = array();
     $part_locale = explode('_', $locale);
     $bundles = Service::getBundles();
     foreach ($bundles as $bundle) {
         $path_i18n = str_replace('\\', '/', $bundle->getPath() . '/i18n/' . $part_locale[0]);
         if (is_dir($path_i18n)) {
             $finder = new Finder();
             $finder->files()->name('*.i18n.php')->in($path_i18n);
             // Une todos los esquemas en un solo array
             foreach ($finder as $file) {
                 $_a = (require $file->getRealpath());
                 $data = array_merge($data, $_a);
             }
         }
     }
     $path_i18n = str_replace('\\', '/', Ki_APP . 'src/i18n/' . $part_locale[0]);
     if (is_dir($path_i18n)) {
         $finder = new Finder();
         $finder->files()->name('*.i18n.php')->in($path_i18n);
         // Une todos los esquemas en un solo array
         foreach ($finder as $file) {
             $_a = (require $file->getRealpath());
             $data = array_merge($data, $_a);
         }
     }
     $Translator->addResource('array', $data, $locale);
     $this->Translator = $Translator;
 }
 /**
  * {@inheritdoc}
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     if (!$input->getOption('lang')) {
         return;
     }
     $this->translator->setLocale($input->getOption('lang'));
 }
 /**
  * @return TranslatorInterface
  */
 private function addResourcesToTranslator(Translator $translator)
 {
     foreach ($this->resourceFinder->findInDirectory($this->translationDir) as $resource) {
         $translator->addResource($resource['format'], $resource['pathname'], $resource['locale'], $resource['domain']);
     }
     return $translator;
 }
 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');
 }
 /**
  * @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']);
         }
     }
 }
Exemple #13
0
 /**
  * Create translator
  *
  * @return Translator
  */
 public static function create(ServiceContainer $app)
 {
     $locale = $app->session->get('user.locale', 'en_US');
     $translator = new Translator($locale, new MessageSelector());
     $translator->addLoader('mo', new MoFileLoader());
     return $translator;
 }
 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 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'));
     }
 }
 /**
  * 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;
 }
Exemple #17
0
 /**
  * Plural rules for russian language.
  */
 public static function ru($string, $number)
 {
     $translator = new Translator('ru');
     $translated = $translator->trans(':count ' . $string, array(':count' => $number));
     $type = $number % 10 == 1 && $number % 100 != 11 ? 0 : ($number % 10 >= 2 && $number % 10 <= 4 && ($number % 100 < 10 || $number % 100 >= 20) ? 1 : 2);
     $translated_array = explode("|", $translated);
     return $translated_array[$type];
 }
Exemple #18
0
function configure()
{
    $translator = new Translator("fr_FR", new MessageSelector());
    $translator->setFallbackLocales(array("fr"));
    $translator->addLoader("array", new ArrayLoader());
    $translator->addResource("array", array("Hello World!" => "Bonjour"), "fr");
    Yasc_App::config()->addOption("translator", $translator);
}
 public function runTest()
 {
     $translator = new Translator("fr_FR", new MessageSelector());
     $translator->addLoader("array", new ArrayLoader());
     $translator->addResource("array", array("Hello World!" => "Bonjour", "Symfony is great" => "Symfony est le meuilleur", "Hello %name%" => "Bonjour %name%", "apple.choice" => "Une pomme | %count% pommes"), "fr_FR");
     $translator->setFallbackLocales(array("en"));
     (new TranslationValidator($translator))->validate();
 }
Exemple #20
0
 public function register(Application $app, array $options = array())
 {
     $translator = new Translator('en', new MessageSelector());
     $translator->setFallbackLocale('en');
     $translator->addLoader('array', new ArrayLoader());
     $translator->addLoader('xliff', new XliffFileLoader());
     return $translator;
 }
Exemple #21
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;
 }
 public function extendTranslator(Translator $translator, Application $app)
 {
     $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
     foreach ($app['locales'] as $locale) {
         $translator->addResource('yaml', LOCALES . '/' . $locale . '.yml', $locale);
     }
     return $translator;
 }
 public function setUp()
 {
     date_default_timezone_set('Europe/London');
     $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
     $this->pool = new Pool($container, '', '');
     $this->pool->setAdminServiceIds(array('sonata_admin_foo_service'));
     $this->pool->setAdminClasses(array('fooClass' => array('sonata_admin_foo_service')));
     $this->logger = $this->getMock('Psr\\Log\\LoggerInterface');
     $this->twigExtension = new SonataAdminExtension($this->pool, $this->logger);
     $loader = new StubFilesystemLoader(array(__DIR__ . '/../../../Resources/views/CRUD'));
     $this->environment = new \Twig_Environment($loader, array('strict_variables' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0));
     $this->environment->addExtension($this->twigExtension);
     // translation extension
     $translator = new Translator('en', new MessageSelector());
     $translator->addLoader('xlf', new XliffFileLoader());
     $translator->addResource('xlf', __DIR__ . '/../../../Resources/translations/SonataAdminBundle.en.xliff', 'en', 'SonataAdminBundle');
     $this->environment->addExtension(new TranslationExtension($translator));
     // routing extension
     $xmlFileLoader = new XmlFileLoader(new FileLocator(array(__DIR__ . '/../../../Resources/config/routing')));
     $routeCollection = $xmlFileLoader->load('sonata_admin.xml');
     $xmlFileLoader = new XmlFileLoader(new FileLocator(array(__DIR__ . '/../../Fixtures/Resources/config/routing')));
     $testRouteCollection = $xmlFileLoader->load('routing.xml');
     $routeCollection->addCollection($testRouteCollection);
     $requestContext = new RequestContext();
     $urlGenerator = new UrlGenerator($routeCollection, $requestContext);
     $this->environment->addExtension(new RoutingExtension($urlGenerator));
     $this->environment->addExtension(new \Twig_Extensions_Extension_Text());
     $this->twigExtension->initRuntime($this->environment);
     // initialize object
     $this->object = new \stdClass();
     // initialize admin
     $this->admin = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $this->admin->expects($this->any())->method('getCode')->will($this->returnValue('xyz'));
     $this->admin->expects($this->any())->method('id')->with($this->equalTo($this->object))->will($this->returnValue(12345));
     $this->admin->expects($this->any())->method('getNormalizedIdentifier')->with($this->equalTo($this->object))->will($this->returnValue(12345));
     $this->admin->expects($this->any())->method('trans')->will($this->returnCallback(function ($id) {
         return $id;
     }));
     $this->adminBar = $this->getMock('Sonata\\AdminBundle\\Admin\\AdminInterface');
     $this->adminBar->expects($this->any())->method('isGranted')->will($this->returnValue(true));
     $this->adminBar->expects($this->any())->method('getNormalizedIdentifier')->with($this->equalTo($this->object))->will($this->returnValue(12345));
     // for php5.3 BC
     $admin = $this->admin;
     $adminBar = $this->adminBar;
     $container->expects($this->any())->method('get')->will($this->returnCallback(function ($id) use($admin, $adminBar) {
         if ($id == 'sonata_admin_foo_service') {
             return $admin;
         } elseif ($id == 'sonata_admin_bar_service') {
             return $adminBar;
         }
         return;
     }));
     // initialize field description
     $this->fieldDescription = $this->getMock('Sonata\\AdminBundle\\Admin\\FieldDescriptionInterface');
     $this->fieldDescription->expects($this->any())->method('getName')->will($this->returnValue('fd_name'));
     $this->fieldDescription->expects($this->any())->method('getAdmin')->will($this->returnValue($this->admin));
     $this->fieldDescription->expects($this->any())->method('getLabel')->will($this->returnValue('Data'));
 }
 public function testSetTranslator()
 {
     $t = new Translator('fr');
     $t->addLoader('array', new ArrayLoader());
     CarbonInterval::setTranslator($t);
     $t = CarbonInterval::getTranslator();
     $this->assertNotNull($t);
     $this->assertSame('fr', $t->getLocale());
 }
 /**
  * @expectedException \RuntimeException
  */
 public function testNonEnumLoad()
 {
     $yml_loader = new YamlFileLoader();
     $loader = new EnumLoader($yml_loader);
     $translator = new Translator("en");
     $translator->addLoader("enum", $loader);
     $translator->addResource("enum", __DIR__ . "/../Mock/Resources/translations/enum.en.yml", "en", "phpunit");
     $translator->trans(0, [], "phpunit");
 }
 /**
  * @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())));
 }
Exemple #27
0
/**
 * Create translator
 *
 * @return Translator
 */
function translator($locale = 'en_US')
{
    static $translator = null;
    if ($translator === null) {
        $translator = new Translator($locale, new MessageSelector());
        $translator->addLoader('mo', new MoFileLoader());
    }
    return $translator;
}
Exemple #28
0
 public function getFormattedErrors(Translator $translator)
 {
     $formattedErrors = array();
     foreach ($this->errors as $error) {
         /** @var $error ConstraintViolation */
         $formattedErrors[$error->getPropertyPath()][] = $translator->trans($error->getMessage(), array(), 'validators');
     }
     return $formattedErrors;
 }
Exemple #29
0
 /**
  * @dataProvider providerLocales
  *
  * @param string $locale
  */
 public function testSetTranslator($locale)
 {
     $t = new Translator($locale);
     $t->addLoader('array', new ArrayLoader());
     Date::setTranslator($t);
     $t = Date::getTranslator();
     $this->assertNotNull($t);
     $this->assertSame($locale, $t->getLocale());
 }
/**
 * @param ContainerInterface $container
 * @return Translator
 */
function loadTranslator(ContainerInterface $container)
{
    $translator = new Translator('ru');
    $translator->addLoader('xlf', new XliffFileLoader());
    $translator->addResource('xlf', VENDOR_PATH . 'symfony/form/Resources/translations/validators.ru.xlf', 'ru', 'validators');
    $translator->addResource('xlf', VENDOR_PATH . 'symfony/validator/Resources/translations/validators.ru.xlf', 'ru', 'validators');
    $container->set('translator', $translator);
    return $translator;
}