You are here

public function LinkedFieldManager::linkNode in Linked Field 8

Link a DOM node.

Parameters

\DOMNode $node: An object which gets investigated.

\DOMDocument $dom: An object which represents an entire HTML or XML document.

array $attributes: An array containing element attributes.

Overrides LinkedFieldManagerInterface::linkNode

1 call to LinkedFieldManager::linkNode()
LinkedFieldManager::linkHtml in src/LinkedFieldManager.php
Link HTML code with set link attributes.

File

src/LinkedFieldManager.php, line 218

Class

LinkedFieldManager
Provides helper methods for client related functionalities.

Namespace

Drupal\linked_field

Code

public function linkNode(\DOMNode $node, \DOMDocument $dom, array $attributes) {
  if ($node
    ->hasChildNodes() && $node->nodeName != 'a') {
    $c = $node->childNodes->length;
    for ($i = $c; $i > 0; --$i) {
      $child = $node->childNodes
        ->item($i - 1);
      $this
        ->linkNode($child, $dom, $attributes);
      if ($child->nodeType == XML_TEXT_NODE) {
        $text = $child->textContent;
        if (strlen(trim($text))) {

          // Convert all applicable characters to HTML entities.
          $text = htmlentities($text, ENT_QUOTES, 'UTF-8');

          // Create new <a> element, set the text and the href attribute.
          $element = $dom
            ->createElement('a', $text);

          // Adding the attributes.
          foreach ($attributes as $name => $value) {
            if ($value) {

              // Convert all HTML entities back to
              // their applicable characters.
              $value = Html::decodeEntities($value);
              $element
                ->setAttribute($name, $value);
            }
          }

          // Replace the the original element with the new one.
          $node
            ->replaceChild($element, $child);
        }
      }
      elseif ($child->nodeName == 'img') {

        // Create new <a> element, set the href and append the image.
        $element = $dom
          ->createElement('a');

        // Adding the attributes.
        foreach ($attributes as $name => $value) {
          if ($value) {

            // Convert all HTML entities back to their applicable characters.
            $value = Html::decodeEntities($value);
            $element
              ->setAttribute($name, $value);
          }
        }
        $node
          ->replaceChild($element, $child);
        $element
          ->appendChild($child);
      }
    }
  }
}