You are here

public function FilterOnomasticon::process in Onomasticon 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/Filter/FilterOnomasticon.php \Drupal\onomasticon\Plugin\Filter\FilterOnomasticon::process()

Main filter function as expected by Drupal.

Parameters

string $text:

string $langcode:

Return value

\Drupal\filter\FilterProcessResult|string

Overrides FilterInterface::process

File

src/Plugin/Filter/FilterOnomasticon.php, line 84

Class

FilterOnomasticon
Plugin annotation @Filter( id = "filter_onomasticon", title = @Translation("Onomasticon Filter"), description = @Translation("Adds glossary information to words."), type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE, settings…

Namespace

Drupal\onomasticon\Plugin\Filter

Code

public function process($text, $langcode) {

  // Check if a vocabulary has been set.
  if (empty($this->settings['onomasticon_vocabulary'])) {
    return $text;
  }

  // Load the description into an HTML5 DOMDocument.
  $html5 = new HTML5();
  $this->htmlDom = $html5
    ->loadHTML('<html><body>' . $text . '</body></html>');
  $this->htmlDom->preserveWhiteSpace = false;

  // Normalize in case HTMLCorrector has not been run.
  $this->htmlDom
    ->normalizeDocument();

  // Get the root element (<html>).
  $rootElement = $this->htmlDom->documentElement;

  // Get the body element (<body>).
  $body = $rootElement
    ->getElementsByTagName('body')
    ->item(0);

  // Walk the DOM and replace terms with definitions.
  $this
    ->processChildren($body);

  // Traversing finished, let's replace child nodes.
  foreach ($this->htmlReplacements as $r) {
    $domFragment = $this->htmlDom
      ->createDocumentFragment();

    // XML doesn't know some named entities like &nbsp;

    #$domFragment->appendXML(self::html_entities_normalize_xml($r['html']));

    #$r['dom']->parentNode->replaceChild($domFragment, $r['dom']);
    try {
      $bool = $domFragment
        ->appendXML(self::html_entities_normalize_xml($r['html']));
    } catch (Exception $e) {
      $bool = FALSE;
    }
    if ($bool) {
      $r['dom']->parentNode
        ->replaceChild($domFragment, $r['dom']);
    }
  }

  // Export all "body" childes as HTML 5.
  $text = '';
  foreach ($body->childNodes as $childNode) {
    $text .= $body->ownerDocument
      ->saveHTML($childNode);
  }

  // Prepare return object.
  $result = new FilterProcessResult($text);
  return $result;
}