You are here

function coder_replace_indent_multiline_array in Coder 6.2

Same name and namespace in other branches
  1. 5.2 scripts/coder_format/coder_format.inc \coder_replace_indent_multiline_array()
  2. 6 scripts/coder_format/coder_format.inc \coder_replace_indent_multiline_array()

Related topics

File

scripts/coder_format/coder_format.inc, line 1306
Coder format helper functions.

Code

function coder_replace_indent_multiline_array($matches) {

  // Separate out important components of the multiline array:
  // (\s*) matches existing indent as \1
  // (([\'"]).+?\2|\$.+?|[+\-]?(?:0x)?[0-9A-F]+) matches key as \2
  //    ([\'"]).+?\3 matches a quoted key, quote used is \3
  //    \.+? matches anything else
  // \),\s*? matches a closing parenthesis in a nested array
  // \s*=>\s* matches existing indentation and arrow to be discarded
  // (.+?) matches value as \4
  // {3,} requires three or more of these lines
  // mi enables multiline and caseless mode
  preg_match_all('/^(\\s*)(?:(([\'"]).+?\\3|\\.+?)\\s*=>\\s*(.+?),?|\\),)\\s*?$/mi', $matches[0], $vars, PREG_SET_ORDER);

  // Determine max key length for varying indentations.
  $maxlengths = array();
  foreach ($vars as $var) {
    list(, $indent, $key) = $var;
    if (!isset($maxlengths[$indent])) {
      $maxlengths[$indent] = 0;
    }
    if (($t = strlen($key)) > $maxlengths[$indent]) {
      $maxlengths[$indent] = $t;
    }
  }

  // Reconstruct variable array declaration.
  $return = '';
  foreach ($vars as $var) {
    list(, $indent, $key, , $value) = $var;
    if ($key === NULL) {
      $return .= "{$indent}),\n";
      continue;
    }
    $spaces = str_repeat(' ', $maxlengths[$indent] - strlen($key));
    if ($value !== 'array(') {
      $comma = ',';
    }
    else {
      $comma = '';
    }
    $return .= "{$indent}{$key}{$spaces} => {$value}{$comma}\n";
  }
  $return = rtrim($return, "\n");
  return $return;
}