Variable.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Provides helpers for dealing with variables.
  5. *
  6. * @ingroup utility
  7. */
  8. class Variable {
  9. /**
  10. * Drupal-friendly var_export().
  11. *
  12. * @param mixed $var
  13. * The variable to export.
  14. * @param string $prefix
  15. * A prefix that will be added at the beginning of every lines of the output.
  16. *
  17. * @return string
  18. * The variable exported in a way compatible to Drupal's coding standards.
  19. */
  20. public static function export($var, $prefix = '') {
  21. if (is_array($var)) {
  22. if (empty($var)) {
  23. $output = 'array()';
  24. }
  25. else {
  26. $output = "array(\n";
  27. // Don't export keys if the array is non associative.
  28. $export_keys = array_values($var) != $var;
  29. foreach ($var as $key => $value) {
  30. $output .= ' ' . ($export_keys ? static::export($key) . ' => ' : '') . static::export($value, ' ', FALSE) . ",\n";
  31. }
  32. $output .= ')';
  33. }
  34. }
  35. elseif (is_bool($var)) {
  36. $output = $var ? 'TRUE' : 'FALSE';
  37. }
  38. elseif (is_string($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, dollar symbols, and
  42. // double quotes and transform some common control characters.
  43. $var = str_replace(['\\', '$', '"', "\n", "\r", "\t"], ['\\\\', '\$', '\"', '\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) ' . static::export((array) $var, $prefix);
  56. }
  57. else {
  58. $output = var_export($var, TRUE);
  59. }
  60. if ($prefix) {
  61. $output = str_replace("\n", "\n$prefix", $output);
  62. }
  63. return $output;
  64. }
  65. }