The break statement in replace function prevents replacement of different keywords in same DOM node

Created on 18 September 2019, almost 5 years ago
Updated 1 February 2024, 5 months ago

I found that sometimes Keywords appearing in the same paragraph aren't replaced.

How to reproduce that? The easiest way is to stuff a paragraph with many different keywords (with different links).

Reason seems to be in function AlinkPostRenderer::replace():

    foreach ($xpath->query($this->xpathSelector) as $node) { # DOM NODE LOOP
      // ... snip ... //
      foreach ($this->keywords as $key => $word) { # KEYWORD LOOP

        // @TODO: Make it configurable replaceAll vs. replaceFirst
        $text = $this->replaceFirst($word, '<a href="' . $word->getUrl() . '" class="linked-by-alinks">' . $word->getText() . '</a>', $text, $count);
        if ($count) {
          $replace = TRUE;
          $this->addExistingLink($word);
          break; # THE BREAK IN QUESTION.
        }
      }
      if ($replace) {
        $this->replaceNodeContent($node, $text);
      }
    }

Why do we have a break in if ($count)? Doesn't this mean to leave the "keyword loop", ignoring all following keywords in that DOM node and so proceed with the next DOM node?

At the same time in AlinkPostRenderer::replaceFirst() we see following foreach loop:

      foreach ($terms as $original_term => $term) {
        if ($term === $search->stemmed_keyword) {
          $search_escaped = preg_quote($original_term, '/');
          $subject = preg_replace('/\b' . $search_escaped . '\b/u', '<a href="' . $search->getUrl() . '">' . $original_term . '</a>', $subject, 1, $count);
          # MISSING break ?
        }
      }

If there are multiple $terms matching the stemmed keyword, won't this replace the first occurrence of each term? Adding a break here will stop the loop and there after the first replacement, won't it?

πŸ› Bug report
Status

Fixed

Version

1.0

Component

Code

Created by

πŸ‡©πŸ‡ͺGermany osopolar πŸ‡©πŸ‡ͺ GER 🌐

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

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024