You are here

function linked_field_link_field in Linked Field 7

Recursive function for linking text parts and images in DOMNodes.

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.

1 call to linked_field_link_field()
linked_field_field_attach_view_alter in ./linked_field.module
Implements hook_field_attach_view_alter().

File

./linked_field.module, line 479
Main file of Linked Field module.

Code

function linked_field_link_field($node, $dom, $attributes) {

  // Some elements need the <a> as wrapper.
  $wrapped_elements = array(
    'img',
    'picture',
  );
  if ($node
    ->hasChildNodes() && $node->nodeName != 'a') {
    $c = $node->childNodes->length;
    for ($i = $c; $i > 0; --$i) {
      $child = $node->childNodes
        ->item($i - 1);
      if (in_array($child->nodeName, $wrapped_elements)) {

        // Create new <a> element, set the href and append the wrapped element.
        $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_entity_decode($value, ENT_QUOTES);
            $element
              ->setAttribute($name, $value);
          }
        }
        $node
          ->replaceChild($element, $child);
        $element
          ->appendChild($child);
      }
      else {
        linked_field_link_field($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_entity_decode($value, ENT_QUOTES);
                $element
                  ->setAttribute($name, $value);
              }
            }

            // Replace the the original element with the new one.
            $node
              ->replaceChild($element, $child);
          }
        }
      }
    }
  }
}