Exporter.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. <?php
  2. /*
  3. * This file is part of the exporter package.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\Exporter;
  11. use SebastianBergmann\RecursionContext\Context;
  12. /**
  13. * A nifty utility for visualizing PHP variables.
  14. *
  15. * <code>
  16. * <?php
  17. * use SebastianBergmann\Exporter\Exporter;
  18. *
  19. * $exporter = new Exporter;
  20. * print $exporter->export(new Exception);
  21. * </code>
  22. */
  23. class Exporter
  24. {
  25. /**
  26. * Exports a value as a string
  27. *
  28. * The output of this method is similar to the output of print_r(), but
  29. * improved in various aspects:
  30. *
  31. * - NULL is rendered as "null" (instead of "")
  32. * - TRUE is rendered as "true" (instead of "1")
  33. * - FALSE is rendered as "false" (instead of "")
  34. * - Strings are always quoted with single quotes
  35. * - Carriage returns and newlines are normalized to \n
  36. * - Recursion and repeated rendering is treated properly
  37. *
  38. * @param mixed $value
  39. * @param int $indentation The indentation level of the 2nd+ line
  40. *
  41. * @return string
  42. */
  43. public function export($value, $indentation = 0)
  44. {
  45. return $this->recursiveExport($value, $indentation);
  46. }
  47. /**
  48. * @param mixed $data
  49. * @param Context $context
  50. *
  51. * @return string
  52. */
  53. public function shortenedRecursiveExport(&$data, Context $context = null)
  54. {
  55. $result = [];
  56. $exporter = new self();
  57. if (!$context) {
  58. $context = new Context;
  59. }
  60. $array = $data;
  61. $context->add($data);
  62. foreach ($array as $key => $value) {
  63. if (is_array($value)) {
  64. if ($context->contains($data[$key]) !== false) {
  65. $result[] = '*RECURSION*';
  66. } else {
  67. $result[] = sprintf(
  68. 'array(%s)',
  69. $this->shortenedRecursiveExport($data[$key], $context)
  70. );
  71. }
  72. } else {
  73. $result[] = $exporter->shortenedExport($value);
  74. }
  75. }
  76. return implode(', ', $result);
  77. }
  78. /**
  79. * Exports a value into a single-line string
  80. *
  81. * The output of this method is similar to the output of
  82. * SebastianBergmann\Exporter\Exporter::export().
  83. *
  84. * Newlines are replaced by the visible string '\n'.
  85. * Contents of arrays and objects (if any) are replaced by '...'.
  86. *
  87. * @param mixed $value
  88. *
  89. * @return string
  90. *
  91. * @see SebastianBergmann\Exporter\Exporter::export
  92. */
  93. public function shortenedExport($value)
  94. {
  95. if (is_string($value)) {
  96. $string = str_replace("\n", '', $this->export($value));
  97. if (function_exists('mb_strlen')) {
  98. if (mb_strlen($string) > 40) {
  99. $string = mb_substr($string, 0, 30) . '...' . mb_substr($string, -7);
  100. }
  101. } else {
  102. if (strlen($string) > 40) {
  103. $string = substr($string, 0, 30) . '...' . substr($string, -7);
  104. }
  105. }
  106. return $string;
  107. }
  108. if (is_object($value)) {
  109. return sprintf(
  110. '%s Object (%s)',
  111. get_class($value),
  112. count($this->toArray($value)) > 0 ? '...' : ''
  113. );
  114. }
  115. if (is_array($value)) {
  116. return sprintf(
  117. 'Array (%s)',
  118. count($value) > 0 ? '...' : ''
  119. );
  120. }
  121. return $this->export($value);
  122. }
  123. /**
  124. * Converts an object to an array containing all of its private, protected
  125. * and public properties.
  126. *
  127. * @param mixed $value
  128. *
  129. * @return array
  130. */
  131. public function toArray($value)
  132. {
  133. if (!is_object($value)) {
  134. return (array) $value;
  135. }
  136. $array = [];
  137. foreach ((array) $value as $key => $val) {
  138. // properties are transformed to keys in the following way:
  139. // private $property => "\0Classname\0property"
  140. // protected $property => "\0*\0property"
  141. // public $property => "property"
  142. if (preg_match('/^\0.+\0(.+)$/', $key, $matches)) {
  143. $key = $matches[1];
  144. }
  145. // See https://github.com/php/php-src/commit/5721132
  146. if ($key === "\0gcdata") {
  147. continue;
  148. }
  149. $array[$key] = $val;
  150. }
  151. // Some internal classes like SplObjectStorage don't work with the
  152. // above (fast) mechanism nor with reflection in Zend.
  153. // Format the output similarly to print_r() in this case
  154. if ($value instanceof \SplObjectStorage) {
  155. // However, the fast method does work in HHVM, and exposes the
  156. // internal implementation. Hide it again.
  157. if (property_exists('\SplObjectStorage', '__storage')) {
  158. unset($array['__storage']);
  159. } elseif (property_exists('\SplObjectStorage', 'storage')) {
  160. unset($array['storage']);
  161. }
  162. if (property_exists('\SplObjectStorage', '__key')) {
  163. unset($array['__key']);
  164. }
  165. foreach ($value as $key => $val) {
  166. $array[spl_object_hash($val)] = [
  167. 'obj' => $val,
  168. 'inf' => $value->getInfo(),
  169. ];
  170. }
  171. }
  172. return $array;
  173. }
  174. /**
  175. * Recursive implementation of export
  176. *
  177. * @param mixed $value The value to export
  178. * @param int $indentation The indentation level of the 2nd+ line
  179. * @param \SebastianBergmann\RecursionContext\Context $processed Previously processed objects
  180. *
  181. * @return string
  182. *
  183. * @see SebastianBergmann\Exporter\Exporter::export
  184. */
  185. protected function recursiveExport(&$value, $indentation, $processed = null)
  186. {
  187. if ($value === null) {
  188. return 'null';
  189. }
  190. if ($value === true) {
  191. return 'true';
  192. }
  193. if ($value === false) {
  194. return 'false';
  195. }
  196. if (is_float($value) && floatval(intval($value)) === $value) {
  197. return "$value.0";
  198. }
  199. if (is_resource($value)) {
  200. return sprintf(
  201. 'resource(%d) of type (%s)',
  202. $value,
  203. get_resource_type($value)
  204. );
  205. }
  206. if (is_string($value)) {
  207. // Match for most non printable chars somewhat taking multibyte chars into account
  208. if (preg_match('/[^\x09-\x0d\x1b\x20-\xff]/', $value)) {
  209. return 'Binary String: 0x' . bin2hex($value);
  210. }
  211. return "'" .
  212. str_replace('<lf>', "\n",
  213. str_replace(
  214. ["\r\n", "\n\r", "\r", "\n"],
  215. ['\r\n<lf>', '\n\r<lf>', '\r<lf>', '\n<lf>'],
  216. $value
  217. )
  218. ) .
  219. "'";
  220. }
  221. $whitespace = str_repeat(' ', 4 * $indentation);
  222. if (!$processed) {
  223. $processed = new Context;
  224. }
  225. if (is_array($value)) {
  226. if (($key = $processed->contains($value)) !== false) {
  227. return 'Array &' . $key;
  228. }
  229. $array = $value;
  230. $key = $processed->add($value);
  231. $values = '';
  232. if (count($array) > 0) {
  233. foreach ($array as $k => $v) {
  234. $values .= sprintf(
  235. '%s %s => %s' . "\n",
  236. $whitespace,
  237. $this->recursiveExport($k, $indentation),
  238. $this->recursiveExport($value[$k], $indentation + 1, $processed)
  239. );
  240. }
  241. $values = "\n" . $values . $whitespace;
  242. }
  243. return sprintf('Array &%s (%s)', $key, $values);
  244. }
  245. if (is_object($value)) {
  246. $class = get_class($value);
  247. if ($hash = $processed->contains($value)) {
  248. return sprintf('%s Object &%s', $class, $hash);
  249. }
  250. $hash = $processed->add($value);
  251. $values = '';
  252. $array = $this->toArray($value);
  253. if (count($array) > 0) {
  254. foreach ($array as $k => $v) {
  255. $values .= sprintf(
  256. '%s %s => %s' . "\n",
  257. $whitespace,
  258. $this->recursiveExport($k, $indentation),
  259. $this->recursiveExport($v, $indentation + 1, $processed)
  260. );
  261. }
  262. $values = "\n" . $values . $whitespace;
  263. }
  264. return sprintf('%s Object &%s (%s)', $class, $hash, $values);
  265. }
  266. return var_export($value, true);
  267. }
  268. }