You are here

public function AlinkPostRenderer::replace in Alinks 8

Load the content and replace the matched strings with automatic links.

File

src/AlinkPostRenderer.php, line 116

Class

AlinkPostRenderer
Class AlinkPostRenderer.

Namespace

Drupal\alinks

Code

public function replace() {
  $dom = Html::load($this->content);
  $xpath = new \DOMXPath($dom);
  $this->existingLinks = $this
    ->extractExistingLinks($xpath);
  $this->keywords = array_filter($this
    ->getKeywords(), function (Keyword $word) {
    return !isset($this->existingLinks[$word
      ->getUrl()]);
  });
  foreach ($xpath
    ->query($this->xpathSelector) as $node) {
    $text = $node->wholeText;
    $replace = FALSE;
    if (empty(trim($text))) {
      continue;
    }
    foreach ($this->keywords as $key => $word) {

      // @TODO: Make it configurable replaceAll vs. replaceFirst
      $text = $this
        ->replaceFirst($word, '<a href="' . $word
        ->getUrl() . '">' . $word
        ->getText() . '</a>', $text, $count);
      if ($count) {
        $replace = TRUE;
        $this
          ->addExistingLink($word);
        break;
      }
    }
    if ($replace) {
      $this
        ->replaceNodeContent($node, $text);
    }
  }
  return Html::serialize($dom);
}