/** * {@inheritdoc} */ public function getAllBundleInfo() { if (empty($this->bundleInfo)) { $langcode = $this->languageManager->getCurrentLanguage()->getId(); if ($cache = $this->cacheGet("entity_bundle_info:{$langcode}")) { $this->bundleInfo = $cache->data; } else { $this->bundleInfo = $this->moduleHandler->invokeAll('entity_bundle_info'); foreach ($this->entityTypeManager->getDefinitions() as $type => $entity_type) { // First look for entity types that act as bundles for others, load them // and add them as bundles. if ($bundle_entity_type = $entity_type->getBundleEntityType()) { foreach ($this->entityTypeManager->getStorage($bundle_entity_type)->loadMultiple() as $entity) { $this->bundleInfo[$type][$entity->id()]['label'] = $entity->label(); } } elseif (!isset($this->bundleInfo[$type])) { $this->bundleInfo[$type][$type]['label'] = $entity_type->getLabel(); } } $this->moduleHandler->alter('entity_bundle_info', $this->bundleInfo); $this->cacheSet("entity_bundle_info:{$langcode}", $this->bundleInfo, Cache::PERMANENT, ['entity_types', 'entity_bundles']); } } return $this->bundleInfo; }
/** * Causes the container to be rebuilt on the next request. * * This event subscriber assumes that the new default langcode and old default * langcode are valid langcodes. If the schema definition of either * system.site:default_langcode or language.negotiation::url.prefixes changes * then this event must be changed to work with both the old and new schema * definition so this event is update safe. * * @param ConfigCrudEvent $event * The configuration event. */ public function onConfigSave(ConfigCrudEvent $event) { $saved_config = $event->getConfig(); if ($saved_config->getName() == 'system.site' && $event->isChanged('default_langcode')) { $new_default_langcode = $saved_config->get('default_langcode'); $default_language = $this->configFactory->get('language.entity.' . $new_default_langcode); // During an import the language might not exist yet. if (!$default_language->isNew()) { $this->languageDefault->set(new Language($default_language->get())); $this->languageManager->reset(); // Directly update language negotiation settings instead of calling // language_negotiation_url_prefixes_update() to ensure that the code // obeys the hook_update_N() restrictions. $negotiation_config = $this->configFactory->getEditable('language.negotiation'); $negotiation_changed = FALSE; $url_prefixes = $negotiation_config->get('url.prefixes'); $old_default_langcode = $saved_config->getOriginal('default_langcode'); if (empty($url_prefixes[$old_default_langcode])) { $negotiation_config->set('url.prefixes.' . $old_default_langcode, $old_default_langcode); $negotiation_changed = TRUE; } if (empty($url_prefixes[$new_default_langcode])) { $negotiation_config->set('url.prefixes.' . $new_default_langcode, ''); $negotiation_changed = TRUE; } if ($negotiation_changed) { $negotiation_config->save(TRUE); } } // Trigger a container rebuild on the next request by invalidating it. ConfigurableLanguageManager::rebuildServices(); } }
/** * {@inheritdoc} */ public function getRuntimeContexts(array $unqualified_context_ids) { // Add a context for each language type. $language_types = $this->languageManager->getLanguageTypes(); $info = $this->languageManager->getDefinedLanguageTypesInfo(); if ($unqualified_context_ids) { foreach ($unqualified_context_ids as $unqualified_context_id) { if (array_search($unqualified_context_id, $language_types) === FALSE) { unset($language_types[$unqualified_context_id]); } } } $result = []; foreach ($language_types as $type_key) { if (isset($info[$type_key]['name'])) { $context = new Context(new ContextDefinition('language', $info[$type_key]['name'])); $context->setContextValue($this->languageManager->getCurrentLanguage($type_key)); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['languages:' . $type_key]); $context->addCacheableDependency($cacheability); $result[$type_key] = $context; } } return $result; }
/** * {@inheritdoc} */ public function getTranslationFromContext(EntityInterface $entity, $langcode = NULL, $context = array()) { $translation = $entity; if ($entity instanceof TranslatableInterface && count($entity->getTranslationLanguages()) > 1) { if (empty($langcode)) { $langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId(); $entity->addCacheContexts(['languages:' . LanguageInterface::TYPE_CONTENT]); } // Retrieve language fallback candidates to perform the entity language // negotiation, unless the current translation is already the desired one. if ($entity->language()->getId() != $langcode) { $context['data'] = $entity; $context += array('operation' => 'entity_view', 'langcode' => $langcode); $candidates = $this->languageManager->getFallbackCandidates($context); // Ensure the default language has the proper language code. $default_language = $entity->getUntranslated()->language(); $candidates[$default_language->getId()] = LanguageInterface::LANGCODE_DEFAULT; // Return the most fitting entity translation. foreach ($candidates as $candidate) { if ($entity->hasTranslation($candidate)) { $translation = $entity->getTranslation($candidate); break; } } } } return $translation; }
/** * Returns an array of route objects. * * @return \Symfony\Component\Routing\Route[] * An array of route objects. */ public function routes() { $routes = array(); $is_multilingual = $this->languageManager->isMultilingual(); /* @var $search_api_page \Drupal\search_api_page\SearchApiPageInterface */ foreach ($this->entityManager->getStorage('search_api_page')->loadMultiple() as $search_api_page) { // Default path. $default_path = $search_api_page->getPath(); // Loop over all languages so we can get the translated path (if any). foreach ($this->languageManager->getLanguages() as $language) { // Check if we are multilingual or not. if ($is_multilingual) { $path = $this->languageManager->getLanguageConfigOverride($language->getId(), 'search_api_page.search_api_page.' . $search_api_page->id())->get('path'); } if (empty($path)) { $path = $default_path; } $args = ['_controller' => 'Drupal\\search_api_page\\Controller\\SearchApiPageController::page', 'search_api_page_name' => $search_api_page->id()]; // Use clean urls or not. if ($search_api_page->getCleanUrl()) { $path .= '/{keys}'; $args['keys'] = ''; } $routes['search_api_page.' . $language->getId() . '.' . $search_api_page->id()] = new Route($path, $args, array('_permission' => 'view search api pages')); } } return $routes; }
/** * Checks translation access for the entity and operation on the given route. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The parametrized route. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * @param string $source * (optional) For a create operation, the language code of the source. * @param string $target * (optional) For a create operation, the language code of the translation. * @param string $language * (optional) For an update or delete operation, the language code of the * translation being updated or deleted. * @param string $entity_type_id * (optional) The entity type ID. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) { /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */ if ($entity = $route_match->getParameter($entity_type_id)) { if ($account->hasPermission('translate any entity')) { return AccessResult::allowed()->cachePerRole(); } $operation = $route->getRequirement('_access_content_translation_manage'); /* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */ $handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation'); // Load translation. $translations = $entity->getTranslationLanguages(); $languages = $this->languageManager->getLanguages(); switch ($operation) { case 'create': $source_language = $this->languageManager->getLanguage($source) ?: $entity->language(); $target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]); return AccessResult::allowedIf($is_new_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); case 'update': case 'delete': $language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT); $has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]); return AccessResult::allowedIf($has_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation)); } } // No opinion. return AccessResult::neutral(); }
/** * {@inheritdoc} */ public function convert($value, $definition, $name, array $defaults) { if (!empty($value)) { return $this->languageManager->getLanguage($value); } return NULL; }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->aliasProcessor = $this->getMockBuilder('Drupal\Core\PathProcessor\PathProcessorAlias') ->disableOriginalConstructor() ->getMock(); $this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface'); $this->languageManager->expects($this->any()) ->method('getCurrentLanguage') ->willReturn(new Language(Language::$defaultValues)); $this->pathValidator = $this->getMock('Drupal\Core\Path\PathValidatorInterface'); $this->subPathautoSettings = $this->getMock('Drupal\Core\Config\ConfigBase'); $this->configFactory = $this->getMock('Drupal\Core\Config\ConfigFactoryInterface'); $this->configFactory->expects($this->any()) ->method('get') ->with('subpathauto.settings') ->willReturn($this->subPathautoSettings); $this->sut = new PathProcessor($this->aliasProcessor, $this->languageManager, $this->configFactory); $this->sut->setPathValidator($this->pathValidator); }
/** * {@inheritdoc} */ public function resolveCurrencyLocale($language_type = LanguageInterface::TYPE_CONTENT) { if (empty($this->currencyLocales[$language_type])) { $currency_locale = NULL; $language_code = $this->languageManager->getCurrentLanguage($language_type)->getId(); // Try this request's country code. $country_code = $this->eventDispatcher->resolveCountryCode(); if ($country_code) { $currency_locale = $this->currencyLocaleStorage->load($language_code . '_' . $country_code); } // Try the site's default country code. if (!$currency_locale) { $country_code = $this->configFactory->get('system.data')->get('country.default'); if ($country_code) { $currency_locale = $this->currencyLocaleStorage->load($language_code . '_' . $country_code); } } // Try the Currency default. if (!$currency_locale) { $currency_locale = $this->currencyLocaleStorage->load($this::DEFAULT_LOCALE); } if ($currency_locale) { $this->currencyLocales[$language_type] = $currency_locale; } else { throw new \RuntimeException(sprintf('The currency locale for %s could not be loaded.', $this::DEFAULT_LOCALE)); } } return $this->currencyLocales[$language_type]; }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installConfig(array('language')); $this->state = $this->container->get('state'); // Ensure we are building a new Language object for each test. $this->languageManager = $this->container->get('language_manager'); $this->languageManager->reset(); }
/** * {@inheritdoc} */ public function query() { // Don't filter by language in case the site is not multilingual, because // there is no point in doing so. if (!$this->languageManager->isMultilingual()) { return; } parent::query(); }
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { $languages = $this->languageManager->getLanguages(); // Count repeated values for uniqueness check. $count = array_count_values($form_state->getValue('prefix')); $default_langcode = $this->config('language.negotiation')->get('selected_langcode'); if ($default_langcode == LanguageInterface::LANGCODE_SITE_DEFAULT) { $default_langcode = $this->languageManager->getDefaultLanguage()->getId(); } foreach ($languages as $langcode => $language) { $value = $form_state->getValue(array('prefix', $langcode)); if ($value === '') { if (!($default_langcode == $langcode) && $form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) { // Throw a form error if the prefix is blank for a non-default language, // although it is required for selected negotiation type. $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix may only be left blank for the <a href=":url">selected detection fallback language.</a>', [':url' => $this->getUrlGenerator()->generate('language.negotiation_selected')])); } } elseif (strpos($value, '/') !== FALSE) { // Throw a form error if the string contains a slash, // which would not work. $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix may not contain a slash.')); } elseif (isset($count[$value]) && $count[$value] > 1) { // Throw a form error if there are two languages with the same // domain/prefix. $form_state->setErrorByName("prefix][{$langcode}", $this->t('The prefix for %language, %value, is not unique.', array('%language' => $language->getName(), '%value' => $value))); } } // Count repeated values for uniqueness check. $count = array_count_values($form_state->getValue('domain')); foreach ($languages as $langcode => $language) { $value = $form_state->getValue(array('domain', $langcode)); if ($value === '') { if ($form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_DOMAIN) { // Throw a form error if the domain is blank for a non-default language, // although it is required for selected negotiation type. $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain may not be left blank for %language.', array('%language' => $language->getName()))); } } elseif (isset($count[$value]) && $count[$value] > 1) { // Throw a form error if there are two languages with the same // domain/domain. $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain for %language, %value, is not unique.', array('%language' => $language->getName(), '%value' => $value))); } } // Domain names should not contain protocol and/or ports. foreach ($languages as $langcode => $language) { $value = $form_state->getValue(array('domain', $langcode)); if (!empty($value)) { // Ensure we have exactly one protocol when checking the hostname. $host = 'http://' . str_replace(array('http://', 'https://'), '', $value); if (parse_url($host, PHP_URL_HOST) != $value) { $form_state->setErrorByName("domain][{$langcode}", $this->t('The domain for %language may only contain the domain name, not a trailing slash, protocol and/or port.', ['%language' => $language->getName()])); } } } parent::validateForm($form, $form_state); }
/** * {@inheritdoc} */ public function sendMailMessages(MessageInterface $message, AccountInterface $sender) { // Clone the sender, as we make changes to mail and name properties. $sender_cloned = clone $this->userStorage->load($sender->id()); $params = array(); $current_langcode = $this->languageManager->getCurrentLanguage()->getId(); $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId(); $contact_form = $message->getContactForm(); if ($sender_cloned->isAnonymous()) { // At this point, $sender contains an anonymous user, so we need to take // over the submitted form values. $sender_cloned->name = $message->getSenderName(); $sender_cloned->mail = $message->getSenderMail(); // For the email message, clarify that the sender name is not verified; it // could potentially clash with a username on this site. $sender_cloned->name = $this->t('@name (not verified)', array('@name' => $message->getSenderName())); } // Build email parameters. $params['contact_message'] = $message; $params['sender'] = $sender_cloned; if (!$message->isPersonal()) { // Send to the form recipient(s), using the site's default language. $params['contact_form'] = $contact_form; $to = implode(', ', $contact_form->getRecipients()); } elseif ($recipient = $message->getPersonalRecipient()) { // Send to the user in the user's preferred language. $to = $recipient->getEmail(); $recipient_langcode = $recipient->getPreferredLangcode(); $params['recipient'] = $recipient; } else { throw new MailHandlerException('Unable to determine message recipient'); } // Send email to the recipient(s). $key_prefix = $message->isPersonal() ? 'user' : 'page'; $this->mailManager->mail('contact', $key_prefix . '_mail', $to, $recipient_langcode, $params, $sender_cloned->getEmail()); // If requested, send a copy to the user, using the current language. if ($message->copySender()) { $this->mailManager->mail('contact', $key_prefix . '_copy', $sender_cloned->getEmail(), $current_langcode, $params, $sender_cloned->getEmail()); } // If configured, send an auto-reply, using the current language. if (!$message->isPersonal() && $contact_form->getReply()) { // User contact forms do not support an auto-reply message, so this // message always originates from the site. if (!$sender_cloned->getEmail()) { $this->logger->error('Error sending auto-reply, missing sender e-mail address in %contact_form', ['%contact_form' => $contact_form->label()]); } else { $this->mailManager->mail('contact', 'page_autoreply', $sender_cloned->getEmail(), $current_langcode, $params); } } if (!$message->isPersonal()) { $this->logger->notice('%sender-name (@sender-from) sent an email regarding %contact_form.', array('%sender-name' => $sender_cloned->getUsername(), '@sender-from' => $sender_cloned->getEmail(), '%contact_form' => $contact_form->label())); } else { $this->logger->notice('%sender-name (@sender-from) sent %recipient-name an email.', array('%sender-name' => $sender_cloned->getUsername(), '@sender-from' => $sender_cloned->getEmail(), '%recipient-name' => $message->getPersonalRecipient()->getUsername())); } }
/** * {@inheritdoc} */ public function build() { $build = array(); $path = drupal_is_front_page() ? '<front>' : current_path(); $type = $this->getDerivativeId(); $links = $this->languageManager->getLanguageSwitchLinks($type, $path); if (isset($links->links)) { $build = array('#theme' => 'links__language_block', '#links' => $links->links, '#attributes' => array('class' => array("language-switcher-{$links->method_id}")), '#set_active_class' => TRUE); } return $build; }
/** * {@inheritdoc} */ public function build() { $build = array(); $route_name = $this->pathMatcher->isFrontPage() ? '<front>' : '<current>'; $type = $this->getDerivativeId(); $links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name)); if (isset($links->links)) { $build = array('#theme' => 'links__language_block', '#links' => $links->links, '#attributes' => array('class' => array("language-switcher-{$links->method_id}")), '#set_active_class' => TRUE); } return $build; }
/** * {@inheritdoc} */ protected function setUp() { $this->cacheBackend = $this->getMock('Drupal\\Core\\Cache\\CacheBackendInterface'); $this->getContainerWithCacheBins($this->cacheBackend); $configs = array(); $configs['views.settings']['skip_cache'] = FALSE; $this->configFactory = $this->getConfigFactoryStub($configs); $this->moduleHandler = $this->getMock('Drupal\\Core\\Extension\\ModuleHandlerInterface'); $this->languageManager = $this->getMock('Drupal\\Core\\Language\\LanguageManagerInterface'); $this->languageManager->expects($this->any())->method('getCurrentLanguage')->will($this->returnValue(new Language(array('id' => 'en')))); $this->viewsData = new ViewsData($this->cacheBackend, $this->configFactory, $this->moduleHandler, $this->languageManager); }
/** * Constructs a ConfigMapperManager. * * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend * The cache backend. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager * The language manager. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. * @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager * The typed config manager. * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler * The theme handler. */ public function __construct(CacheBackendInterface $cache_backend, LanguageManagerInterface $language_manager, ModuleHandlerInterface $module_handler, TypedConfigManagerInterface $typed_config_manager, ThemeHandlerInterface $theme_handler) { $this->typedConfigManager = $typed_config_manager; $this->factory = new ContainerFactory($this, '\\Drupal\\config_translation\\ConfigMapperInterface'); // Let others alter definitions with hook_config_translation_info_alter(). $this->moduleHandler = $module_handler; $this->themeHandler = $theme_handler; $this->alterInfo('config_translation_info'); // Config translation only uses an info hook discovery, cache by language. $cache_key = 'config_translation_info_plugins' . ':' . $language_manager->getCurrentLanguage()->getId(); $this->setCacheBackend($cache_backend, $cache_key, array('config_translation_info_plugins')); }
/** * {@inheritdoc} */ public function getAll($locale = NULL) { if ($locale) { $original_language = $this->languageManager->getConfigOverrideLanguage(); $this->languageManager->setConfigOverrideLanguage(new Language(['id' => $locale])); $address_formats = $this->formatStorage->loadMultiple(); $this->languageManager->setConfigOverrideLanguage($original_language); } else { $address_formats = $this->formatStorage->loadMultiple(); } return $address_formats; }
/** * Checks access to the overview based on permissions and translatability. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * @param \Drupal\Core\Session\AccountInterface $account * The currently logged in account. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(Route $route, AccountInterface $account) { /** @var \Drupal\config_translation\ConfigMapperInterface $mapper */ $mapper = $this->configMapperManager->createInstance($route->getDefault('plugin_id')); $this->sourceLanguage = $this->languageManager->getLanguage($mapper->getLangcode()); // Allow access to the translation overview if the proper permission is // granted, the configuration has translatable pieces, and the source // language is not locked if it is present. $source_language_access = is_null($this->sourceLanguage) || !$this->sourceLanguage->isLocked(); $access = $account->hasPermission('translate configuration') && $mapper->hasSchema() && $mapper->hasTranslatable() && $source_language_access; return AccessResult::allowedIf($access)->cachePerRole(); }
/** * {@inheritdoc} */ public function getNumberOfPlurals($langcode = NULL) { // Ensure that the formulae are loaded. $this->loadFormulae(); // Set the langcode to use. $langcode = $langcode ?: $this->languageManager->getCurrentLanguage()->getId(); // We assume 2 plurals if there is no explicit information yet. if (!isset($this->formulae[$langcode]['plurals'])) { return 2; } return $this->formulae[$langcode]['plurals']; }
/** * Checks access to the overview based on permissions and translatability. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route_match to check against. * @param \Drupal\Core\Session\AccountInterface $account * The account to check access for. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */ public function access(RouteMatchInterface $route_match, AccountInterface $account) { $mapper = $this->getMapperFromRouteMatch($route_match); try { $langcode = $mapper->getLangcode(); } catch (ConfigMapperLanguageException $exception) { // ConfigTranslationController shows a helpful message if the language // codes do not match, so do not let that prevent granting access. $langcode = 'en'; } $source_language = $this->languageManager->getLanguage($langcode); return $this->doCheckAccess($account, $mapper, $source_language); }
/** * {@inheritdoc} */ public function import(Row $row, array $old_destination_id_values = array()) { if ($row->hasDestinationProperty('langcode')) { $this->config = $this->language_manager->getLanguageConfigOverride($row->getDestinationProperty('langcode'), $this->config->getName()); } foreach ($row->getRawDestination() as $key => $value) { if (isset($value) || !empty($this->configuration['store null'])) { $this->config->set(str_replace(Row::PROPERTY_SEPARATOR, '.', $key), $value); } } $this->config->save(); return [$this->config->getName()]; }
/** * {@inheritdoc} */ public function setup() { $this->defaultDateTime = $this->getMockBuilder(DrupalDateTime::class)->disableOriginalConstructor()->getMock(); $language = $this->getMock(LanguageInterface::class); $this->languageManager = $this->getMock(LanguageManagerInterface::class); $this->languageManager->expects($this->any())->method('getCurrentLanguage')->willReturn($language); $this->moduleHandler = $this->getMock(ModuleHandlerInterface::class); $this->paymentStatusManager = $this->getMock(PaymentStatusManagerInterface::class); $configuration = []; $this->pluginId = $this->randomMachineName(); $this->pluginDefinition = array('label' => $this->randomMachineName()); $this->sut = $this->getMockBuilder(PaymentStatusBase::class)->setConstructorArgs(array($configuration, $this->pluginId, $this->pluginDefinition, $this->moduleHandler, $this->paymentStatusManager, $this->defaultDateTime))->getMockForAbstractClass(); }
/** * {@inheritdoc} */ public function onBlockActiveContext(BlockContextEvent $event) { // Add a context for each language type. $language_types = $this->languageManager->getLanguageTypes(); $info = $this->languageManager->getDefinedLanguageTypesInfo(); foreach ($language_types as $type_key) { if (isset($info[$type_key]['name'])) { $context = new Context(new ContextDefinition('language', $info[$type_key]['name'])); $context->setContextValue($this->languageManager->getCurrentLanguage($type_key)); $event->setContext('language.' . $type_key, $context); } } }
/** * Sets the 'is-active' class on links. * * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event * The response event. */ public function onResponse(FilterResponseEvent $event) { // Only care about HTML responses. if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) { return; } // For authenticated users, the 'is-active' class is set in JavaScript. // @see system_page_attachments() if ($this->currentUser->isAuthenticated()) { return; } $response = $event->getResponse(); $response->setContent(static::setLinkActiveClass($response->getContent(), ltrim($this->currentPath->getPath(), '/'), $this->pathMatcher->isFrontPage(), $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(), $event->getRequest()->query->all())); }
/** * {@inheritdoc} */ public function importTranslations(array $langcodes) { $available_translations = $this->getAvailableTranslations(); $available_translations = array_intersect_key($available_translations, array_flip($langcodes)); foreach ($available_translations as $langcode => $country_codes) { $address_formats = $this->storage->loadMultiple($country_codes); foreach ($address_formats as $country_code => $address_format) { $external_translation = $this->externalRepository->get($country_code, $langcode); $config_name = $address_format->getConfigDependencyName(); $config_translation = $this->languageManager->getLanguageConfigOverride($langcode, $config_name); $config_translation->set('format', $external_translation->getFormat()); $config_translation->save(); } } }
/** * Causes the container to be rebuilt on the next request. * * @param ConfigCrudEvent $event * The configuration event. */ public function onConfigSave(ConfigCrudEvent $event) { $saved_config = $event->getConfig(); if ($saved_config->getName() == 'system.site' && $event->isChanged('default_langcode')) { $language = $this->languageManager->getLanguage($saved_config->get('default_langcode')); // During an import the language might not exist yet. if ($language) { $this->languageDefault->set($language); $this->languageManager->reset(); language_negotiation_url_prefixes_update(); } // Trigger a container rebuild on the next request by invalidating it. ConfigurableLanguageManager::rebuildServices(); } }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->mailManager = $this->getMock('\\Drupal\\Core\\Mail\\MailManagerInterface'); $this->languageManager = $this->getMock('\\Drupal\\Core\\Language\\LanguageManagerInterface'); $this->logger = $this->getMock('\\Psr\\Log\\LoggerInterface'); $this->entityManager = $this->getMock('\\Drupal\\Core\\Entity\\EntityManagerInterface'); $this->userStorage = $this->getMock('\\Drupal\\Core\\Entity\\EntityStorageInterface'); $this->entityManager->expects($this->any())->method('getStorage')->with('user')->willReturn($this->userStorage); $string_translation = $this->getStringTranslationStub(); $this->contactMailHandler = new MailHandler($this->mailManager, $this->languageManager, $this->logger, $string_translation, $this->entityManager); $language = new Language(array('id' => 'en')); $this->languageManager->expects($this->any())->method('getDefaultLanguage')->will($this->returnValue($language)); $this->languageManager->expects($this->any())->method('getCurrentLanguage')->will($this->returnValue($language)); }
/** * {@inheritdoc} */ protected function resolveCacheMiss($offset) { $translation = $this->stringStorage->findTranslation(array('language' => $this->langcode, 'source' => $offset, 'context' => $this->context)); if ($translation) { $value = !empty($translation->translation) ? $translation->translation : TRUE; } else { // We don't have the source string, update the {locales_source} table to // indicate the string is not translated. $this->stringStorage->createString(array('source' => $offset, 'context' => $this->context, 'version' => \Drupal::VERSION))->addLocation('path', $this->requestUri())->save(); $value = TRUE; } // If there is no translation available for the current language then use // language fallback to try other translations. if ($value === TRUE) { $fallbacks = $this->languageManager->getFallbackCandidates($this->langcode, array('operation' => 'locale_lookup', 'data' => $offset)); if (!empty($fallbacks)) { foreach ($fallbacks as $langcode) { $translation = $this->stringStorage->findTranslation(array('language' => $langcode, 'source' => $offset, 'context' => $this->context)); if ($translation && !empty($translation->translation)) { $value = $translation->translation; break; } } } } $this->storage[$offset] = $value; // Disabling the usage of string caching allows a module to watch for // the exact list of strings used on a page. From a performance // perspective that is a really bad idea, so we have no user // interface for this. Be careful when turning this option off! if ($this->configFactory->get('locale.settings')->get('cache_strings')) { $this->persist($offset); } return $value; }
/** * {@inheritdoc} * * @covers ::__construct() */ protected function setUp() { parent::setUp(); $this->entityType = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface'); $this->entityTypeId = 'test_entity_type'; $this->entityType->expects($this->any())->method('getKey')->will($this->returnValueMap(array(array('id', 'id'), array('uuid', 'uuid')))); $this->entityType->expects($this->any())->method('id')->will($this->returnValue($this->entityTypeId)); $this->entityType->expects($this->any())->method('getConfigPrefix')->will($this->returnValue('the_config_prefix')); $this->entityType->expects($this->any())->method('getClass')->will($this->returnValue(get_class($this->getMockEntity()))); $this->entityType->expects($this->any())->method('getListCacheTags')->willReturn(array('test_entity_type_list')); $this->moduleHandler = $this->getMock('Drupal\\Core\\Extension\\ModuleHandlerInterface'); $this->uuidService = $this->getMock('Drupal\\Component\\Uuid\\UuidInterface'); $this->languageManager = $this->getMock('Drupal\\Core\\Language\\LanguageManagerInterface'); $this->languageManager->expects($this->any())->method('getDefaultLanguage')->will($this->returnValue(new Language(array('langcode' => 'en')))); $this->configFactory = $this->getMock('Drupal\\Core\\Config\\ConfigFactoryInterface'); $this->entityQuery = $this->getMock('Drupal\\Core\\Entity\\Query\\QueryInterface'); $this->entityStorage = $this->getMockBuilder('Drupal\\Core\\Config\\Entity\\ConfigEntityStorage')->setConstructorArgs(array($this->entityType, $this->configFactory, $this->uuidService, $this->languageManager))->setMethods(array('getQuery'))->getMock(); $this->entityStorage->expects($this->any())->method('getQuery')->will($this->returnValue($this->entityQuery)); $this->entityStorage->setModuleHandler($this->moduleHandler); $this->entityManager = $this->getMock('\\Drupal\\Core\\Entity\\EntityManagerInterface'); $this->entityManager->expects($this->any())->method('getDefinition')->with('test_entity_type')->will($this->returnValue($this->entityType)); $this->cacheBackend = $this->getMock('Drupal\\Core\\Cache\\CacheBackendInterface'); $this->typedConfigManager = $this->getMock('Drupal\\Core\\Config\\TypedConfigManagerInterface'); $this->typedConfigManager->expects($this->any())->method('getDefinition')->will($this->returnValue(array('mapping' => array('id' => '', 'uuid' => '', 'dependencies' => '')))); $container = new ContainerBuilder(); $container->set('entity.manager', $this->entityManager); $container->set('config.typed', $this->typedConfigManager); $container->set('cache.test', $this->cacheBackend); $container->setParameter('cache_bins', array('cache.test' => 'test')); \Drupal::setContainer($container); }