本文整理汇总了PHP中Drupal\Core\Language\LanguageManagerInterface::getCurrentLanguage方法的典型用法代码示例。如果您正苦于以下问题:PHP LanguageManagerInterface::getCurrentLanguage方法的具体用法?PHP LanguageManagerInterface::getCurrentLanguage怎么用?PHP LanguageManagerInterface::getCurrentLanguage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Language\LanguageManagerInterface
的用法示例。
在下文中一共展示了LanguageManagerInterface::getCurrentLanguage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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];
}
示例2: 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;
}
示例3: 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;
}
示例4: 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();
}
示例5: 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;
}
示例6: 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()));
}
}
示例7: getNumberOfPlurals
/**
* {@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'];
}
示例8: onBlockActiveContext
/**
* {@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);
}
}
}
示例9: onResponse
/**
* 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()));
}
示例10: preparePage
/**
* Enhances a page object based on a render array.
*
* @param \Drupal\Core\Page\HtmlPage $page
* The page object to enhance.
* @param array $page_array
* The page array to extract onto the page object.
*
* @return \Drupal\Core\Page\HtmlPage
* The modified page object.
*/
public function preparePage(HtmlPage $page, &$page_array)
{
$page_array['#page'] = $page;
// HTML element attributes.
$language_interface = $this->languageManager->getCurrentLanguage();
$html_attributes = $page->getHtmlAttributes();
$html_attributes['lang'] = $language_interface->getId();
$html_attributes['dir'] = $language_interface->getDirection();
$this->setDefaultMetaTags($page);
// @todo: collect feed links from #attached rather than a static once
// http://drupal.org/node/2256365 is completed.
foreach (drupal_get_feeds() as $feed) {
// Force the URL to be absolute, for consistency with other <link> tags
// output by Drupal.
$link = new FeedLinkElement($feed['title'], _url($feed['url'], array('absolute' => TRUE)));
$page->addLinkElement($link);
}
// Add libraries and CSS used by this theme.
$active_theme = \Drupal::theme()->getActiveTheme();
foreach ($active_theme->getLibraries() as $library) {
$page_array['#attached']['library'][] = $library;
}
foreach ($active_theme->getStyleSheets() as $media => $stylesheets) {
foreach ($stylesheets as $stylesheet) {
$page_array['#attached']['css'][$stylesheet] = array('group' => CSS_AGGREGATE_THEME, 'every_page' => TRUE, 'media' => $media);
}
}
return $page;
}
示例11: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
// This form submits to the search page, so processing happens there.
$keys = $form_state->getValue('keys');
/* @var $searchApiPage \Drupal\search_api_page\SearchApiPageInterface */
$form_state->setRedirectUrl(Url::fromRoute('search_api_page.' . $this->languageManager->getCurrentLanguage()->getId() . '.' . $form_state->getValue('search_api_page'), array('keys' => $keys)));
}
示例12: format
/**
* Formats a date, using a date type or a custom date format string.
*
* @param int $timestamp
* A UNIX timestamp to format.
* @param string $type
* (optional) The format to use, one of:
* - One of the built-in formats: 'short', 'medium',
* 'long', 'html_datetime', 'html_date', 'html_time',
* 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
* - The name of a date type defined by a date format config entity.
* - The machine name of an administrator-defined date format.
* - 'custom', to use $format.
* Defaults to 'medium'.
* @param string $format
* (optional) If $type is 'custom', a PHP date format string suitable for
* input to date(). Use a backslash to escape ordinary text, so it does not
* get interpreted as date format characters.
* @param string|null $timezone
* (optional) Time zone identifier, as described at
* http://php.net/manual/timezones.php Defaults to the time zone used to
* display the page.
* @param string|null $langcode
* (optional) Language code to translate to. NULL (default) means to use
* the user interface language for the page.
*
* @return string
* A translated date string in the requested format. Since the format may
* contain user input, this value should be escaped when output.
*/
public function format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)
{
if (!isset($timezone)) {
$timezone = date_default_timezone_get();
}
// Store DateTimeZone objects in an array rather than repeatedly
// constructing identical objects over the life of a request.
if (!isset($this->timezones[$timezone])) {
$this->timezones[$timezone] = timezone_open($timezone);
}
if (empty($langcode)) {
$langcode = $this->languageManager->getCurrentLanguage()->getId();
}
// Create a DrupalDateTime object from the timestamp and timezone.
$create_settings = array('langcode' => $langcode, 'country' => $this->country());
$date = DrupalDateTime::createFromTimestamp($timestamp, $this->timezones[$timezone], $create_settings);
// If we have a non-custom date format use the provided date format pattern.
if ($date_format = $this->dateFormat($type, $langcode)) {
$format = $date_format->getPattern();
}
// Fall back to medium if a format was not found.
if (empty($format)) {
$format = $this->dateFormat('fallback', $langcode)->getPattern();
}
// Call $date->format().
$settings = array('langcode' => $langcode);
return $date->format($format, $settings);
}
示例13: form
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state)
{
$block = $this->entity;
$account = $this->currentUser();
if ($this->operation == 'edit') {
$form['#title'] = $this->t('Edit custom block %label', array('%label' => $block->label()));
}
// Override the default CSS class name, since the user-defined custom block
// type name in 'TYPE-block-form' potentially clashes with third-party class
// names.
$form['#attributes']['class'][0] = drupal_html_class('block-' . $block->bundle() . '-form');
if ($this->moduleHandler->moduleExists('language')) {
$language_configuration = language_get_default_configuration('block_content', $block->bundle());
// Set the correct default language.
if ($block->isNew()) {
$language_default = $this->languageManager->getCurrentLanguage($language_configuration['langcode']);
$block->langcode->value = $language_default->getId();
}
}
$form['langcode'] = array('#title' => $this->t('Language'), '#type' => 'language_select', '#default_value' => $block->getUntranslated()->language()->getId(), '#languages' => LanguageInterface::STATE_ALL, '#access' => isset($language_configuration['language_show']) && $language_configuration['language_show']);
$form['advanced'] = array('#type' => 'vertical_tabs', '#weight' => 99);
// Add a log field if the "Create new revision" option is checked, or if the
// current user has the ability to check that option.
$form['revision_information'] = array('#type' => 'details', '#title' => $this->t('Revision information'), '#open' => $block->isNewRevision(), '#group' => 'advanced', '#attributes' => array('class' => array('block-content-form-revision-information')), '#attached' => array('library' => array('block_content/drupal.block_content')), '#weight' => 20, '#access' => $block->isNewRevision() || $account->hasPermission('administer blocks'));
$form['revision_information']['revision'] = array('#type' => 'checkbox', '#title' => $this->t('Create new revision'), '#default_value' => $block->isNewRevision(), '#access' => $account->hasPermission('administer blocks'));
// Check the revision log checkbox when the log textarea is filled in.
// This must not happen if "Create new revision" is enabled by default,
// since the state would auto-disable the checkbox otherwise.
if (!$block->isNewRevision()) {
$form['revision_information']['revision']['#states'] = array('checked' => array('textarea[name="revision_log"]' => array('empty' => FALSE)));
}
$form['revision_information']['revision_log'] = array('#type' => 'textarea', '#title' => $this->t('Revision log message'), '#rows' => 4, '#default_value' => $block->getRevisionLog(), '#description' => $this->t('Briefly describe the changes you have made.'));
return parent::form($form, $form_state, $block);
}
示例14: getJSSettings
/**
* {@inheritdoc}
*/
public function getJSSettings(EditorEntity $editor)
{
$settings = array();
// Get the settings for all enabled plugins, even the internal ones.
$enabled_plugins = array_keys($this->ckeditorPluginManager->getEnabledPluginFiles($editor, TRUE));
foreach ($enabled_plugins as $plugin_id) {
$plugin = $this->ckeditorPluginManager->createInstance($plugin_id);
$settings += $plugin->getConfig($editor);
}
// Fall back on English if no matching language code was found.
$display_langcode = 'en';
// Map the interface language code to a CKEditor translation.
$ckeditor_langcodes = $this->getLangcodes();
$language_interface = $this->languageManager->getCurrentLanguage();
if (isset($ckeditor_langcodes[$language_interface->getId()])) {
$display_langcode = $ckeditor_langcodes[$language_interface->getId()];
}
// Next, set the most fundamental CKEditor settings.
$external_plugin_files = $this->ckeditorPluginManager->getEnabledPluginFiles($editor);
$settings += array('toolbar' => $this->buildToolbarJSSetting($editor), 'contentsCss' => $this->buildContentsCssJSSetting($editor), 'extraPlugins' => implode(',', array_keys($external_plugin_files)), 'language' => $display_langcode, 'stylesSet' => FALSE);
// Finally, set Drupal-specific CKEditor settings.
$settings += array('drupalExternalPlugins' => array_map('file_create_url', $external_plugin_files));
// Parse all CKEditor plugin JavaScript files for translations.
if ($this->moduleHandler->moduleExists('locale')) {
locale_js_translate(array_values($external_plugin_files));
}
ksort($settings);
return $settings;
}
示例15: doCreate
/**
* {@inheritdoc}
*/
protected function doCreate(array $values)
{
// Set default language to current language if not provided.
$values += array($this->langcodeKey => $this->languageManager->getCurrentLanguage()->getId());
$entity = new $this->entityClass($values, $this->entityTypeId);
return $entity;
}