comparison core/lib/Drupal/Component/Utility/Variable.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 namespace Drupal\Component\Utility;
4
5 /**
6 * Provides helpers for dealing with variables.
7 *
8 * @ingroup utility
9 */
10 class Variable {
11
12 /**
13 * Drupal-friendly var_export().
14 *
15 * @param mixed $var
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.
19 *
20 * @return string
21 * The variable exported in a way compatible to Drupal's coding standards.
22 */
23 public static function export($var, $prefix = '') {
24 if (is_array($var)) {
25 if (empty($var)) {
26 $output = 'array()';
27 }
28 else {
29 $output = "array(\n";
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";
34 }
35 $output .= ')';
36 }
37 }
38 elseif (is_bool($var)) {
39 $output = $var ? 'TRUE' : 'FALSE';
40 }
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 . '"';
48 }
49 else {
50 $output = "'" . $var . "'";
51 }
52 }
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);
59 }
60 else {
61 $output = var_export($var, TRUE);
62 }
63
64 if ($prefix) {
65 $output = str_replace("\n", "\n$prefix", $output);
66 }
67
68 return $output;
69 }
70
71 }