token example

/** * {@inheritdoc} */
  public function usesOptions() {
    return $this->usesOptions;
  }

  /** * {@inheritdoc} */
  public function globalTokenReplace($string = '', array $options = []) {
    return \Drupal::token()->replace($string['view' => $this->view]$options);
  }

  /** * Replaces Views' tokens in a given string. * * The resulting string will be sanitized with Xss::filterAdmin. * * @param $text * Unsanitized string with possible tokens. * @param $tokens * Array of token => replacement_value items. * * @return string */
protected static $modules = ['system'];

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Install default system configuration.     $this->installConfig(['system']);

    $this->interfaceLanguage = \Drupal::languageManager()->getCurrentLanguage();
    $this->tokenService = \Drupal::token();
  }

}
/** * Views used by this test. * * @var array */
  public static $testViews = ['test_tokens', 'test_invalid_tokens'];

  /** * Tests core token replacements generated from a view. */
  public function testTokenReplacement() {
    $token_handler = \Drupal::token();
    $view = Views::getView('test_tokens');
    $view->setDisplay('page_1');
    // Force the view to span more than one page to better test page_count.     $view->display_handler->getPlugin('pager')->setItemsPerPage(4);
    $this->executeView($view);

    $expected = [
      '[view:label]' => 'Test tokens',
      '[view:description]' => 'Test view to token replacement tests.',
      '[view:id]' => 'test_tokens',
      '[view:title]' => 'Test token page',
      
$authorizationServer = $this->createMock(AuthorizationServer::class);
        $authorizationServer->method('respondToAccessTokenRequest')->willReturn(new Response());

        $controller = new AdminAuthController(
            $authorizationServer,
            $psrFactory,
            $this->mockResetLimiter([
                RateLimiter::OAUTH => 1,
            ])
        );

        $controller->token(new Request());
    }

    public function testRateLimitContactForm(): void
    {
        for ($i = 0; $i <= 3; ++$i) {
            $this->browser
                ->request(
                    'POST',
                    '/store-api/contact-form',
                    [
                        'salutationId' => $this->getValidSalutationId(),
                        
/** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * Creates a file, then tests the tokens generated from it. */
  public function testFileTokenReplacement() {
    $node_storage = $this->container->get('entity_type.manager')->getStorage('node');
    $token_service = \Drupal::token();
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = $this->container->get('date.formatter');

    // 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.

  protected function setUp(): void {
    parent::setUp();
    ConfigurableLanguage::createFromLangcode('de')->save();
  }

  /** * Creates a user, then tests the tokens generated from it. */
  public function testUserTokenReplacement() {
    $token_service = \Drupal::token();
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
    $url_options = [
      'absolute' => TRUE,
      'language' => $language_interface,
    ];

    \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
    \Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);

    // Create two users and log them in one after another.     $user1 = $this->drupalCreateUser([]);
    
    $this->drupalGet($this->assertLinkToCreatedMedia());

    // Assert the image element is present inside the media element and that its     // src attribute uses the large image style, the label is visually hidden,     // and there is no link to the image file.     $label = $assert_session->elementExists('xpath', '//div[contains(@class, "visually-hidden") and text()="Image"]');
    // The field is the parent div of the label.     $field = $label->getParent();
    $image_element = $field->find('css', 'img');
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $expected_image_src = $file_url_generator->generateString(\Drupal::token()->replace('public://styles/large/public/[date:custom:Y]-[date:custom:m]/example_1.jpeg'));
    $this->assertStringContainsString($expected_image_src$image_element->getAttribute('src'));
    $assert_session->elementNotExists('css', 'a', $field);

    // Ensure the image has the correct alt attribute.     $this->assertSame('Image Alt Text 1', $image_element->getAttribute('alt'));

    // Load the media and check that all fields are properly populated.     $media = Media::load(1);
    $this->assertSame('example_1.jpeg', $media->getName());
    $this->assertSame('200', $media->get('field_string_width')->value);
    $this->assertSame('89', $media->get('field_string_height')->value);

    

function hook_tokens($type$tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $token_service = \Drupal::token();

  $url_options = ['absolute' => TRUE];
  if (isset($options['langcode'])) {
    $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
    $langcode = $options['langcode'];
  }
  else {
    $langcode = NULL;
  }
  $replacements = [];

  
    $assert_session->elementTextContains('xpath', '//h1', $image_media_name);
    // Here we expect to see only the image, nothing else.     // Assert only one element in the content region.     $media_item = $assert_session->elementExists('xpath', '//div[@class="layout-content"]/div/div[2]');
    $assert_session->elementsCount('xpath', '/div', 1, $media_item);
    // Assert the image is present inside the media element.     $media_image = $assert_session->elementExists('xpath', '//img', $media_item);
    // Assert that the image src uses the large image style, the label is     // visually hidden, and there is no link to the image file.     /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $expected_image_src = $file_url_generator->generateString(\Drupal::token()->replace('public://styles/large/public/[date:custom:Y]-[date:custom:m]/example_1.jpeg'));
    $this->assertStringContainsString($expected_image_src$media_image->getAttribute('src'));
    $field = $assert_session->elementExists('xpath', '/div[1]', $media_item);
    $assert_session->elementExists('xpath', '/div[@class="visually-hidden"]', $field);
    $assert_session->elementNotExists('xpath', '//a', $field);

    $test_filename = $this->randomMachineName() . '.txt';
    $test_filepath = 'public://' . $test_filename;
    file_put_contents($test_filepath$this->randomMachineName());
    $this->drupalGet("media/add/document");
    $page->attachFileToField("files[field_media_document_0]", \Drupal::service('file_system')->realpath($test_filepath));
    $result = $assert_session->waitForButton('Remove');
    
protected function isDefaultValueWidget(FormStateInterface $form_state) {
    return (bool) $form_state->get('default_value_widget');
  }

  /** * Returns the filtered field description. * * @return \Drupal\Core\Field\FieldFilteredMarkup * The filtered field description, with tokens replaced. */
  protected function getFilteredDescription() {
    return FieldFilteredMarkup::create(\Drupal::token()->replace((string) $this->fieldDefinition->getDescription()));
  }

}
$display_repository->getViewDisplay('node', 'article')
      ->setComponent($this->fieldName, [
        'type' => 'entity_reference_label',
      ])
      ->save();
  }

  /** * Creates some terms and a node, then tests the tokens generated from them. */
  public function testTaxonomyTokenReplacement() {
    $token_service = \Drupal::token();
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();

    // Create two taxonomy terms.     $term1 = $this->createTerm($this->vocabulary);
    $term2 = $this->createTerm($this->vocabulary);

    // Edit $term2, setting $term1 as parent.     $edit = [];
    $edit['name[0][value]'] = '<blink>Blinking Text</blink>';
    $edit['parent[]'] = [$term1->id()];
    $this->drupalGet('taxonomy/term/' . $term2->id() . '/edit');
    
protected static $modules = ['taxonomy'];

  /** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * Creates a comment, then tests the tokens generated from it. */
  public function testCommentTokenReplacement() {
    $token_service = \Drupal::token();
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();
    $url_options = [
      'absolute' => TRUE,
      'language' => $language_interface,
    ];

    // Setup vocabulary.     Vocabulary::create([
      'vid' => 'tags',
      'name' => 'Tags',
    ])->save();

    
// 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_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $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 = ['user' => $this->adminUser];
    $subdirectory = \Drupal::token()->replace('[user:uid]/[user:name]', $data);
    $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename()$node_file->getFileUri()new FormattableMarkup('The file %file was uploaded to the correct path with token replacements.', ['%file' => $node_file->getFileUri()]));
  }

  /** * Asserts that a file is uploaded to the right location. * * @param string $expected_path * The location where the file is expected to be uploaded. Duplicate file * names to not need to be taken into account. * @param string $actual_path * Where the file was actually uploaded. * @param string $message * The message to display with this assertion. * * @internal */

  protected static function doGetUploadLocation(array $settings$data = []) {
    $destination = trim($settings['file_directory'], '/');

    // Replace tokens. As the tokens might contain HTML we convert it to plain     // text.     $destination = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($destination$data));
    return $settings['uri_scheme'] . '://' . $destination;
  }

  /** * Retrieves the upload validators for a file field. * * @return array * An array suitable for passing to file_save_upload() or the file field * element's '#upload_validators' property. */
  public function getUploadValidators() {
    
$date_formatter = $this->container->get('date.formatter');
    $request_time = \Drupal::time()->getRequestTime();

    // Generate and test tokens.     $tests = [];
    $tests['[node:total-count]'] = 0;
    $tests['[node:day-count]'] = 0;
    $tests['[node:last-view]'] = 'never';
    $tests['[node:last-view:short]'] = $date_formatter->format($request_time, 'short');

    foreach ($tests as $input => $expected) {
      $output = \Drupal::token()->replace($input['node' => $node]['langcode' => $language_interface->getId()]);
      $this->assertEquals($expected$outputnew FormattableMarkup('Statistics token %token replaced.', ['%token' => $input]));
    }

    // Hit the node.     $this->drupalGet('node/' . $node->id());
    // Manually calling statistics.php, simulating ajax behavior.     $nid = $node->id();
    $post = http_build_query(['nid' => $nid]);
    $headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
    global $base_url;
    $stats_path = $base_url . '/' . $this->getModulePath('statistics') . '/statistics.php';
    
Home | Imprint | This part of the site doesn't use cookies.