You are here

public static function RequestTree::replaceAllOccurrences in Subrequests 8

Do in-place replacements for an input string containing replacement tokens.

Parameters

array $responses: The pool of responses where to find the replacement data.

string $input: The string containing the token to replace. It's passed by reference and modified if necessary.

Return value

int The number of replacements made.

1 call to RequestTree::replaceAllOccurrences()
RequestTree::dereference in src/Blueprint/RequestTree.php
Resolves the JSON Pointer references.

File

src/Blueprint/RequestTree.php, line 218

Class

RequestTree
Contains the hierarchical information of the requests.

Namespace

Drupal\subrequests\Blueprint

Code

public static function replaceAllOccurrences(array $responses, &$input) {
  if (is_array($input)) {
    $changes = 0;

    // Apply the replacement recursively on the array keys and values.
    foreach ($input as $key => $value) {
      $new_key = $key;
      $local_changes = static::replaceAllOccurrences($responses, $new_key);
      $local_changes += static::replaceAllOccurrences($responses, $value);
      $changes += $local_changes;
      if ($local_changes) {
        unset($input[$key]);
        $input[$new_key] = $value;
      }
    }
    return $changes;
  }

  // Detect {{/foo#/bar}}
  $pattern = '/\\{\\{\\/([^\\{\\}]+)@(\\/[^\\{\\}]+)\\}\\}/';
  $matches = [];
  if (!preg_match_all($pattern, $input, $matches)) {
    return 0;
  }
  for ($index = 0; $index < count($matches[1]); $index++) {
    $replacement = static::findReplacement($responses, $matches[1][$index], $matches[2][$index]);
    $pattern = sprintf('/%s/', preg_quote($matches[0][$index], '/'));
    $input = preg_replace($pattern, $replacement, $input);
  }
  return $index;
}