Exporter.php 8.8 KB

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