3 namespace Drupal\Component\Utility;
6 * Provides helpers for dealing with variables.
13 * Drupal-friendly var_export().
16 * The variable to export.
17 * @param string $prefix
18 * A prefix that will be added at the beginning of every lines of the output.
21 * The variable exported in a way compatible to Drupal's coding standards.
23 public static function export($var, $prefix = '') {
30 // Don't export keys if the array is non associative.
31 $export_keys = array_values($var) != $var;
32 foreach ($var as $key => $value) {
33 $output .= ' ' . ($export_keys ? static::export($key) . ' => ' : '') . static::export($value, ' ', FALSE) . ",\n";
38 elseif (is_bool($var)) {
39 $output = $var ? 'TRUE' : 'FALSE';
41 elseif (is_string($var)) {
42 if (strpos($var, "\n") !== FALSE || strpos($var, "'") !== FALSE) {
43 // If the string contains a line break or a single quote, use the
44 // double quote export mode. Encode backslash, dollar symbols, and
45 // double quotes and transform some common control characters.
46 $var = str_replace(['\\', '$', '"', "\n", "\r", "\t"], ['\\\\', '\$', '\"', '\n', '\r', '\t'], $var);
47 $output = '"' . $var . '"';
50 $output = "'" . $var . "'";
53 elseif (is_object($var) && get_class($var) === 'stdClass') {
54 // var_export() will export stdClass objects using an undefined
55 // magic method __set_state() leaving the export broken. This
56 // workaround avoids this by casting the object as an array for
57 // export and casting it back to an object when evaluated.
58 $output = '(object) ' . static::export((array) $var, $prefix);
61 $output = var_export($var, TRUE);
65 $output = str_replace("\n", "\n$prefix", $output);