You are here

public function TokenReplaceKernelTest::testSystemTokenRecognition in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php \Drupal\Tests\system\Kernel\Token\TokenReplaceKernelTest::testSystemTokenRecognition()
  2. 9 core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php \Drupal\Tests\system\Kernel\Token\TokenReplaceKernelTest::testSystemTokenRecognition()

Tests whether token-replacement works in various contexts.

File

core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php, line 31

Class

TokenReplaceKernelTest
Generates text using placeholders for dummy content to check token replacement.

Namespace

Drupal\Tests\system\Kernel\Token

Code

public function testSystemTokenRecognition() {

  // Generate prefixes and suffixes for the token context.
  $tests = [
    [
      'prefix' => 'this is the ',
      'suffix' => ' site',
    ],
    [
      'prefix' => 'this is the',
      'suffix' => 'site',
    ],
    [
      'prefix' => '[',
      'suffix' => ']',
    ],
    [
      'prefix' => '',
      'suffix' => ']]]',
    ],
    [
      'prefix' => '[[[',
      'suffix' => '',
    ],
    [
      'prefix' => ':[:',
      'suffix' => '--]',
    ],
    [
      'prefix' => '-[-',
      'suffix' => ':]:',
    ],
    [
      'prefix' => '[:',
      'suffix' => ']',
    ],
    [
      'prefix' => '[site:',
      'suffix' => ':name]',
    ],
    [
      'prefix' => '[site:',
      'suffix' => ']',
    ],
  ];

  // Check if the token is recognized in each of the contexts.
  foreach ($tests as $test) {
    $input = $test['prefix'] . '[site:name]' . $test['suffix'];
    $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
    $output = $this->tokenService
      ->replace($input, [], [
      'langcode' => $this->interfaceLanguage
        ->getId(),
    ]);
    $this
      ->assertSame($expected, $output, new FormattableMarkup('Token recognized in string %string', [
      '%string' => $input,
    ]));
  }

  // Test token replacement when the string contains no tokens.
  $this
    ->assertEquals('No tokens here.', $this->tokenService
    ->replace('No tokens here.'));
}