Exporter.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of 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 int $indentation The indentation level of the 2nd+ line
  39. *
  40. * @return string
  41. */
  42. public function export($value, $indentation = 0)
  43. {
  44. return $this->recursiveExport($value, $indentation);
  45. }
  46. /**
  47. * @param array<mixed> $data
  48. * @param Context $context
  49. *
  50. * @return string
  51. */
  52. public function shortenedRecursiveExport(&$data, Context $context = null)
  53. {
  54. $result = [];
  55. $exporter = new self();
  56. if (!$context) {
  57. $context = new Context;
  58. }
  59. $array = $data;
  60. $context->add($data);
  61. foreach ($array as $key => $value) {
  62. if (\is_array($value)) {
  63. if ($context->contains($data[$key]) !== false) {
  64. $result[] = '*RECURSION*';
  65. } else {
  66. $result[] = \sprintf(
  67. 'array(%s)',
  68. $this->shortenedRecursiveExport($data[$key], $context)
  69. );
  70. }
  71. } else {
  72. $result[] = $exporter->shortenedExport($value);
  73. }
  74. }
  75. return \implode(', ', $result);
  76. }
  77. /**
  78. * Exports a value into a single-line string
  79. *
  80. * The output of this method is similar to the output of
  81. * SebastianBergmann\Exporter\Exporter::export().
  82. *
  83. * Newlines are replaced by the visible string '\n'.
  84. * Contents of arrays and objects (if any) are replaced by '...'.
  85. *
  86. * @return string
  87. *
  88. * @see SebastianBergmann\Exporter\Exporter::export
  89. */
  90. public function shortenedExport($value)
  91. {
  92. if (\is_string($value)) {
  93. $string = \str_replace("\n", '', $this->export($value));
  94. if (\function_exists('mb_strlen')) {
  95. if (\mb_strlen($string) > 40) {
  96. $string = \mb_substr($string, 0, 30) . '...' . \mb_substr($string, -7);
  97. }
  98. } else {
  99. if (\strlen($string) > 40) {
  100. $string = \substr($string, 0, 30) . '...' . \substr($string, -7);
  101. }
  102. }
  103. return $string;
  104. }
  105. if (\is_object($value)) {
  106. return \sprintf(
  107. '%s Object (%s)',
  108. \get_class($value),
  109. \count($this->toArray($value)) > 0 ? '...' : ''
  110. );
  111. }
  112. if (\is_array($value)) {
  113. return \sprintf(
  114. 'Array (%s)',
  115. \count($value) > 0 ? '...' : ''
  116. );
  117. }
  118. return $this->export($value);
  119. }
  120. /**
  121. * Converts an object to an array containing all of its private, protected
  122. * and public properties.
  123. *
  124. * @return array
  125. */
  126. public function toArray($value)
  127. {
  128. if (!\is_object($value)) {
  129. return (array) $value;
  130. }
  131. $array = [];
  132. foreach ((array) $value as $key => $val) {
  133. // Exception traces commonly reference hundreds to thousands of
  134. // objects currently loaded in memory. Including them in the result
  135. // has a severe negative performance impact.
  136. if ("\0Error\0trace" === $key || "\0Exception\0trace" === $key) {
  137. continue;
  138. }
  139. // properties are transformed to keys in the following way:
  140. // private $property => "\0Classname\0property"
  141. // protected $property => "\0*\0property"
  142. // public $property => "property"
  143. if (\preg_match('/^\0.+\0(.+)$/', (string) $key, $matches)) {
  144. $key = $matches[1];
  145. }
  146. // See https://github.com/php/php-src/commit/5721132
  147. if ($key === "\0gcdata") {
  148. continue;
  149. }
  150. $array[$key] = $val;
  151. }
  152. // Some internal classes like SplObjectStorage don't work with the
  153. // above (fast) mechanism nor with reflection in Zend.
  154. // Format the output similarly to print_r() in this case
  155. if ($value instanceof \SplObjectStorage) {
  156. foreach ($value as $key => $val) {
  157. $array[\spl_object_hash($val)] = [
  158. 'obj' => $val,
  159. 'inf' => $value->getInfo(),
  160. ];
  161. }
  162. }
  163. return $array;
  164. }
  165. /**
  166. * Recursive implementation of export
  167. *
  168. * @param mixed $value The value to export
  169. * @param int $indentation The indentation level of the 2nd+ line
  170. * @param \SebastianBergmann\RecursionContext\Context $processed Previously processed objects
  171. *
  172. * @return string
  173. *
  174. * @see SebastianBergmann\Exporter\Exporter::export
  175. */
  176. protected function recursiveExport(&$value, $indentation, $processed = null)
  177. {
  178. if ($value === null) {
  179. return 'null';
  180. }
  181. if ($value === true) {
  182. return 'true';
  183. }
  184. if ($value === false) {
  185. return 'false';
  186. }
  187. if (\is_float($value) && (float) ((int) $value) === $value) {
  188. return "$value.0";
  189. }
  190. if (\is_resource($value)) {
  191. return \sprintf(
  192. 'resource(%d) of type (%s)',
  193. $value,
  194. \get_resource_type($value)
  195. );
  196. }
  197. if (\is_string($value)) {
  198. // Match for most non printable chars somewhat taking multibyte chars into account
  199. if (\preg_match('/[^\x09-\x0d\x1b\x20-\xff]/', $value)) {
  200. return 'Binary String: 0x' . \bin2hex($value);
  201. }
  202. return "'" .
  203. \str_replace(
  204. '<lf>',
  205. "\n",
  206. \str_replace(
  207. ["\r\n", "\n\r", "\r", "\n"],
  208. ['\r\n<lf>', '\n\r<lf>', '\r<lf>', '\n<lf>'],
  209. $value
  210. )
  211. ) .
  212. "'";
  213. }
  214. $whitespace = \str_repeat(' ', (int)(4 * $indentation));
  215. if (!$processed) {
  216. $processed = new Context;
  217. }
  218. if (\is_array($value)) {
  219. if (($key = $processed->contains($value)) !== false) {
  220. return 'Array &' . $key;
  221. }
  222. $array = $value;
  223. $key = $processed->add($value);
  224. $values = '';
  225. if (\count($array) > 0) {
  226. foreach ($array as $k => $v) {
  227. $values .= \sprintf(
  228. '%s %s => %s' . "\n",
  229. $whitespace,
  230. $this->recursiveExport($k, $indentation),
  231. $this->recursiveExport($value[$k], $indentation + 1, $processed)
  232. );
  233. }
  234. $values = "\n" . $values . $whitespace;
  235. }
  236. return \sprintf('Array &%s (%s)', $key, $values);
  237. }
  238. if (\is_object($value)) {
  239. $class = \get_class($value);
  240. if ($hash = $processed->contains($value)) {
  241. return \sprintf('%s Object &%s', $class, $hash);
  242. }
  243. $hash = $processed->add($value);
  244. $values = '';
  245. $array = $this->toArray($value);
  246. if (\count($array) > 0) {
  247. foreach ($array as $k => $v) {
  248. $values .= \sprintf(
  249. '%s %s => %s' . "\n",
  250. $whitespace,
  251. $this->recursiveExport($k, $indentation),
  252. $this->recursiveExport($v, $indentation + 1, $processed)
  253. );
  254. }
  255. $values = "\n" . $values . $whitespace;
  256. }
  257. return \sprintf('%s Object &%s (%s)', $class, $hash, $values);
  258. }
  259. return \var_export($value, true);
  260. }
  261. }