You are here

public function TableAltrow::process in Table Alternate Rows 8

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/TableAltrow.php, line 23

Class

TableAltrow
Insert even and odd classes for tables via input filters to allow for proper zebra-style striping.

Namespace

Drupal\table_altrow\Plugin\Filter

Code

public function process($text, $langcode) {

  // The actual filtering is performed here. The supplied text should be
  // returned, once any necessary substitutions have taken place.
  // First, we have to parse the variable.
  $matches = [];
  $offset = 0;

  // Find a tbody.
  while (preg_match('!(<tbody ?.*>)!i', $text, $matches, PREG_OFFSET_CAPTURE, $offset)) {
    $offset = $matches[0][1];
    $count = 1;

    // While the tbody is still open.
    while (preg_match('!(<tr( ?.*)>)|(</tbody>)!i', $text, $matches, PREG_OFFSET_CAPTURE, $offset)) {

      // +1 so we don't match the same string.
      $offset = $matches[0][1] + 1;

      // Don't process tr's until we find a tbody.
      if ($matches[0][0] == '</tbody>') {
        break;
      }

      // Don't replace existing classes. Perhaps this should append a class instead?
      if (!strstr($matches[2][0], 'class=')) {
        if ($count % 2 == 0) {
          $new_tag = '<tr class="even"' . $matches[2][0] . '>';
          $text = table_altrow_str_replace_count($matches[0][0], $new_tag, $text, $offset - 1, 1);
        }
        else {
          $new_tag = '<tr class="odd"' . $matches[2][0] . '>';
          $text = table_altrow_str_replace_count($matches[0][0], $new_tag, $text, $offset - 1, 1);
        }
      }
      $count++;
    }
  }
  return new FilterProcessResult($text);
}