/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addEventSubscriber(new CleanFormSubscriber()); $builder->addEventSubscriber(new FormExitSubscriber('user.user', $options)); $builder->add('username', 'text', array('label' => 'mautic.core.username', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'preaddon' => 'fa fa-user', 'autocomplete' => 'off'))); $builder->add('firstName', 'text', array('label' => 'mautic.core.firstname', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'))); $builder->add('lastName', 'text', array('label' => 'mautic.core.lastname', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'))); $positions = $this->model->getLookupResults('position', null, 0, true); $builder->add('position', 'text', array('label' => 'mautic.core.position', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'data-options' => json_encode($positions)), 'required' => false)); $builder->add('email', 'email', array('label' => 'mautic.core.type.email', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'preaddon' => 'fa fa-envelope'))); $existing = !empty($options['data']) && $options['data']->getId(); $placeholder = $existing ? $this->translator->trans('mautic.user.user.form.passwordplaceholder') : ''; $required = $existing ? false : true; $builder->add('plainPassword', 'repeated', array('first_name' => 'password', 'first_options' => array('label' => 'mautic.core.password', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'placeholder' => $placeholder, 'tooltip' => 'mautic.user.user.form.help.passwordrequirements', 'preaddon' => 'fa fa-lock', 'autocomplete' => 'off'), 'required' => $required, 'error_bubbling' => false), 'second_name' => 'confirm', 'second_options' => array('label' => 'mautic.user.user.form.passwordconfirm', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control', 'placeholder' => $placeholder, 'tooltip' => 'mautic.user.user.form.help.passwordrequirements', 'preaddon' => 'fa fa-lock', 'autocomplete' => 'off'), 'required' => $required, 'error_bubbling' => false), 'type' => 'password', 'invalid_message' => 'mautic.user.user.password.mismatch', 'required' => $required, 'error_bubbling' => false)); $builder->add('timezone', 'timezone', array('label' => 'mautic.core.timezone', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'), 'multiple' => false, 'empty_value' => 'mautic.user.user.form.defaulttimezone')); $builder->add('locale', 'choice', array('choices' => $this->supportedLanguages, 'label' => 'mautic.core.language', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'), 'multiple' => false, 'empty_value' => 'mautic.user.user.form.defaultlocale')); if (empty($options['in_profile'])) { $builder->add($builder->create('role', 'entity', array('label' => 'mautic.user.role', 'label_attr' => array('class' => 'control-label'), 'attr' => array('class' => 'form-control'), 'class' => 'MauticUserBundle:Role', 'property' => 'name', 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('r')->where('r.isPublished = true')->orderBy('r.name', 'ASC'); }))); $builder->add('isPublished', 'yesno_button_group'); $builder->add('buttons', 'form_buttons'); } else { $builder->add('buttons', 'form_buttons', array('save_text' => 'mautic.core.form.apply', 'apply_text' => false)); } if (!empty($options["action"])) { $builder->setAction($options["action"]); } }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { // Build a list of columns $builder->add('column', 'choice', array('choices' => $options['columnList'], 'expanded' => false, 'multiple' => false, 'label' => 'mautic.report.report.label.filtercolumn', 'label_attr' => array('class' => 'control-label'), 'empty_value' => false, 'required' => false, 'attr' => array('class' => 'form-control filter-columns'))); // Direction $builder->add('direction', 'choice', array('choices' => array('ASC' => $this->translator->trans('mautic.report.report.label.tableorder_dir.asc'), 'DESC' => $this->translator->trans('mautic.report.report.label.tableorder_dir.desc')), 'expanded' => false, 'multiple' => false, 'label' => 'mautic.core.order', 'label_attr' => array('class' => 'control-label'), 'empty_value' => false, 'required' => false, 'attr' => array('class' => 'form-control not-chosen'))); }
public function onKernelRequest(GetResponseEvent $event) { if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) { return; } $request = $event->getRequest(); $fc_form = $this->form_service->guessFcForm($request); if (!$fc_form instanceof FcForm) { return; } if ($fc_form->getAction()) { return; } /** @var FormInterface $form */ $form = $this->form_service->create($fc_form); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $this->form_service->clear($fc_form, array('template' => $data['_template'], 'data' => $this->form_service->initData($data))); if ($fc_form->getIsAjax()) { return; } if ($fc_form->getMessage()) { $message = $fc_form->getMessage(); } else { $message = $this->translator->trans('fc.message.form.is_valid', array(), 'FenrizbesFormConstructorBundle'); } // TODO: Связывать сообщение с конкретной формой и подчищать старые $this->session->getFlashBag()->add('fc_form.success', $message); $response = new RedirectResponse($this->router->generate($request->get('_route'), $request->get('_route_params'))); $event->setResponse($response); } }
public function __construct(Loader $loader, EventDispatcherInterface $eventDispatcher, Translator $translator) { $this->loader = $loader; $this->eventDispatcher = $eventDispatcher; $this->translator = $translator; $translator->addLoader('array', new ArrayLoader()); }
/** * Permet de retourner une erreur ajax avec le bon message en fonction du code erreur envoyé * @param $errorCode * @param string $notificationType * @param null $infos * @param null $specificMessage * @return Response */ public function returnAjaxError($errorCode, $notificationType = 'error', $infos = null, $specificMessage = null) { switch ($errorCode) { case 103: $message = 'La recherche est vide'; break; case 130: case 131: case 132: $message = 'Vous n\'êtes pas autorisé à accéder à cette page (seulement ROLE_SUPER_ADMIN)'; break; case 200: $message = 'Tout a fonctionné correctement'; break; default: $message = $this->translator->trans('bo.global.errorProcessing', array(), 'messages'); break; } $message .= ' - ' . $errorCode; if (null !== $infos) { $message .= ' (' . $infos . ')'; } if (null !== $specificMessage) { $message = $specificMessage; } $return = json_encode(array('responseCode' => $errorCode, 'message' => $message, 'notification' => $notificationType)); return new Response($return, 200, array('Content-Type' => 'application/json')); }
public function getTranslator($loader, $options = array()) { $translator = new Translator($this->getContainer($loader), $this->getMock('Symfony\\Component\\Translation\\MessageSelector'), array('loader' => 'loader'), $options); $translator->addResource('loader', 'foo', 'fr'); $translator->addResource('loader', 'foo', 'en'); return $translator; }
/** * Breadcrumbs * * @param Request $request * * @return mixed */ public function createBreadcrumbsMenu(Request $request) { $menu = $this->factory->createItem('root'); $menu->setUri($request->getRequestUri()); $menu->addChild($this->translator->trans('Главная'), array('route' => 'homepage')); return $menu; }
public function departmentLabel($code) { try { return $this->departements->getLabel($code, true); } catch (\InvalidArgumentException $e) { return $this->translator->trans('report.company_departement.unknown'); } }
public function sendWelcomeEmail(User $user) { $token = $this->tokenGenerator->generateToken(); $link = $this->router->generate('fos_user_registration_register', array('token' => $token), true); $this->mailer->sendMail($this->translator->trans('jwkh.publishers.email.welcome.subject', array(), null, $user->getPublisher()->getCongregation()->getDefaultLocale()), '*****@*****.**', $user->getEmail(), $this->translator->trans('jwkh.publishers.email.welcome.body', array('%link%' => $link), null, $user->getPublisher()->getCongregation()->getDefaultLocale())); $user->setConfirmationToken($token); $this->userManager->updateUser($user); }
public function createMainMenu(Request $request, Translator $translator, SecurityContext $securityContext) { $menu = $this->factory->createItem('root'); $menu->setCurrentUri($request->getRequestUri()); $menu->addChild('bundles', array('route' => 'bundle_list'))->setLabel($translator->trans('menu.bundles')); $menu->addChild('users', array('route' => 'user_list'))->setLabel($translator->trans('menu.users')); $menu->addChild('evolution', array('route' => 'evolution'))->setLabel($translator->trans('menu.evolution')); $menu->addChild('add-bundle', array('route' => 'add_bundle'))->setLabel($translator->trans('menu.addBundleManually')); return $menu; }
/** * @param OAuthEvent $event * * @throws AccessDeniedException */ public function onPreAuthorizationProcess(OAuthEvent $event) { if ($user = $this->getUser($event)) { //check to see if user has api access if (!$this->mauticSecurity->isGranted('api:access:full')) { throw new AccessDeniedException($this->translator->trans('mautic.core.error.accessdenied', [], 'flashes')); } $client = $event->getClient(); $event->setAuthorizedClient($client->isAuthorizedClient($user, $this->em)); } }
/** * Returns a DQL expression that can be used to get a text representation of the given type of entities. * * @param string $format The representation format, for example full, short, etc. * @param string|null $locale The representation locale. * @param string $className The FQCN of the entity * @param string $alias The alias in SELECT or JOIN statement * * @return string A DQL expression or FALSE if this provider cannot return reliable result */ public function getNameDQL($format, $locale, $className, $alias) { if ($className === self::CLASS_NAME) { if ($format === self::SHORT) { return $alias . 'label'; } else { return sprintf('CONCAT(%s.label, \' %s\')', $alias, $this->translator->trans('oro.email.mailbox.entity_label', [], null, $locale)); } } return false; }
/** * Adds an action to the list of available . * * @param string $key - a unique identifier; it is recommended that it be namespaced i.e. lead.action * @param array $event - can contain the following keys: * 'label' => (required) what to display in the list * 'description' => (optional) short description of event * 'template' => (optional) template to use for the action's HTML in the point builder * i.e AcmeMyBundle:PointAction:theaction.html.php * 'formType' => (optional) name of the form type SERVICE for the action * 'formTypeOptions' => (optional) array of options to pass to formType * 'callback' => (required) callback function that will be passed when the action is triggered * The callback function can receive the following arguments by name (via ReflectionMethod::invokeArgs()) * Mautic\CoreBundle\Factory\MauticFactory $factory * Mautic\PointBundle\Entity\TriggerEvent $event * Mautic\LeadBundle\Entity\Lead $lead * * @return void * @throws InvalidArgumentException */ public function addEvent($key, array $event) { if (array_key_exists($key, $this->events)) { throw new InvalidArgumentException("The key, '{$key}' is already used by another action. Please use a different key."); } //check for required keys and that given functions are callable $this->verifyComponent(array('group', 'label', 'callback'), array('callback'), $event); $event['label'] = $this->translator->trans($event['label']); $event['group'] = $this->translator->trans($event['group']); $event['description'] = isset($event['description']) ? $this->translator->trans($event['description']) : ''; $this->events[$key] = $event; }
/** * Adds an action to the list of available . * * @param string $key - a unique identifier; it is recommended that it be namespaced i.e. lead.action * @param array $action - can contain the following keys: * 'label' => (required) what to display in the list * 'description' => (optional) short description of event * 'template' => (optional) template to use for the action's HTML in the point builder * i.e AcmeMyBundle:PointAction:theaction.html.php * 'formType' => (optional) name of the form type SERVICE for the action; will use a default form with point change only * 'formTypeOptions' => (optional) array of options to pass to formType * 'callback' => (optional) callback function that will be passed when the action is triggered; return true to * change the configured points or false to ignore the action * The callback function can receive the following arguments by name (via ReflectionMethod::invokeArgs()) * Mautic\CoreBundle\Factory\MauticFactory $factory * Mautic\LeadBundle\Entity\Lead $lead * $eventDetails - variable sent from firing function to call back function * array $action = array( * 'id' => int * 'type' => string * 'name' => string * 'properties' => array() * ) * * @return void * @throws InvalidArgumentException */ public function addAction($key, array $action) { if (array_key_exists($key, $this->actions)) { throw new InvalidArgumentException("The key, '{$key}' is already used by another action. Please use a different key."); } //check for required keys and that given functions are callable $this->verifyComponent(array('group', 'label'), array('callback'), $action); //translate the label and group $action['label'] = $this->translator->trans($action['label']); $action['group'] = $this->translator->trans($action['group']); $this->actions[$key] = $action; }
/** * Adds a submit action to the list of available actions. * * @param string $key a unique identifier; it is recommended that it be namespaced i.e. lead.action * @param array $action can contain the following keys: * $action = [ * 'group' => (required) Label of the group to add this action to * 'label' => (required) what to display in the list * 'eventName' => (required) Event dispatched to execute action; it will receive a SubmissionEvent object * 'formType' => (required) name of the form type SERVICE for the action * 'allowCampaignForm' => (optional) true to allow this action for campaign forms; defaults to false * 'description' => (optional) short description of event * 'template' => (optional) template to use for the action's HTML in the form builder; * eg AcmeMyBundle:FormAction:theaction.html.php * 'formTypeOptions' => (optional) array of options to pass to formType * 'formTheme' => (optional theme for custom form views * 'validator' => (deprecated) callback function to validate form results - use addValidator() instead * 'callback' => (deprecated) callback function that will be passed the results upon a form submit; use eventName instead * ] * * @throws InvalidArgumentException */ public function addSubmitAction($key, array $action) { if (array_key_exists($key, $this->actions)) { throw new InvalidArgumentException("The key, '{$key}' is already used by another action. Please use a different key."); } //check for required keys and that given functions are callable $this->verifyComponent(['group', 'label', 'formType', ['eventName', 'callback', 'validator']], $action); $action['label'] = $this->translator->trans($action['label']); if (!isset($action['description'])) { $action['description'] = ''; } $this->actions[$key] = $action; }
/** * @param PersistentCollection $key * * @return array|mixed */ public function getConstraints(Attachment $attachment, DimensionContainer $dimensionContainer) { $constraints = array(); foreach ($this->constraints as $constraintClass) { $constraintClass->setup($attachment, $dimensionContainer); $validate = $constraintClass->validate(); if ($validate && $validate instanceof TranslatorObject) { $constraints[] = $this->translator->trans($validate->getId(), $validate->getData()); } } if (count($constraints) == 0) { return; } return $constraints; }
/** * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ protected function setUp() { $this->formatter = $this->getMockBuilder('Oro\\Bundle\\LocaleBundle\\Formatter\\DateTimeFormatter')->disableOriginalConstructor()->setMethods(array('getPattern'))->getMock(); $this->formatter->expects($this->any())->method('getPattern')->will($this->returnValueMap($this->localFormatMap)); $this->translator = $this->getMockBuilder('Symfony\\Bundle\\FrameworkBundle\\Translation\\Translator')->disableOriginalConstructor()->getMock(); $this->translator->method('trans')->will($this->returnCallback(function ($one, $two, $tree, $locale) { if ($locale == self::LOCALE_EN) { return 'MMM d'; } if ($locale == self::LOCALE_RU) { return 'd.MMM'; } return ''; })); $this->converter = $this->createFormatConverter(); }
/** * Constructor. * * Available options: * * * cache_dir: The cache directory (or null to disable caching) * * debug: Whether to enable debugging or not (false by default) * * resource_files: List of translation resources available grouped by locale. * * @param ContainerInterface $container A ContainerInterface instance * @param MessageSelector $selector The message selector for pluralization * @param array $loaderIds An array of loader Ids * @param array $options An array of options * * @throws \InvalidArgumentException */ public function __construct(ContainerInterface $container, MessageSelector $selector, $loaderIds = [], array $options = []) { $domains = $resources = []; foreach ($options['resource_files'] as $locale => $files) { foreach ($files as $file) { if (preg_match('!([^.]+)\\.([^.]+)\\.[^\\.]+$!', basename($file), $a)) { $resources[] = $file; $domains[] = $a[1]; } } } try { $locales = $container->get('octava_mui.locale_manager')->getAllAliases(); foreach ($domains as $domain) { foreach ($locales as $locale) { if (empty($options['resource_files'][$locale])) { $options['resource_files'][$locale] = []; } $options['resource_files'][$locale][] = $domain . '.' . $locale . '.zdb'; } } } catch (DBALException $e) { //for unit test, if cache empty and db scheme not created } $this->resources = $options['resource_files']; parent::__construct($container, $selector, $loaderIds, $options); }
public function getClientBillStatusText(User $client, $year, $quarter) { $status = $this->getClientBillStatus($client, $year, $quarter); if ($status < 0) { return $this->translator->transChoice('bill.accounts_require_attention', -$status, array('%count%' => -$status)); } return $this->translator->trans('bill.status' . $status); }
/** * Override the fosuserbundles original sendMessage, to embed template variables etc. into html-emails. * @param string $templateName * @param array $context * @param string $fromEmail * @param string $toEmail * @return boolean true if the mail was sent successfully, else false */ protected function sendMessage($templateName, $context, $fromEmail, $toEmail) { // get the subject from the template // => make sure the subject block exists in your fos-templates (FOSUserBundle:Registration:email.txt.twig & FOSUserBundle:Resetting:email.txt.twig) $twigTemplate = $this->loadTemplate($templateName); $subject = $twigTemplate->renderBlock('subject', $context); return $this->sendSingleEmail($toEmail, null, $subject, $context, $templateName, $this->translator->getLocale()); }
/** * @param string $label * @param string $context * @param string $type * * @return string */ public function getLabel($label, $context = '', $type = '') { $deleteStr = '_delete'; if ($context == 'breadcrumb' && substr($label, -strlen($deleteStr)) == $deleteStr) { return $this->translator->trans('admin.delete', [], 'OctavaAdminBundle'); } if (in_array($label, ['_action', 'Action'])) { return $this->translator->trans('admin._action', [], 'OctavaAdminBundle'); } if (in_array($label, ['Actions'])) { return $this->translator->trans('Actions', [], 'OctavaAdminBundle'); } if ($label == 'id') { return $this->translator->trans('admin.id', [], 'OctavaAdminBundle'); } if (in_array($label, ['created_at', 'createdAt', 'Created At'])) { return $this->translator->trans('admin.created_at', [], 'OctavaAdminBundle'); } if (in_array($label, ['updated_at', 'updatedAt', 'Updated At'])) { return $this->translator->trans('admin.updated_at', [], 'OctavaAdminBundle'); } $label = str_replace('.', '_', $label); $result = preg_replace('/^translation___(.*)___[a-z]{2}$/i', '$1', $label); $result = strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $result)); $result = 'admin.' . $result; return $result; }
/** * {@inheritdoc} */ protected function loadCatalogue($locale) { if ($locale != 'en_US') { // Always force en_US so that it's available for fallback $this->addResource('mautic', null, 'en_US', 'messages'); } $this->addResource('mautic', null, $locale, 'messages'); parent::loadCatalogue($locale); }
protected function loadCatalogue($locale) { // Schauen, ob die Cache-Datei älter als wfd_meta.last_touched ist foreach ($this->getCacheFiles($locale) as $cacheFile) { if (filemtime($cacheFile) < $this->metaQuery->getLastTouched()) { @unlink($cacheFile); } } parent::loadCatalogue($locale); }
/** * process a task * * @param integer $jobId the id of the job being processed * @param array $parameters an array of parameters * * @throws TaskException * @return void */ public function process($jobId, $parameters = array()) { $territories = $this->entityManager->getRepository('KingdomHallDataBundle:Territory')->findAll(); $tNotifs = array_filter($territories, function (Territory $territory) { return $territory->getStatus() == Territory::TERRITORY_STATUS_WARNING || $territory->getStatus() == Territory::TERRITORY_STATUS_ALERT; }); /** @var Territory $territory */ foreach ($tNotifs as $territory) { if ($territory->getPublisher()->getEmail() && $territory->getNotified() != $territory->getStatus()) { $settings = $territory->getCongregation()->getSettings(); $alertDate = clone $territory->getBorrowDate(); $alertDate->add(\DateInterval::createFromDateString('+' . $settings->get('territory_max_borrow_time')->getValue())); $this->mailer->sendMail($this->translator->trans('jwkh.territories.email.' . $territory->getStatus() . '.subject', array('%number%' => $territory->getNumber() . ' - ' . $territory->getName()), null, $territory->getCongregation()->getDefaultLocale()), '*****@*****.**', $territory->getPublisher()->getEmail(), $this->translator->trans('jwkh.territories.email.' . $territory->getStatus() . '.body', array('%firstName%' => $territory->getPublisher()->getFirstName(), '%number%' => $territory->getNumber() . ' - ' . $territory->getName(), '%date%' => $alertDate->format($settings->get('date_format_twig')->getValue())), null, $territory->getCongregation()->getDefaultLocale())); $territory->setNotified($territory->getStatus()); $this->entityManager->persist($territory); $this->entityManager->flush(); } } }
/** * @return array */ protected function getRows() { $rows = array(); $columns = $this->columns(); $accessor = PropertyAccess::createPropertyAccessor(); $rowProcessor = $this->getRowProcessor(); foreach ($this->data as $data) { $cells = []; foreach ($columns->getColumns() as $col) { try { $val = null; switch (strtolower($col['type'])) { case 'template': break; case 'action': $actions = array(); if ($columns->getActionColumn()) { foreach ($columns->getActionColumn()['options']['actions'] as $action) { if (is_callable($action['route_params'])) { $action['route_params'] = call_user_func($action['route_params'], $data); } $actions[$action['group']][] = $action; } } $col['options']['actions'] = $actions; break; case 'text': case 'datetime': $val = $accessor->getValue($data, $col['options']['property']); if ($col['type'] === 'text') { if ($this->translator && $col['options']['translate'] !== false) { $val = $this->translator->trans($val, $col['options']['translation_params'], $col['options']['translation_domain']); } } else { if ($col['type'] === 'datetime') { if ($val instanceof \DateTime && isset($col['options']['format'])) { $val = date_format($val, $col['options']['format']); } } } break; } $cells[] = array_merge($col, ['value' => $val]); } catch (UnexpectedTypeException $e) { $cells[] = array_merge($col, ['value' => null]); } } $row = array('data' => $data, 'columns' => $this->columns, 'cells' => $cells, 'attributes' => [], 'template' => $this->rowTemplate); if ($rowProcessor) { $row = $rowProcessor($row, $this); } $rows[] = $row; } return $rows; }
/** * Converts dates into relative textual dates * * Ex: x days ago, yesterday, tomorrow, in x days * * @param \DateTime $date * * @throws \InvalidArgumentException * @return string */ public function textualDateFilter($date) { if (!$date instanceof \DateTime) { throw new \InvalidArgumentException('Textual Date Filter expects input to be a instance of DateTime'); } $now = new \DateTime('now'); $diff = $now->diff($date); $diffUnit = $this->getHighestDiffUnitAndValue($diff); $temporalModifier = $diff->invert ? 'ago' : 'next'; $translationString = $temporalModifier . '.' . $diffUnit['unit']; // Override yesterday and tomorrow if ($diffUnit['unit'] == 'd' && $diffUnit['value'] == 1) { $translationString = $diff->invert ? 'date.yesterday' : 'date.tomorrow'; } // Override "just.now" if ($diffUnit['unit'] == 'now') { $translationString = 'date.just_now'; } return $this->translator->transChoice($translationString, $diffUnit['value'], array('%value%' => $diffUnit['value']), 'date'); }
/** * @return array */ public function getField() { $container = isset($this->options['container']) ? $this->options['container'] : null; $ids = array(); $height = array(); $width = array(); $helpMessage = array(); foreach ($this->field->getDimensions() as $dimension) { $height[] = (int) $dimension->getMinHeight(); $height[] = (int) $dimension->getFixedHeight(); $width[] = (int) $dimension->getMinWidth(); $width[] = (int) $dimension->getFixedWidth(); $ids[] = $dimension->getId(); } $helpMessage[] = $this->field->getDescription(); if (count($height) > 0) { $helpMessage[] = $this->translator->trans('bigfish.media.help.sizes', array('%height%' => max($height), '%width%' => max($width))); } return array('identifier' => $this->field->getIdentifier(), 'formType' => $this->field->getFormType(), 'formAttributes' => array('container' => $container, 'field' => $this->field, 'label' => $this->field->getName(), 'attr' => array('data-dimensions' => implode(',', $ids), 'class' => 'uploadValue', 'help_text' => ltrim(implode('<BR>', $helpMessage), '<BR>')))); }
/** * @param Config $config */ private function setConfig(Config $config) { $this->config = $config; $this->logger->info(sprintf("Loading catalogues from \"%s\"", $config->getTranslationsDir())); $this->existingCatalogue = new MessageCatalogue(); // load external resources, so current translations can be reused in the final translation foreach ($config->getLoadResources() as $resource) { $this->existingCatalogue->merge($this->loader->loadFromDirectory($resource, $config->getLocale())); } $this->existingCatalogue->merge($this->loader->loadFromDirectory($config->getTranslationsDir(), $config->getLocale())); $this->extractor->reset(); $this->extractor->setDirectories($config->getScanDirs()); $this->extractor->setExcludedDirs($config->getExcludedDirs()); $this->extractor->setExcludedNames($config->getExcludedNames()); $this->extractor->setEnabledExtractors($config->getEnabledExtractors()); $this->logger->info("Extracting translation keys"); $this->scannedCatalogue = $this->extractor->extract(); $this->scannedCatalogue->setLocale($config->getLocale()); // merge existing messages into scanned messages foreach ($this->scannedCatalogue->getDomains() as $domainCatalogue) { foreach ($domainCatalogue->all() as $message) { if (!$this->existingCatalogue->has($message)) { continue; } $existingMessage = clone $this->existingCatalogue->get($message->getId(), $message->getDomain()); $existingMessage->mergeScanned($message); $this->scannedCatalogue->set($existingMessage, true); } } if ($this->config->isKeepOldMessages()) { foreach ($this->existingCatalogue->getDomains() as $domainCatalogue) { foreach ($domainCatalogue->all() as $message) { if ($this->scannedCatalogue->has($message)) { continue; } $this->scannedCatalogue->add($message); } } } //keep old translations translated if ($this->config->isKeepOldTranslationMessages()) { $locale = $this->scannedCatalogue->getLocale(); /** @var MessageCatalogue $domainCatalogue */ foreach ($this->scannedCatalogue->getDomains() as $domainCatalogue) { /** @var Message $message */ foreach ($domainCatalogue->all() as $message) { $translated = $this->translator->trans($message->getId(), array(), $message->getDomain(), $locale); $message->setLocaleString($translated); $message->setNew(false); } } } }
/** * @param array $config * @return string */ public function button($config) { $path = $this->router->generate($config['route'], $config['route_params']); $class = $config['class']; $icon = $config['icon'] ? "<i class=\"fa fa-{$config['icon']} fa-fw\"></i> " : ''; $label = $icon . $this->translator->trans($config['label']); $attributes = implode(' ', array_map(function ($key, $val) { return sprintf('%s="%s"', $key, $val); }, array_keys($config['attributes']), $config['attributes'])); return <<<HTML <a href="{$path}" class="btn btn-sm btn-{$class}" {$attributes}>{$label}</a> HTML; }
/** * Retrieve entity based on id/alias slugs * * @param string $slug * * @return object|bool */ public function getEntityBySlugs($slug) { $slugs = explode('/', $slug); $idSlug = ''; $category = null; $lang = null; $slugCount = count($slugs); $locales = Intl::getLocaleBundle()->getLocaleNames(); switch (true) { case $slugCount === 3: list($lang, $category, $idSlug) = $slugs; break; case $slugCount === 2: list($category, $idSlug) = $slugs; // Check if the first slug is actually a locale if (isset($locales[$category])) { $lang = $category; $category = null; } break; case $slugCount === 1: $idSlug = $slugs[0]; break; } // Check for uncategorized if ($this->translator->trans('mautic.core.url.uncategorized') == $category) { $category = null; } if (null === $lang) { // Default to en $lang = 'en'; } elseif (!isset($locales[$lang])) { // Language doesn't exist so return false return false; } if (strpos($idSlug, ':') !== false) { $parts = explode(':', $idSlug); if (count($parts) == 2) { $entity = $this->getEntity($parts[0]); if (!empty($entity)) { return $entity; } } } else { $entity = $this->getRepository()->findOneBySlugs($idSlug, $category, $lang); if (!empty($entity)) { return $entity; } } return false; }