本文整理汇总了PHP中Drupal\Core\Language\LanguageManagerInterface类的典型用法代码示例。如果您正苦于以下问题:PHP LanguageManagerInterface类的具体用法?PHP LanguageManagerInterface怎么用?PHP LanguageManagerInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LanguageManagerInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: setUp
/**
* {@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);
}
示例2: setUp
/**
* {@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);
}
示例3: __construct
/**
* 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'));
}
示例4: getAllBundleInfo
/**
* {@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;
}
示例5: onConfigSave
/**
* 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();
}
}
示例6: getRuntimeContexts
/**
* {@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;
}
示例7: getTranslationFromContext
/**
* {@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;
}
示例8: routes
/**
* 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;
}
示例9: access
/**
* 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();
}
示例10: convert
/**
* {@inheritdoc}
*/
public function convert($value, $definition, $name, array $defaults)
{
if (!empty($value)) {
return $this->languageManager->getLanguage($value);
}
return NULL;
}
示例11: resolveCurrencyLocale
/**
* {@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];
}
示例12: setUp
/**
* {@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();
}
示例13: query
/**
* {@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();
}
示例14: validateForm
/**
* {@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);
}
示例15: sendMailMessages
/**
* {@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()));
}
}