You are here

public static function ConfigActionsTransform::replaceTree in Config Actions 8

Recursively string replace the values of an array.

Parameters

string|array $search: Optional search values for operating on BOTH keys and values

string|array $replace: Optional replace keys for operating on BOTH keys and values

array $data: Data to be altered

string|array $search_keys: Optional search values for operating on JUST keys

string|array $replace_keys: Optional replace keys for operating on JUST keys

Return value

array

1 call to ConfigActionsTransform::replaceTree()
ConfigActionsTransform::replace in src/ConfigActionsTransform.php
Replace tokens within yaml data and return the resulting array

File

src/ConfigActionsTransform.php, line 104

Class

ConfigActionsTransform
Perform transformations on data needed for config_actions plugins

Namespace

Drupal\config_actions

Code

public static function replaceTree($data, $search = '', $replace = '', $search_keys = '', $replace_keys = '') {
  if (!is_array($data)) {
    if (is_string($data)) {

      // Regular string replace.
      $matched = FALSE;

      // First check for exact variable matches.
      foreach ($search as $search_key => $search_value) {
        if ($search_value === $data) {

          // Replace exact match with the exact replacement value.
          // Fixes issue with integer vs string replacements.
          $data = $replace[$search_key];
          $matched = TRUE;
          break;
        }
      }
      if (!$matched) {

        // No exact match, so perform generic string replacements.
        $data = str_replace($search, $replace, $data);
      }
    }
    return $data;
  }
  $newArr = array();
  foreach ($data as $key => $value) {

    // Recurse
    if (!empty($search_keys)) {
      $key = str_replace($search_keys, $replace_keys, $key);
    }
    $newArr[$key] = static::replaceTree($value, $search, $replace, $search_keys, $replace_keys);
  }
  return $newArr;
}