You are here

public static function CustomFilterBaseFilter::applyRules in Custom filter 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Filter/CustomFilterBaseFilter.php \Drupal\customfilter\Plugin\Filter\CustomFilterBaseFilter::applyRules()

Replace the text using rules.

Parameters

array $matches: The text match by regular expression.

Return value

string The text after rules have beem apply.

File

src/Plugin/Filter/CustomFilterBaseFilter.php, line 91

Class

CustomFilterBaseFilter
Provides a base filter for Custom Filter.

Namespace

Drupal\customfilter\Plugin\Filter

Code

public static function applyRules(array $matches) {
  $globals =& static::getGlobals();
  $result = $matches[0];
  $rule = end($globals->stack);
  $code = $rule['code'];
  $pattern = $rule['pattern'];
  $replacement = $rule['replacement'];
  if (is_array($sub = $rule['sub']) && count($sub)) {
    foreach ($sub as $subrule) {
      if ($subrule['enabled']) {
        $globals->stack[] = $subrule;
        $substr =& $matches[$subrule['matches']];
        $substr = preg_replace_callback($subrule['pattern'], [
          CustomFilterBaseFilter::class,
          'applyRules',
        ], $substr);
        array_pop($globals->stack);
      }
    }
    if ($code) {
      CustomFilterBaseFilter::replaceCallback($replacement, TRUE);
      $result = CustomFilterBaseFilter::replaceCallback($matches);
    }
    else {
      $result = $replacement;
      $rmatches = array();
      $reps = array();
      preg_match_all('/([^\\\\]|^)(\\$([0-9]{1,2}|\\{([0-9]{1,2})\\}))/', $replacement, $rmatches, PREG_OFFSET_CAPTURE);
      foreach ($rmatches[4] as $key => $val) {
        if ($val == '') {
          $index = $rmatches[3][$key][0];
        }
        else {
          $index = $rmatches[4][$key][0];
        }
        $offset = $rmatches[2][$key][1];
        $length = strlen($rmatches[2][$key][0]);
        $reps[] = array(
          'index' => $index,
          'offset' => $offset,
          'length' => $length,
        );
      }
      krsort($reps);
      foreach ($reps as $rep) {
        $result = substr_replace($result, $matches[$rep['index']], $rep['offset'], $rep['length']);
      }
    }
  }
  elseif ($code) {
    CustomFilterBaseFilter::replaceCallback($replacement, TRUE);
    $result = preg_replace_callback($pattern, [
      CustomFilterBaseFilter::class,
      'replaceCallback',
    ], $result);
  }
  else {
    $result = preg_replace($pattern, $replacement, $result);
  }
  return $result;
}