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