utility.inc 1.9 KB

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