BaseVarDumper.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use yii\base\Arrayable;
  9. use yii\base\InvalidValueException;
  10. /**
  11. * BaseVarDumper provides concrete implementation for [[VarDumper]].
  12. *
  13. * Do not use BaseVarDumper. Use [[VarDumper]] instead.
  14. *
  15. * @author Qiang Xue <qiang.xue@gmail.com>
  16. * @since 2.0
  17. */
  18. class BaseVarDumper
  19. {
  20. private static $_objects;
  21. private static $_output;
  22. private static $_depth;
  23. /**
  24. * Displays a variable.
  25. * This method achieves the similar functionality as var_dump and print_r
  26. * but is more robust when handling complex objects such as Yii controllers.
  27. * @param mixed $var variable to be dumped
  28. * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
  29. * @param bool $highlight whether the result should be syntax-highlighted
  30. */
  31. public static function dump($var, $depth = 10, $highlight = false)
  32. {
  33. echo static::dumpAsString($var, $depth, $highlight);
  34. }
  35. /**
  36. * Dumps a variable in terms of a string.
  37. * This method achieves the similar functionality as var_dump and print_r
  38. * but is more robust when handling complex objects such as Yii controllers.
  39. * @param mixed $var variable to be dumped
  40. * @param int $depth maximum depth that the dumper should go into the variable. Defaults to 10.
  41. * @param bool $highlight whether the result should be syntax-highlighted
  42. * @return string the string representation of the variable
  43. */
  44. public static function dumpAsString($var, $depth = 10, $highlight = false)
  45. {
  46. self::$_output = '';
  47. self::$_objects = [];
  48. self::$_depth = $depth;
  49. self::dumpInternal($var, 0);
  50. if ($highlight) {
  51. $result = highlight_string("<?php\n" . self::$_output, true);
  52. self::$_output = preg_replace('/&lt;\\?php<br \\/>/', '', $result, 1);
  53. }
  54. return self::$_output;
  55. }
  56. /**
  57. * @param mixed $var variable to be dumped
  58. * @param int $level depth level
  59. */
  60. private static function dumpInternal($var, $level)
  61. {
  62. switch (gettype($var)) {
  63. case 'boolean':
  64. self::$_output .= $var ? 'true' : 'false';
  65. break;
  66. case 'integer':
  67. self::$_output .= (string)$var;
  68. break;
  69. case 'double':
  70. self::$_output .= (string)$var;
  71. break;
  72. case 'string':
  73. self::$_output .= "'" . addslashes($var) . "'";
  74. break;
  75. case 'resource':
  76. self::$_output .= '{resource}';
  77. break;
  78. case 'NULL':
  79. self::$_output .= 'null';
  80. break;
  81. case 'unknown type':
  82. self::$_output .= '{unknown}';
  83. break;
  84. case 'array':
  85. if (self::$_depth <= $level) {
  86. self::$_output .= '[...]';
  87. } elseif (empty($var)) {
  88. self::$_output .= '[]';
  89. } else {
  90. $keys = array_keys($var);
  91. $spaces = str_repeat(' ', $level * 4);
  92. self::$_output .= '[';
  93. foreach ($keys as $key) {
  94. self::$_output .= "\n" . $spaces . ' ';
  95. self::dumpInternal($key, 0);
  96. self::$_output .= ' => ';
  97. self::dumpInternal($var[$key], $level + 1);
  98. }
  99. self::$_output .= "\n" . $spaces . ']';
  100. }
  101. break;
  102. case 'object':
  103. if (($id = array_search($var, self::$_objects, true)) !== false) {
  104. self::$_output .= get_class($var) . '#' . ($id + 1) . '(...)';
  105. } elseif (self::$_depth <= $level) {
  106. self::$_output .= get_class($var) . '(...)';
  107. } else {
  108. $id = array_push(self::$_objects, $var);
  109. $className = get_class($var);
  110. $spaces = str_repeat(' ', $level * 4);
  111. self::$_output .= "$className#$id\n" . $spaces . '(';
  112. if ('__PHP_Incomplete_Class' !== get_class($var) && method_exists($var, '__debugInfo')) {
  113. $dumpValues = $var->__debugInfo();
  114. if (!is_array($dumpValues)) {
  115. throw new InvalidValueException('__debuginfo() must return an array');
  116. }
  117. } else {
  118. $dumpValues = (array) $var;
  119. }
  120. foreach ($dumpValues as $key => $value) {
  121. $keyDisplay = strtr(trim($key), "\0", ':');
  122. self::$_output .= "\n" . $spaces . " [$keyDisplay] => ";
  123. self::dumpInternal($value, $level + 1);
  124. }
  125. self::$_output .= "\n" . $spaces . ')';
  126. }
  127. break;
  128. }
  129. }
  130. /**
  131. * Exports a variable as a string representation.
  132. *
  133. * The string is a valid PHP expression that can be evaluated by PHP parser
  134. * and the evaluation result will give back the variable value.
  135. *
  136. * This method is similar to `var_export()`. The main difference is that
  137. * it generates more compact string representation using short array syntax.
  138. *
  139. * It also handles objects by using the PHP functions serialize() and unserialize().
  140. *
  141. * PHP 5.4 or above is required to parse the exported value.
  142. *
  143. * @param mixed $var the variable to be exported.
  144. * @return string a string representation of the variable
  145. */
  146. public static function export($var)
  147. {
  148. self::$_output = '';
  149. self::exportInternal($var, 0);
  150. return self::$_output;
  151. }
  152. /**
  153. * @param mixed $var variable to be exported
  154. * @param int $level depth level
  155. */
  156. private static function exportInternal($var, $level)
  157. {
  158. switch (gettype($var)) {
  159. case 'NULL':
  160. self::$_output .= 'null';
  161. break;
  162. case 'array':
  163. if (empty($var)) {
  164. self::$_output .= '[]';
  165. } else {
  166. $keys = array_keys($var);
  167. $outputKeys = ($keys !== range(0, count($var) - 1));
  168. $spaces = str_repeat(' ', $level * 4);
  169. self::$_output .= '[';
  170. foreach ($keys as $key) {
  171. self::$_output .= "\n" . $spaces . ' ';
  172. if ($outputKeys) {
  173. self::exportInternal($key, 0);
  174. self::$_output .= ' => ';
  175. }
  176. self::exportInternal($var[$key], $level + 1);
  177. self::$_output .= ',';
  178. }
  179. self::$_output .= "\n" . $spaces . ']';
  180. }
  181. break;
  182. case 'object':
  183. if ($var instanceof \Closure) {
  184. self::$_output .= self::exportClosure($var);
  185. } else {
  186. try {
  187. $output = 'unserialize(' . var_export(serialize($var), true) . ')';
  188. } catch (\Exception $e) {
  189. // serialize may fail, for example: if object contains a `\Closure` instance
  190. // so we use a fallback
  191. if ($var instanceof Arrayable) {
  192. self::exportInternal($var->toArray(), $level);
  193. return;
  194. } elseif ($var instanceof \IteratorAggregate) {
  195. $varAsArray = [];
  196. foreach ($var as $key => $value) {
  197. $varAsArray[$key] = $value;
  198. }
  199. self::exportInternal($varAsArray, $level);
  200. return;
  201. } elseif ('__PHP_Incomplete_Class' !== get_class($var) && method_exists($var, '__toString')) {
  202. $output = var_export($var->__toString(), true);
  203. } else {
  204. $outputBackup = self::$_output;
  205. $output = var_export(self::dumpAsString($var), true);
  206. self::$_output = $outputBackup;
  207. }
  208. }
  209. self::$_output .= $output;
  210. }
  211. break;
  212. default:
  213. self::$_output .= var_export($var, true);
  214. }
  215. }
  216. /**
  217. * Exports a [[Closure]] instance.
  218. * @param \Closure $closure closure instance.
  219. * @return string
  220. */
  221. private static function exportClosure(\Closure $closure)
  222. {
  223. $reflection = new \ReflectionFunction($closure);
  224. $fileName = $reflection->getFileName();
  225. $start = $reflection->getStartLine();
  226. $end = $reflection->getEndLine();
  227. if ($fileName === false || $start === false || $end === false) {
  228. return 'function() {/* Error: unable to determine Closure source */}';
  229. }
  230. --$start;
  231. $source = implode("\n", array_slice(file($fileName), $start, $end - $start));
  232. $tokens = token_get_all('<?php ' . $source);
  233. array_shift($tokens);
  234. $closureTokens = [];
  235. $pendingParenthesisCount = 0;
  236. foreach ($tokens as $token) {
  237. if (isset($token[0]) && $token[0] === T_FUNCTION) {
  238. $closureTokens[] = $token[1];
  239. continue;
  240. }
  241. if ($closureTokens !== []) {
  242. $closureTokens[] = isset($token[1]) ? $token[1] : $token;
  243. if ($token === '}') {
  244. $pendingParenthesisCount--;
  245. if ($pendingParenthesisCount === 0) {
  246. break;
  247. }
  248. } elseif ($token === '{') {
  249. $pendingParenthesisCount++;
  250. }
  251. }
  252. }
  253. return implode('', $closureTokens);
  254. }
  255. }