ValueExporter.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\HttpKernel\DataCollector\Util;
  11. /**
  12. * @author Bernhard Schussek <bschussek@gmail.com>
  13. */
  14. class ValueExporter
  15. {
  16. /**
  17. * Converts a PHP value to a string.
  18. *
  19. * @param mixed $value The PHP value
  20. * @param int $depth Only for internal usage
  21. * @param bool $deep Only for internal usage
  22. *
  23. * @return string The string representation of the given value
  24. */
  25. public function exportValue($value, $depth = 1, $deep = false)
  26. {
  27. if ($value instanceof \__PHP_Incomplete_Class) {
  28. return sprintf('__PHP_Incomplete_Class(%s)', $this->getClassNameFromIncomplete($value));
  29. }
  30. if (\is_object($value)) {
  31. if ($value instanceof \DateTime || $value instanceof \DateTimeInterface) {
  32. return sprintf('Object(%s) - %s', \get_class($value), $value->format(\DateTime::ATOM));
  33. }
  34. return sprintf('Object(%s)', \get_class($value));
  35. }
  36. if (\is_array($value)) {
  37. if (empty($value)) {
  38. return '[]';
  39. }
  40. $indent = str_repeat(' ', $depth);
  41. $a = array();
  42. foreach ($value as $k => $v) {
  43. if (\is_array($v)) {
  44. $deep = true;
  45. }
  46. $a[] = sprintf('%s => %s', $k, $this->exportValue($v, $depth + 1, $deep));
  47. }
  48. if ($deep) {
  49. return sprintf("[\n%s%s\n%s]", $indent, implode(sprintf(", \n%s", $indent), $a), str_repeat(' ', $depth - 1));
  50. }
  51. return sprintf('[%s]', implode(', ', $a));
  52. }
  53. if (\is_resource($value)) {
  54. return sprintf('Resource(%s#%d)', get_resource_type($value), $value);
  55. }
  56. if (null === $value) {
  57. return 'null';
  58. }
  59. if (false === $value) {
  60. return 'false';
  61. }
  62. if (true === $value) {
  63. return 'true';
  64. }
  65. return (string) $value;
  66. }
  67. private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value)
  68. {
  69. $array = new \ArrayObject($value);
  70. return $array['__PHP_Incomplete_Class_Name'];
  71. }
  72. }