Exporter.php 9.6 KB

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