You are here

public function GeshiFilterFilter::process in GeSHi Filter for syntax highlighting 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Filter/GeshiFilterFilter.php \Drupal\geshifilter\Plugin\Filter\GeshiFilterFilter::process()

Performs the filter processing.

Parameters

string $text: The text string to be filtered.

string $langcode: The language code of the text to be filtered.

Return value

\Drupal\filter\FilterProcessResult The filtered text, wrapped in a FilterProcessResult object, and possibly with associated assets, cacheability metadata and placeholders.

Overrides FilterInterface::process

See also

\Drupal\filter\FilterProcessResult

File

src/Plugin/Filter/GeshiFilterFilter.php, line 76

Class

GeshiFilterFilter
Provides a base filter for Geshi Filter.

Namespace

Drupal\geshifilter\Plugin\Filter

Code

public function process($text, $langcode) {
  $result = new FilterProcessResult($text);
  try {

    // Load GeSHi library (if not already).
    $geshi_library = GeshiFilter::loadGeshi();
    if (!$geshi_library['loaded']) {
      throw new \Exception($geshi_library['error message']);
    }

    // Get the available tags.
    list($generic_code_tags, $language_tags, $tag_to_lang) = $this
      ->getTags();
    if (in_array(GeshiFilter::BRACKETS_PHPBLOCK, array_filter($this
      ->tagStyles()))) {
      $language_tags[] = 'questionmarkphp';
      $tag_to_lang['questionmarkphp'] = 'php';
    }
    $tags = array_merge($generic_code_tags, $language_tags);

    // Escape special (regular expression) characters in tags (for tags like
    // 'c++' and 'c#').
    $tags = preg_replace('#(\\+|\\#)#', '\\\\$1', $tags);
    $tags_string = implode('|', $tags);

    // Pattern for matching the prepared "<code>...</code>" stuff.
    $pattern = '#\\[geshifilter-(' . $tags_string . ')([^\\]]*)\\](.*?)(\\[/geshifilter-\\1\\])#s';
    $text = preg_replace_callback($pattern, [
      $this,
      'replaceCallback',
    ], $text);

    // Create the object with result.
    $result = new FilterProcessResult($text);

    // Add the css file when necessary.
    if (in_array($this->config
      ->get('css_mode'), [
      GeshiFilter::CSS_CLASSES_AUTOMATIC,
      GeshiFilter::CSS_INLINE,
    ])) {
      $result
        ->setAttachments([
        'library' => [
          'geshifilter/geshifilter',
        ],
      ]);
    }

    // Add cache tags, so we can re-create the node when some geshifilter
    // settings change.
    $cache_tags = [
      'geshifilter',
    ];
    $result
      ->addCacheTags($cache_tags);
  } catch (\Exception $e) {
    watchdog_exception('geshifilter', $e);
    drupal_set_message($geshi_library['error message'], 'error');
  }
  return $result;
}