You are here

function _variable_clean_code_get_variables in Variable Cleanup 6

Same name and namespace in other branches
  1. 7 variable_clean.module \_variable_clean_code_get_variables()

Reduce a list of code into a list of variables, both static and dynamic.

Parameters

array $code_lines:

Return value

mixed Array of three arrays: 'static_variables', 'dyamic_variables', and 'non_processable_variables'.

2 calls to _variable_clean_code_get_variables()
variableCleanWebTestCase::testVariableClean in ./variable_clean.test
Test our variations.
variable_clean_form in ./variable_clean.module
Form builder for variable cleanup.

File

./variable_clean.module, line 189
Allows you to remove variables not currently used.

Code

function _variable_clean_code_get_variables($code_lines) {
  $static_variables = $dynamic_variables = $non_processable_variables = array();
  foreach ($code_lines as $line) {

    // Skip stuff in SVN.
    // @todo This could be done when we grep, but would require also using find.
    if (strpos($line, DIRECTORY_SEPARATOR . '.svn' . DIRECTORY_SEPARATOR) !== FALSE) {
      continue;
    }

    // Extract the variable name.
    $matches = array();
    if (preg_match_all('!variable_[g,s]et\\(([^\',"]*?[\',"](.+?)[\',"].*?),!', $line, $matches, PREG_SET_ORDER)) {
      foreach ($matches as $match) {

        // $match[1] is what is between ( and ,
        // $match[2] is what is enclosed in the first set of quotes
        $cleaned_match_1 = str_replace(array(
          '"',
          "'",
        ), '', $match[1]);

        // Test for really twisted syntax that we aren't going to even try to deal with.
        // ex. "foo_{$bar['baz']}"
        if (preg_match('![\',"][^\',"]*?{[^\',"]*?\\[!', $match[1])) {
          $non_processable_variables[] = $line;
        }
        elseif ($match[2] != $cleaned_match_1) {

          // If static portion is not at the beginning, we are screwed.
          if (strpos($cleaned_match_1, $match[2]) !== 0 || !$match[2]) {
            $non_processable_variables[] = $line;
          }
          else {
            $dynamic_variables[$match[2]] = $match[2];
          }
        }
        elseif (($dollar_position = strpos($match[2], '$')) !== FALSE) {

          // If the dollar is in position 0 we are screwed.
          if ($dollar_position === 0) {
            $non_processable_variables[] = $line;
          }
          else {
            $variable = str_replace('{', '', substr($match[2], 0, $dollar_position));
            if ($variable) {
              $dynamic_variables[$variable] = $variable;
            }
            else {
              $non_processable_variables[] = $line;
            }
          }
        }
        else {
          $static_variables[$match[2]] = $match[2];
        }
      }
    }
  }
  return array(
    'static_variables' => $static_variables,
    'dynamic_variables' => $dynamic_variables,
    'non_processable_variables' => $non_processable_variables,
  );
}