You are here

public function TokenReplaceKernelTest::testSystemTokenRecognition in Drupal 8

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

Test 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
      ->assertTrue($output == $expected, new FormattableMarkup('Token recognized in string %string', [
      '%string' => $input,
    ]));
  }

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