本文整理汇总了PHP中user_format_name函数的典型用法代码示例。如果您正苦于以下问题:PHP user_format_name函数的具体用法?PHP user_format_name怎么用?PHP user_format_name使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了user_format_name函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testUserHooks
public function testUserHooks()
{
FieldStorageConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user'))->save();
FieldConfig::create(array('field_name' => 'field_text', 'type' => 'string', 'entity_type' => 'user', 'bundle' => 'user'))->save();
$this->assertIdentical('', \Drupal::config('name.settings')->get('user_preferred'));
FieldStorageConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user'))->save();
FieldStorageConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user'))->save();
$field = FieldConfig::create(array('field_name' => 'field_name_test', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
$field->save();
$field2 = FieldConfig::create(array('field_name' => 'field_name_test2', 'type' => 'name', 'entity_type' => 'user', 'bundle' => 'user'));
$field2->save();
$this->assertEqual($field->getName(), \Drupal::config('name.settings')->get('user_preferred'));
\Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field2->getName())->save();
$field2->delete();
$this->assertEqual('', \Drupal::config('name.settings')->get('user_preferred'));
\Drupal::configFactory()->getEditable('name.settings')->set('user_preferred', $field->getName())->save();
$account = User::create(array('name' => 'test'));
$account->field_name_test[0] = array('given' => 'Max', 'family' => 'Mustermann');
$account->save();
$account = User::load($account->id());
$this->assertEqual('Max Mustermann', $account->realname);
$this->assertEqual('Max Mustermann', user_format_name($account));
$this->assertEqual('test', $account->getUsername());
$this->assertEqual('Max Mustermann', $account->getDisplayName());
}
示例2: blockForm
/**
* {@inheritdoc}
*/
public function blockForm($form, &$form_state)
{
$form['list_size'] = array('#type' => 'textfield', '#title' => t('Number of users to display in the list'), '#default_value' => $this->configuration['list_size'], '#size' => '3', '#maxlength' => '4');
$form['include_anon'] = array('#type' => 'checkbox', '#title' => t('Include %anonymous', array('%anonymous' => user_format_name(drupal_anonymous_user()))), '#default_value' => $this->configuration['include_anon']);
$form['show_form'] = array('#type' => 'checkbox', '#title' => t('Allow entering any user name'), '#default_value' => $this->configuration['show_form']);
return $form;
}
示例3: testFileTokenReplacement
/**
* Creates a file, then tests the tokens generated from it.
*/
function testFileTokenReplacement()
{
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
// Create file field.
$type_name = 'article';
$field_name = 'field_' . strtolower($this->randomMachineName());
$this->createFileField($field_name, 'node', $type_name);
$test_file = $this->getTestFile('text');
// Coping a file to test uploads with non-latin filenames.
$filename = drupal_dirname($test_file->getFileUri()) . '/текстовый файл.txt';
$test_file = file_copy($test_file, $filename);
// Create a new node with the uploaded file.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
// Load the node and the file.
$node_storage->resetCache(array($nid));
$node = $node_storage->load($nid);
$file = file_load($node->{$field_name}->target_id);
// Generate and test sanitized tokens.
$tests = array();
$tests['[file:fid]'] = $file->id();
$tests['[file:name]'] = String::checkPlain($file->getFilename());
$tests['[file:path]'] = String::checkPlain($file->getFileUri());
$tests['[file:mime]'] = String::checkPlain($file->getMimeType());
$tests['[file:size]'] = format_size($file->getSize());
$tests['[file:url]'] = String::checkPlain(file_create_url($file->getFileUri()));
$tests['[file:created]'] = format_date($file->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[file:created:short]'] = format_date($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[file:changed]'] = format_date($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[file:changed:short]'] = format_date($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[file:owner]'] = String::checkPlain(user_format_name($this->adminUser));
$tests['[file:owner:uid]'] = $file->getOwnerId();
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId()));
$this->assertEqual($output, $expected, format_string('Sanitized file token %token replaced.', array('%token' => $input)));
}
// Generate and test unsanitized tokens.
$tests['[file:name]'] = $file->getFilename();
$tests['[file:path]'] = $file->getFileUri();
$tests['[file:mime]'] = $file->getMimeType();
$tests['[file:size]'] = format_size($file->getSize());
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('file' => $file), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized file token %token replaced.', array('%token' => $input)));
}
}
示例4: renderLink
/**
* {@inheritdoc}
*/
protected function renderLink($data, ResultRow $values)
{
$account = entity_create('user');
$account->uid = $this->getValue($values, 'uid');
$account->name = $this->getValue($values);
if (!empty($this->options['link_to_user']) || !empty($this->options['overwrite_anonymous'])) {
if (!empty($this->options['overwrite_anonymous']) && !$account->id()) {
// This is an anonymous user, and we're overriting the text.
return String::checkPlain($this->options['anonymous_text']);
} elseif (!empty($this->options['link_to_user'])) {
$account->name = $this->getValue($values);
$username = array('#theme' => 'username', '#account' => $account);
return drupal_render($username);
}
}
// If we want a formatted username, do that.
if (!empty($this->options['format_username'])) {
return user_format_name($account);
}
// Otherwise, there's no special handling, so return the data directly.
return $data;
}
示例5: testUserTokenReplacement
/**
* Creates a user, then tests the tokens generated from it.
*/
function testUserTokenReplacement()
{
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$url_options = array('absolute' => TRUE, 'language' => $language_interface);
// Create two users and log them in one after another.
$user1 = $this->drupalCreateUser(array());
$user2 = $this->drupalCreateUser(array());
$this->drupalLogin($user1);
$this->drupalLogout();
$this->drupalLogin($user2);
$account = user_load($user1->id());
$global_account = user_load(\Drupal::currentUser()->id());
// Generate and test sanitized tokens.
$tests = array();
$tests['[user:uid]'] = $account->id();
$tests['[user:name]'] = String::checkPlain(user_format_name($account));
$tests['[user:mail]'] = String::checkPlain($account->getEmail());
$tests['[user:url]'] = $account->url('canonical', $url_options);
$tests['[user:edit-url]'] = $account->url('edit-form', $url_options);
$tests['[user:last-login]'] = format_date($account->getLastLoginTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[user:last-login:short]'] = format_date($account->getLastLoginTime(), 'short', '', NULL, $language_interface->getId());
$tests['[user:created]'] = format_date($account->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[user:created:short]'] = format_date($account->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[current-user:name]'] = String::checkPlain(user_format_name($global_account));
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId()));
$this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
}
// Generate and test unsanitized tokens.
$tests['[user:name]'] = user_format_name($account);
$tests['[user:mail]'] = $account->getEmail();
$tests['[current-user:name]'] = user_format_name($global_account);
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized user token %token replaced.', array('%token' => $input)));
}
// Generate login and cancel link.
$tests = array();
$tests['[user:one-time-login-url]'] = user_pass_reset_url($account);
$tests['[user:cancel-url]'] = user_cancel_url($account);
// Generate tokens with interface language.
$link = \Drupal::url('user.page', [], array('absolute' => TRUE));
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
$this->assertTrue(strpos($output, $link) === 0, 'Generated URL is in interface language.');
}
// Generate tokens with the user's preferred language.
$account->preferred_langcode = 'de';
$account->save();
$link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()), 'absolute' => TRUE));
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
$this->assertTrue(strpos($output, $link) === 0, "Generated URL is in the user's preferred language.");
}
// Generate tokens with one specific language.
$link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage('de'), 'absolute' => TRUE));
foreach ($tests as $input => $expected) {
foreach (array($user1, $user2) as $account) {
$output = $token_service->replace($input, array('user' => $account), array('langcode' => 'de', 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
$this->assertTrue(strpos($output, $link) === 0, "Generated URL in in the requested language.");
}
}
}
示例6: entityQueryAlter
/**
* {@inheritdoc}
*/
public function entityQueryAlter(SelectInterface $query)
{
// Bail out early if we do not need to match the Anonymous user.
$handler_settings = $this->configuration['handler_settings'];
if (isset($handler_settings['include_anonymous']) && !$handler_settings['include_anonymous']) {
return;
}
if ($this->currentUser->hasPermission('administer users')) {
// In addition, if the user is administrator, we need to make sure to
// match the anonymous user, that doesn't actually have a name in the
// database.
$conditions =& $query->conditions();
foreach ($conditions as $key => $condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') {
// Remove the condition.
unset($conditions[$key]);
// Re-add the condition and a condition on uid = 0 so that we end up
// with a query in the form:
// WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
$or = db_or();
$or->condition($condition['field'], $condition['value'], $condition['operator']);
// Sadly, the Database layer doesn't allow us to build a condition
// in the form ':placeholder = :placeholder2', because the 'field'
// part of a condition is always escaped.
// As a (cheap) workaround, we separately build a condition with no
// field, and concatenate the field and the condition separately.
$value_part = db_and();
$value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
$value_part->compile($this->connection, $query);
$or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name($this->userStorage->load(0))))->condition('base_table.uid', 0));
$query->condition($or);
}
}
}
}
示例7: hook_mail
/**
* Prepares a message based on parameters;
*
* This hook is called from MailManagerInterface->mail(). Note that hook_mail(),
* unlike hook_mail_alter(), is only called on the $module argument to
* MailManagerInterface->mail(), not all modules.
*
* @param $key
* An identifier of the mail.
* @param $message
* An array to be filled in. Elements in this array include:
* - id: An ID to identify the mail sent. Look at module source code or
* MailManagerInterface->mail() for possible id values.
* - to: The address or addresses the message will be sent to. The
* formatting of this string must comply with RFC 2822.
* - subject: Subject of the email to be sent. This must not contain any
* newline characters, or the mail may not be sent properly.
* MailManagerInterface->mail() sets this to an empty
* string when the hook is invoked.
* - body: An array of lines containing the message to be sent. Drupal will
* format the correct line endings for you. MailManagerInterface->mail()
* sets this to an empty array when the hook is invoked.
* - from: The address the message will be marked as being from, which is
* set by MailManagerInterface->mail() to either a custom address or the
* site-wide default email address when the hook is invoked.
* - headers: Associative array containing mail headers, such as From,
* Sender, MIME-Version, Content-Type, etc.
* MailManagerInterface->mail() pre-fills several headers in this array.
* @param $params
* An array of parameters supplied by the caller of
* MailManagerInterface->mail().
*
* @see \Drupal\Core\Mail\MailManagerInterface->mail()
*/
function hook_mail($key, &$message, $params)
{
$account = $params['account'];
$context = $params['context'];
$variables = array('%site_name' => \Drupal::config('system.site')->get('name'), '%username' => user_format_name($account));
if ($context['hook'] == 'taxonomy') {
$entity = $params['entity'];
$vocabulary = Vocabulary::load($entity->id());
$variables += array('%term_name' => $entity->name, '%term_description' => $entity->description, '%term_id' => $entity->id(), '%vocabulary_name' => $vocabulary->label(), '%vocabulary_description' => $vocabulary->getDescription(), '%vocabulary_id' => $vocabulary->id());
}
// Node-based variable translation is only available if we have a node.
if (isset($params['node'])) {
/** @var \Drupal\node\NodeInterface $node */
$node = $params['node'];
$variables += array('%uid' => $node->getOwnerId(), '%url' => $node->url('canonical', array('absolute' => TRUE)), '%node_type' => node_get_type_label($node), '%title' => $node->getTitle(), '%teaser' => $node->teaser, '%body' => $node->body);
}
$subject = strtr($context['subject'], $variables);
$body = strtr($context['message'], $variables);
$message['subject'] .= str_replace(array("\r", "\n"), '', $subject);
$message['body'][] = MailFormatHelper::htmlToText($body);
}
示例8: hook_mail
/**
* Prepare a message based on parameters; called from backdrop_mail().
*
* Note that hook_mail(), unlike hook_mail_alter(), is only called on the
* $module argument to backdrop_mail(), not all modules.
*
* @param $key
* An identifier of the mail.
* @param $message
* An array to be filled in. Elements in this array include:
* - id: An ID to identify the mail sent. Look at module source code
* or backdrop_mail() for possible id values.
* - to: The address or addresses the message will be sent to. The
* formatting of this string must comply with RFC 2822.
* - subject: Subject of the e-mail to be sent. This must not contain any
* newline characters, or the mail may not be sent properly. backdrop_mail()
* sets this to an empty string when the hook is invoked.
* - body: An array of lines containing the message to be sent. Backdrop will
* format the correct line endings for you. backdrop_mail() sets this to an
* empty array when the hook is invoked.
* - from: The address the message will be marked as being from, which is
* set by backdrop_mail() to either a custom address or the site-wide
* default email address when the hook is invoked.
* - headers: Associative array containing mail headers, such as From,
* Sender, MIME-Version, Content-Type, etc. backdrop_mail() pre-fills
* several headers in this array.
* @param $params
* An array of parameters supplied by the caller of backdrop_mail().
*/
function hook_mail($key, &$message, $params)
{
$account = $params['account'];
$context = $params['context'];
$variables = array('%site_name' => config_get('system.core', 'site_name'), '%username' => user_format_name($account));
if ($context['hook'] == 'taxonomy') {
$entity = $params['entity'];
$vocabulary = taxonomy_vocabulary_load($entity->vocabulary);
$variables += array('%term_name' => $entity->name, '%term_description' => $entity->description, '%term_id' => $entity->tid, '%vocabulary_name' => $vocabulary->name, '%vocabulary_description' => $vocabulary->description, '%vocabulary_machine_name' => $vocabulary->machine_name);
}
// Node-based variable translation is only available if we have a node.
if (isset($params['node'])) {
$node = $params['node'];
$variables += array('%uid' => $node->uid, '%node_url' => url('node/' . $node->nid, array('absolute' => TRUE)), '%node_type' => node_type_get_name($node), '%title' => $node->title, '%teaser' => $node->teaser, '%body' => $node->body);
}
$subject = strtr($context['subject'], $variables);
$body = strtr($context['message'], $variables);
$message['subject'] .= str_replace(array("\r", "\n"), '', $subject);
$message['body'][] = backdrop_html_to_text($body);
}
示例9: entityQueryAlter
/**
* {@inheritdoc}
*/
public function entityQueryAlter(SelectInterface $query)
{
if (\Drupal::currentUser()->hasPermission('administer users')) {
// In addition, if the user is administrator, we need to make sure to
// match the anonymous user, that doesn't actually have a name in the
// database.
$conditions =& $query->conditions();
foreach ($conditions as $key => $condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') {
// Remove the condition.
unset($conditions[$key]);
// Re-add the condition and a condition on uid = 0 so that we end up
// with a query in the form:
// WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
$or = db_or();
$or->condition($condition['field'], $condition['value'], $condition['operator']);
// Sadly, the Database layer doesn't allow us to build a condition
// in the form ':placeholder = :placeholder2', because the 'field'
// part of a condition is always escaped.
// As a (cheap) workaround, we separately build a condition with no
// field, and concatenate the field and the condition separately.
$value_part = db_and();
$value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
$value_part->compile(Database::getConnection(), $query);
$or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name(user_load(0))))->condition('base_table.uid', 0));
$query->condition($or);
}
}
}
// Add the filter by role option.
if (!empty($this->fieldDefinition->getSetting('handler_settings')['filter'])) {
$filter_settings = $this->fieldDefinition->getSetting('handler_settings')['filter'];
if ($filter_settings['type'] == 'role') {
$tables = $query->getTables();
$base_table = $tables['base_table']['alias'];
$query->join('users_roles', 'ur', $base_table . '.uid = ur.uid');
$query->condition('ur.rid', $filter_settings['role']);
}
}
}
示例10: testUserTokenReplacement
/**
* Creates a user, then tests the tokens generated from it.
*/
function testUserTokenReplacement()
{
$token_service = \Drupal::token();
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$url_options = array('absolute' => TRUE, 'language' => $language_interface);
// Create two users and log them in one after another.
$user1 = $this->drupalCreateUser(array());
$user2 = $this->drupalCreateUser(array());
$this->drupalLogin($user1);
$this->drupalLogout();
$this->drupalLogin($user2);
$account = User::load($user1->id());
$global_account = User::load(\Drupal::currentUser()->id());
// Generate and test sanitized tokens.
$tests = array();
$tests['[user:uid]'] = $account->id();
$tests['[user:name]'] = SafeMarkup::checkPlain(user_format_name($account));
$tests['[user:mail]'] = SafeMarkup::checkPlain($account->getEmail());
$tests['[user:url]'] = $account->url('canonical', $url_options);
$tests['[user:edit-url]'] = $account->url('edit-form', $url_options);
$tests['[user:last-login]'] = format_date($account->getLastLoginTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[user:last-login:short]'] = format_date($account->getLastLoginTime(), 'short', '', NULL, $language_interface->getId());
$tests['[user:created]'] = format_date($account->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[user:created:short]'] = format_date($account->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[current-user:name]'] = SafeMarkup::checkPlain(user_format_name($global_account));
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($account);
$metadata_tests = [];
$metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
$metadata_tests['[user:name]'] = $base_bubbleable_metadata;
$metadata_tests['[user:mail]'] = $base_bubbleable_metadata;
$metadata_tests['[user:url]'] = $base_bubbleable_metadata;
$metadata_tests['[user:edit-url]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
// This test runs with the Language module enabled, which means config is
// overridden by LanguageConfigFactoryOverride (to provide translations of
// config). This causes the interface language cache context to be added for
// config entities. The four next tokens use DateFormat Config entities, and
// therefore have the interface language cache context.
$bubbleable_metadata->addCacheContexts(['languages:language_interface']);
$metadata_tests['[user:last-login]'] = $bubbleable_metadata->addCacheTags(['rendered']);
$metadata_tests['[user:last-login:short]'] = $bubbleable_metadata;
$metadata_tests['[user:created]'] = $bubbleable_metadata;
$metadata_tests['[user:created:short]'] = $bubbleable_metadata;
$metadata_tests['[current-user:name]'] = $base_bubbleable_metadata->merge(BubbleableMetadata::createFromObject($global_account)->addCacheContexts(['user']));
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
$this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate tokens for the anonymous user.
$anonymous_user = User::load(0);
$tests = [];
$tests['[user:uid]'] = t('not yet assigned');
$tests['[user:name]'] = SafeMarkup::checkPlain(user_format_name($anonymous_user));
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($anonymous_user);
$metadata_tests = [];
$metadata_tests['[user:uid]'] = $base_bubbleable_metadata;
$bubbleable_metadata = clone $base_bubbleable_metadata;
$bubbleable_metadata->addCacheableDependency(\Drupal::config('user.settings'));
$metadata_tests['[user:name]'] = $bubbleable_metadata;
foreach ($tests as $input => $expected) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_service->replace($input, array('user' => $anonymous_user), array('langcode' => $language_interface->getId()), $bubbleable_metadata);
$this->assertEqual($output, $expected, format_string('Sanitized user token %token replaced.', array('%token' => $input)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
// Generate and test unsanitized tokens.
$tests = [];
$tests['[user:name]'] = user_format_name($account);
$tests['[user:mail]'] = $account->getEmail();
$tests['[current-user:name]'] = user_format_name($global_account);
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId(), 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized user token %token replaced.', array('%token' => $input)));
}
// Generate login and cancel link.
$tests = array();
$tests['[user:one-time-login-url]'] = user_pass_reset_url($account);
$tests['[user:cancel-url]'] = user_cancel_url($account);
// Generate tokens with interface language.
$link = \Drupal::url('user.page', [], array('absolute' => TRUE));
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('langcode' => $language_interface->getId(), 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
$this->assertTrue(strpos($output, $link) === 0, 'Generated URL is in interface language.');
}
// Generate tokens with the user's preferred language.
$account->preferred_langcode = 'de';
$account->save();
$link = \Drupal::url('user.page', [], array('language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()), 'absolute' => TRUE));
foreach ($tests as $input => $expected) {
$output = $token_service->replace($input, array('user' => $account), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));
$this->assertTrue(strpos($output, $link) === 0, "Generated URL is in the user's preferred language.");
}
// Generate tokens with one specific language.
//.........这里部分代码省略.........
示例11: switchUserList
/**
* Provides the Switch user list.
*/
public function switchUserList()
{
$list_size = $this->configuration['list_size'];
$include_anon = $this->configuration['include_anon'];
$anon = new AnonymousUserSession();
$links = array();
if ($this->currentUser->hasPermission('switch users')) {
if ($include_anon) {
--$list_size;
}
$dest = $this->redirectDestination->getAsArray();
// Try to find at least $list_size users that can switch.
// Inactive users are omitted from all of the following db selects.
$roles = user_roles(TRUE, 'switch users');
$query = db_select('users', 'u');
$query->join('users_field_data', 'ufd');
$query->addField('u', 'uid');
$query->addField('ufd', 'access');
$query->distinct();
$query->condition('u.uid', 0, '>');
$query->condition('ufd.status', 0, '>');
$query->orderBy('ufd.access', 'DESC');
$query->range(0, $list_size);
if (!isset($roles[DRUPAL_AUTHENTICATED_RID])) {
$query->leftJoin('users_roles', 'r', 'u.uid = r.uid');
$or_condition = db_or();
$or_condition->condition('u.uid', 1);
if (!empty($roles)) {
$or_condition->condition('r.rid', array_keys($roles), 'IN');
}
$query->condition($or_condition);
}
$uids = $query->execute()->fetchCol();
$accounts = user_load_multiple($uids);
foreach ($accounts as $account) {
$path = 'devel/switch/' . $account->name->value;
$links[$account->id()] = array('title' => user_format_name($account), 'href' => $path, 'query' => $dest + array('token' => $this->csrfTokenGenerator->get($path)), 'attributes' => array('title' => t('This user can switch back.')), 'html' => TRUE, 'last_access' => $account->access->value);
}
$num_links = count($links);
if ($num_links < $list_size) {
// If we don't have enough, add distinct uids until we hit $list_size.
$uids = db_query_range('SELECT u.uid FROM {users} u INNER JOIN {users_field_data} ufd WHERE u.uid > 0 AND u.uid NOT IN (:uids) AND ufd.status > 0 ORDER BY ufd.access DESC', 0, $list_size - $num_links, array(':uids' => array_keys($links)))->fetchCol();
$accounts = user_load_multiple($uids);
foreach ($accounts as $account) {
$path = 'devel/switch/' . $account->name->value;
$links[$account->id()] = array('title' => user_format_name($account), 'href' => $path, 'query' => $dest + array('token' => $this->csrfTokenGenerator->get($path)), 'attributes' => array('title' => t('Caution: this user will be unable to switch back.')), 'last_access' => $account->access->value);
}
uasort($links, '_devel_switch_user_list_cmp');
}
if ($include_anon) {
$path = 'devel/switch';
$link = array('title' => $anon->getUsername(), 'href' => $path, 'query' => $dest + array('token' => $this->csrfTokenGenerator->get($path)), 'attributes' => array('title' => t('Caution: the anonymous user will be unable to switch back.')));
if ($this->currentUser->hasPermission('switch users')) {
$link['title'] = SafeMarkup::placeholder($link['title']);
$link['attributes'] = array('title' => t('This user can switch back.'));
$link['html'] = TRUE;
}
$links[$anon->id()] = $link;
}
}
if (array_key_exists($uid = $this->currentUser->id(), $links)) {
$links[$uid]['title'] = '<strong>' . $links[$uid]['title'] . '</strong>';
}
return $links;
}
示例12: build
/**
* {@inheritdoc}
*/
public function build()
{
$account = \Drupal::currentUser();
return ['#markup' => t('@welcome @username', array('@welcome' => $this->configuration['welcome_text'], '@username' => user_format_name($account)))];
}