Exporter.php 9.8 KB

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