本文整理汇总了PHP中Drupal::token方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::token方法的具体用法?PHP Drupal::token怎么用?PHP Drupal::token使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::token方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testLocalizedTokenizedString
/**
* Tests if a translated and tokenized string is properly escaped by Twig.
*
* In each assert* call we add a new line at the expected result to match the
* newline at the end of the template file.
*/
public function testLocalizedTokenizedString()
{
$tests_to_do = [1 => ['original' => 'Go to the <a href="[locale_test:security_test1]">frontpage</a>', 'replaced' => 'Go to the <a href="javascript:alert(&#039;Mooooh!&#039;);">frontpage</a>'], 2 => ['original' => 'Hello <strong>[locale_test:security_test2]</strong>!', 'replaced' => 'Hello <strong>&lt;script&gt;alert(&#039;Mooooh!&#039;);&lt;/script&gt;</strong>!']];
foreach ($tests_to_do as $i => $test) {
$original_string = $test['original'];
$rendered_original_string = \Drupal::theme()->render('locale_test_tokenized', ['content' => $original_string]);
// Twig assumes that strings are unsafe so it escapes them, and so the
// original and the rendered version should be different.
$this->assertNotEqual($rendered_original_string, $original_string . "\n", 'Security test ' . $i . ' before translation');
// Pass the original string to the t() function to get it marked as safe.
$safe_string = t($original_string);
$rendered_safe_string = \Drupal::theme()->render('locale_test_tokenized', ['content' => $safe_string]);
// t() function always marks the string as safe so it won't be escaped,
// and should be the same as the original.
$this->assertEqual($rendered_safe_string, $original_string . "\n", 'Security test ' . $i . ' after translation before token replacement');
// Replace tokens in the safe string to inject it with dangerous content.
// @see locale_test_tokens().
$unsafe_string = \Drupal::token()->replace($safe_string);
$rendered_unsafe_string = \Drupal::theme()->render('locale_test_tokenized', ['content' => $unsafe_string]);
// Token replacement changes the string so it is not marked as safe
// anymore. Check it is escaped the way we expect.
$this->assertEqual($rendered_unsafe_string, $test['replaced'] . "\n", 'Security test ' . $i . ' after translation after token replacement');
}
}
示例2: massageRenderValues
/**
* {@inheritdoc}
*/
public function massageRenderValues(&$field_settings, $values) {
if (isset($values['classes'])) {
$classes = is_array($values['classes']) ? implode(' ', $values['classes']) : $values['classes'];
if (!empty($classes)) {
$field_settings['classes'] = $classes;
}
}
// Token replacement.
if ($entity = $this->getEntity()) {
// Tokens
$apply_to = array(
'classes',
);
foreach ($apply_to as $identifier) {
$field_settings[$identifier] = \Drupal::token()->replace(
$field_settings[$identifier],
array($entity->getEntityTypeId() => $entity),
array('clear' => TRUE)
);
}
}
parent::massageRenderValues($field_settings, $values);
}
示例3: completeSale
/**
* {@inheritdoc}
*/
public function completeSale($order, $login = FALSE)
{
// Empty that cart...
$this->emptyCart();
// Force the order to load from the DB instead of the entity cache.
// @todo Remove this once uc_payment_enter() can modify order objects?
// @todo Should we be overwriting $order with this newly-loaded db_order?
$db_order = $this->entityManager()->getStorage('uc_order')->loadUnchanged($order->id());
$order->data = $db_order->data;
// Ensure that user creation and triggers are only run once.
if (empty($order->data->complete_sale)) {
$this->completeSaleAccount($order);
// Move an order's status from "In checkout" to "Pending".
if ($order->getStateId() == 'in_checkout') {
$order->setStatusId(uc_order_state_default('post_checkout'));
}
$order->save();
// Invoke the checkout complete trigger and hook.
$account = $order->getUser();
$this->moduleHandler()->invokeAll('uc_checkout_complete', array($order, $account));
// rules_invoke_event('uc_checkout_complete', $order);
}
$type = $order->data->complete_sale;
// Log in new users, if requested.
if ($type == 'new_user' && $login && $this->currentUser()->isAnonymous()) {
$type = 'new_user_logged_in';
user_login_finalize($order->getUser());
}
$message = $this->config('uc_cart.messages')->get($type);
$message = \Drupal::token()->replace($message, array('uc_order' => $order));
$variables['!new_username'] = isset($order->data->new_user_name) ? $order->data->new_user_name : '';
$variables['!new_password'] = isset($order->password) ? $order->password : t('Your password');
$message = strtr($message, $variables);
return array('#theme' => 'uc_cart_complete_sale', '#message' => Xss::filterAdmin($message), '#order' => $order);
}
示例4: viewElements
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items)
{
$element = array();
$entity = $items->getEntity();
$settings = $this->getSettings();
foreach ($items as $delta => $item) {
// By default use the full URL as the link text.
$url = $this->buildUrl($item);
$link_title = $url->toString();
// If the link text field value is available, use it for the text.
if (empty($settings['url_only']) && !empty($item->title)) {
// Unsanitized token replacement here because $options['html'] is FALSE
// by default in l().
$link_title = \Drupal::token()->replace($item->title, array($entity->getEntityTypeId() => $entity), array('sanitize' => FALSE, 'clear' => TRUE));
}
// The link_separate formatter has two titles; the link text (as in the
// field values) and the URL itself. If there is no link text value,
// $link_title defaults to the URL, so it needs to be unset.
// The URL version may need to be trimmed as well.
if (empty($item->title)) {
$link_title = NULL;
}
$url_title = $url->toString();
if (!empty($settings['trim_length'])) {
$link_title = truncate_utf8($link_title, $settings['trim_length'], FALSE, TRUE);
$url_title = truncate_utf8($url_title, $settings['trim_length'], FALSE, TRUE);
}
$element[$delta] = array('#theme' => 'link_formatter_link_separate', '#title' => $link_title, '#url_title' => $url_title, '#url' => $url);
}
return $element;
}
示例5: testStatisticsTokenReplacement
/**
* Creates a node, then tests the statistics tokens generated from it.
*/
function testStatisticsTokenReplacement()
{
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
// Create user and node.
$user = $this->drupalCreateUser(array('create page content'));
$this->drupalLogin($user);
$node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->id()));
// Hit the node.
$this->drupalGet('node/' . $node->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $node->id();
$post = http_build_query(array('nid' => $nid));
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
global $base_url;
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]);
$client->post($stats_path, array('headers' => $headers, 'body' => $post));
$statistics = statistics_get($node->id());
// Generate and test tokens.
$tests = array();
$tests['[node:total-count]'] = 1;
$tests['[node:day-count]'] = 1;
$tests['[node:last-view]'] = format_date($statistics['timestamp']);
$tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short');
// 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 = \Drupal::token()->replace($input, array('node' => $node), array('langcode' => $language_interface->getId()));
$this->assertEqual($output, $expected, format_string('Statistics token %token replaced.', array('%token' => $input)));
}
}
示例6: assertToken
public function assertToken($type, $object, $token, $expected)
{
$bubbleable_metadata = new BubbleableMetadata();
$tokens = \Drupal::token()->generate($type, array($token => $token), array($type => $object), [], $bubbleable_metadata);
$tokens += array($token => '');
$this->assertIdentical($tokens[$token], $expected, t("Token value for [@type:@token] was '@actual', expected value '@expected'.", array('@type' => $type, '@token' => $token, '@actual' => $tokens[$token], '@expected' => $expected)));
}
示例7: testUploadPath
/**
* Tests the normal formatter display on node display.
*/
function testUploadPath()
{
$field_name = strtolower($this->randomMachineName());
$type_name = 'article';
$this->createFileField($field_name, 'node', $type_name);
$test_file = $this->getTestFile('text');
// Create a new node.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
// Check that the file was uploaded to the file root.
$node = node_load($nid, TRUE);
$node_file = file_load($node->{$field_name}->target_id);
$this->assertPathMatch('public://' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri())));
// Change the path to contain multiple subdirectories.
$this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz'));
// Upload a new file into the subdirectories.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
// Check that the file was uploaded into the subdirectory.
$node = node_load($nid, TRUE);
$node_file = file_load($node->{$field_name}->target_id, TRUE);
$this->assertPathMatch('public://foo/bar/baz/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri())));
// Check the path when used with tokens.
// Change the path to contain multiple token directories.
$this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]'));
// Upload a new file into the token subdirectories.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
// Check that the file was uploaded into the subdirectory.
$node = node_load($nid, TRUE);
$node_file = file_load($node->{$field_name}->target_id);
// Do token replacement using the same user which uploaded the file, not
// the user running the test case.
$data = array('user' => $this->admin_user);
$subdirectory = \Drupal::token()->replace('[user:uid]/[user:name]', $data);
$this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->getFileUri())));
}
示例8: testTokenReplacement
/**
* Tests core token replacements generated from a view.
*/
function testTokenReplacement()
{
$token_handler = \Drupal::token();
$view = Views::getView('test_tokens');
$view->setDisplay('page_1');
$this->executeView($view);
$expected = array('[view:label]' => 'Test tokens', '[view:description]' => 'Test view to token replacement tests.', '[view:id]' => 'test_tokens', '[view:title]' => 'Test token page', '[view:url]' => $view->getUrl(NULL, 'page_1')->setAbsolute(TRUE)->toString(), '[view:total-rows]' => (string) $view->total_rows, '[view:base-table]' => 'views_test_data', '[view:base-field]' => 'id', '[view:items-per-page]' => '10', '[view:current-page]' => '1', '[view:page-count]' => '1');
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($view->storage);
$metadata_tests = [];
$metadata_tests['[view:label]'] = $base_bubbleable_metadata;
$metadata_tests['[view:description]'] = $base_bubbleable_metadata;
$metadata_tests['[view:id]'] = $base_bubbleable_metadata;
$metadata_tests['[view:title]'] = $base_bubbleable_metadata;
$metadata_tests['[view:url]'] = $base_bubbleable_metadata;
$metadata_tests['[view:total-rows]'] = $base_bubbleable_metadata;
$metadata_tests['[view:base-table]'] = $base_bubbleable_metadata;
$metadata_tests['[view:base-field]'] = $base_bubbleable_metadata;
$metadata_tests['[view:items-per-page]'] = $base_bubbleable_metadata;
$metadata_tests['[view:current-page]'] = $base_bubbleable_metadata;
$metadata_tests['[view:page-count]'] = $base_bubbleable_metadata;
foreach ($expected as $token => $expected_output) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_handler->replace($token, array('view' => $view), [], $bubbleable_metadata);
$this->assertIdentical($output, $expected_output, format_string('Token %token replaced correctly.', array('%token' => $token)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$token]);
}
}
示例9: testSchedulerTokenReplacement
/**
* Creates a node, then tests the tokens generated from it.
*/
function testSchedulerTokenReplacement()
{
$this->drupalLogin($this->adminUser);
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$date_formatter = \Drupal::service('date.formatter');
// Define timestamps for consistent use when repeated throughout this test.
$publish_on_timestamp = REQUEST_TIME + 3600;
$unpublish_on_timestamp = REQUEST_TIME + 7200;
// Create an unpublished page with scheduled dates.
$settings = ['type' => 'page', 'status' => FALSE, 'publish_on' => $publish_on_timestamp, 'unpublish_on' => $unpublish_on_timestamp];
$node = $this->drupalCreateNode($settings);
// Show that the node is scheduled.
$this->drupalGet('admin/content/scheduled');
// Create array of test case data.
$test_cases = array(['token_format' => '', 'date_format' => 'medium', 'custom' => ''], ['token_format' => ':long', 'date_format' => 'long', 'custom' => ''], ['token_format' => ':raw', 'date_format' => 'custom', 'custom' => 'U'], ['token_format' => ':custom:jS F g:ia e O', 'date_format' => 'custom', 'custom' => 'jS F g:ia e O']);
foreach ($test_cases as $test_data) {
// Edit the node and set the body tokens to use the format being tested.
$edit = ['body[0][value]' => 'Publish on: [node:scheduler-publish' . $test_data['token_format'] . ']. Unpublish on: [node:scheduler-unpublish' . $test_data['token_format'] . '].'];
$this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep unpublished'));
$this->drupalGet('node/' . $node->id());
// Refresh the node and get the body output value.
$node_storage->resetCache(array($node->id()));
$node = $node_storage->load($node->id());
$body_output = \Drupal::token()->replace($node->body->value, array('node' => $node));
// Create the expected text for the body.
$publish_on_date = $date_formatter->format($publish_on_timestamp, $test_data['date_format'], $test_data['custom']);
$unpublish_on_date = $date_formatter->format($unpublish_on_timestamp, $test_data['date_format'], $test_data['custom']);
$expected_output = 'Publish on: ' . $publish_on_date . '. Unpublish on: ' . $unpublish_on_date . '.';
// Check that the actual text matches the expected value.
$this->assertEqual($body_output, $expected_output, 'Scheduler tokens replaced correctly for ' . $test_data['token_format'] . ' format.');
}
}
示例10: assertToken
/**
* Assert that the provided token matches the provided value.
*
* @param string $token
* The token to test.
* @param string $value
* The value to check against the token.
* @param array $data
* The data to process the token with.
*
* @return bool
* TRUE if the assertion succeeded, FALSE otherwise.
*/
public function assertToken($token, $value, $data) {
$result = \Drupal::token()->replace($token, $data);
return $this->assertEqual($result, $value, $this->t('Token @token equals @value', [
'@token' => $token,
'@value' => $value,
]));
}
示例11: setUp
public function setUp()
{
parent::setUp();
// Install default system configuration.
$this->installConfig(array('system'));
$this->interfaceLanguage = \Drupal::languageManager()->getCurrentLanguage();
$this->tokenService = \Drupal::token();
}
示例12: testTokenIntegration
/**
* Tests token integration.
*/
function testTokenIntegration()
{
$token_service = \Drupal::token();
$tokens = array('[currency:code]' => 'XXX', '[currency:number]' => '999', '[currency:subunits]' => '0');
$data = array('currency' => 'XXX');
foreach ($tokens as $token => $replacement) {
$this->assertEqual($token_service->replace($token, $data), $replacement);
}
}
示例13: setUp
protected function setUp()
{
parent::setUp();
// Install default system configuration.
$this->installConfig(array('system'));
\Drupal::service('router.builder')->rebuild();
$this->interfaceLanguage = \Drupal::languageManager()->getCurrentLanguage();
$this->tokenService = \Drupal::token();
}
示例14: testDefaults
/**
* Tests the interface to manage metatag defaults.
*/
function testDefaults()
{
// Save the default title to test the Revert operation at the end.
$metatag_defaults = \Drupal::config('metatag.metatag_defaults.global');
$default_title = $metatag_defaults->get('tags')['title'];
// Initiate session with a user who can manage metatags.
$permissions = array('administer site configuration', 'administer meta tags');
$account = $this->drupalCreateUser($permissions);
$this->drupalLogin($account);
// Check that the user can see the list of metatag defaults.
$this->drupalGet('admin/structure/metatag_defaults');
$this->assertResponse(200);
// Check that the Global defaults were created.
$this->assertLinkByHref('/admin/structure/metatag_defaults/global', 0, t('Global defaults were created on installation.'));
// Check that Global and entity defaults can't be deleted.
$this->assertNoLinkByHref('/admin/structure/metatag_defaults/global/delete', 0, t('Global defaults can\'t be deleted'));
$this->assertNoLinkByHref('/admin/structure/metatag_defaults/node/delete', 0, t('Entity defaults can\'t be deleted'));
// Check that the module defaults were injected into the Global config entity.
$this->drupalGet('admin/structure/metatag_defaults/global');
$this->assertFieldById('edit-title', $metatag_defaults->get('title'), t('Metatag defaults were injected into the Global configuration entity.'));
// Update the Global defaults and test them.
$values = array('title' => 'Test title', 'description' => 'Test description');
$this->drupalPostForm('admin/structure/metatag_defaults/global', $values, 'Save');
$this->assertText('Saved the Global Metatag defaults.');
$this->drupalGet('hit-a-404');
foreach ($values as $metatag => $value) {
$this->assertRaw($value, t('Updated metatag @tag was found in the HEAD section of the page.', array('@tag' => $metatag)));
}
// Check that tokens are processed.
$values = array('title' => '[site:name] | Test title', 'description' => '[site:name] | Test description');
$this->drupalPostForm('admin/structure/metatag_defaults/global', $values, 'Save');
$this->assertText('Saved the Global Metatag defaults.');
drupal_flush_all_caches();
$this->drupalGet('hit-a-404');
foreach ($values as $metatag => $value) {
$processed_value = \Drupal::token()->replace($value);
$this->assertRaw($processed_value, t('Processed token for metatag @tag was found in the HEAD section of the page.', array('@tag' => $metatag)));
}
// Test the Robots plugin.
$robots_values = array('index', 'follow', 'noydir');
$form_values = array();
foreach ($robots_values as $value) {
$values['robots[' . $value . ']'] = TRUE;
}
$this->drupalPostForm('admin/structure/metatag_defaults/global', $values, 'Save');
$this->assertText('Saved the Global Metatag defaults.');
drupal_flush_all_caches();
$this->drupalGet('hit-a-404');
$robots_value = implode(', ', $robots_values);
$this->assertRaw($robots_value, t('Robots metatag has the expected values.'));
// Test reverting global configuration to its defaults.
$this->drupalPostForm('admin/structure/metatag_defaults/global/revert', array(), 'Revert');
$this->assertText('Reverted Global defaults.');
$this->assertText($default_title, 'Global title was reverted to its default value.');
$this->drupalLogout();
}
示例15: assertNoTokens
function assertNoTokens($type, array $data, array $tokens, array $options = array())
{
$input = $this->mapTokenNames($type, $tokens);
$replacements = \Drupal::token()->generate($type, $input, $data, $options);
foreach ($tokens as $name) {
$token = $input[$name];
$this->assertTrue(!isset($replacements[$token]), t("Token value for @token was not generated.", array('@type' => $type, '@token' => $token)));
}
return $values;
}