utility.inc 1.9 KB

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