Projet

Général

Profil

Paste
Télécharger (1,94 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / utility.inc @ bfb52287

1
<?php
2

    
3
/**
4
 * @file
5
 * Miscellaneous functions.
6
 */
7

    
8
/**
9
 * Drupal-friendly var_export().
10
 *
11
 * @param $var
12
 *   The variable to export.
13
 * @param $prefix
14
 *   A prefix that will be added at the beginning of every lines of the output.
15
 *
16
 * @return
17
 *   The variable exported in a way compatible to Drupal's coding standards.
18
 */
19
function drupal_var_export($var, $prefix = '') {
20
  if (is_array($var)) {
21
    if (empty($var)) {
22
      $output = 'array()';
23
    }
24
    else {
25
      $output = "array(\n";
26
      // Don't export keys if the array is non associative.
27
      $export_keys = array_values($var) != $var;
28
      foreach ($var as $key => $value) {
29
        $output .= '  ' . ($export_keys ? drupal_var_export($key) . ' => ' : '') . drupal_var_export($value, '  ', FALSE) . ",\n";
30
      }
31
      $output .= ')';
32
    }
33
  }
34
  elseif (is_bool($var)) {
35
    $output = $var ? 'TRUE' : 'FALSE';
36
  }
37
  elseif (is_string($var)) {
38
    $line_safe_var = str_replace("\n", '\n', $var);
39
    if (strpos($var, "\n") !== FALSE || strpos($var, "'") !== FALSE) {
40
      // If the string contains a line break or a single quote, use the
41
      // double quote export mode. Encode backslash and double quotes and
42
      // transform some common control characters.
43
      $var = str_replace(array('\\', '"', "\n", "\r", "\t"), array('\\\\', '\"', '\n', '\r', '\t'), $var);
44
      $output = '"' . $var . '"';
45
    }
46
    else {
47
      $output = "'" . $var . "'";
48
    }
49
  }
50
  elseif (is_object($var) && get_class($var) === 'stdClass') {
51
    // var_export() will export stdClass objects using an undefined
52
    // magic method __set_state() leaving the export broken. This
53
    // workaround avoids this by casting the object as an array for
54
    // export and casting it back to an object when evaluated.
55
    $output = '(object) ' . drupal_var_export((array) $var, $prefix);
56
  }
57
  else {
58
    $output = var_export($var, TRUE);
59
  }
60

    
61
  if ($prefix) {
62
    $output = str_replace("\n", "\n$prefix", $output);
63
  }
64

    
65
  return $output;
66
}