Tokens are cleared even when the clear option is false or not set

Created on 26 May 2025, 2 months ago

Problem/Motivation

When replacing the token "[token_or:empty|token_or:empty2]" with the option ["clear"=>FALSE], or not specified, we get unexpected behavior:

  • Returned String: ""
  • Expected String: "[token_or:empty|token_or:empty2]"

The default behavior of the Token::replace() function is to only clear tokens when the option ["clear"=>TRUE].

Steps to reproduce

The module already has a test where this behavior is incorrect:

 /**
   * Tests the basic functionality.
   */
  public function testTokenReplacement() {
    foreach ($this->renderMethods as $method) {
      ...
      $value = $this->tokenService->$method('[token_or:empty|token_or:empty2]');
      $this->assertEmpty($value);
      ...
  }

Proposed resolution

In the TokenOrTokensPreAlter class we should only execute $text = str_replace($match, '', $text); if clear option is set to TRUE.

Example:

/**
 * Tokens Pre Alter Service.
 */
class TokenOrTokensPreAlter {
  ...
  /**
   * Performs a tokens pre alter.
   */
  public function tokensPreAlter(&$text, $data, $options) {
    ...
    foreach (reset($matches) as $match) {
      if (strpos($match, '|') !== FALSE) {
        ...
        if (!empty($options["clear"])) {
          $text = str_replace($match, '', $text);
        }
      }
    }
  }
}

Remaining tasks

Create MR and tests.

User interface changes

None.

API changes

None.

Data model changes

None.

πŸ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡΅πŸ‡ΉPortugal lolgm

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024