NodeDumper.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace PhpParser;
  3. class NodeDumper
  4. {
  5. private $dumpComments;
  6. /**
  7. * Constructs a NodeDumper.
  8. *
  9. * @param array $options Boolean option 'dumpComments' controls whether comments should be
  10. * dumped
  11. */
  12. public function __construct(array $options = []) {
  13. $this->dumpComments = !empty($options['dumpComments']);
  14. }
  15. /**
  16. * Dumps a node or array.
  17. *
  18. * @param array|Node $node Node or array to dump
  19. *
  20. * @return string Dumped value
  21. */
  22. public function dump($node) {
  23. if ($node instanceof Node) {
  24. $r = $node->getType() . '(';
  25. foreach ($node->getSubNodeNames() as $key) {
  26. $r .= "\n " . $key . ': ';
  27. $value = $node->$key;
  28. if (null === $value) {
  29. $r .= 'null';
  30. } elseif (false === $value) {
  31. $r .= 'false';
  32. } elseif (true === $value) {
  33. $r .= 'true';
  34. } elseif (is_scalar($value)) {
  35. $r .= $value;
  36. } else {
  37. $r .= str_replace("\n", "\n ", $this->dump($value));
  38. }
  39. }
  40. if ($this->dumpComments && $comments = $node->getAttribute('comments')) {
  41. $r .= "\n comments: " . str_replace("\n", "\n ", $this->dump($comments));
  42. }
  43. } elseif (is_array($node)) {
  44. $r = 'array(';
  45. foreach ($node as $key => $value) {
  46. $r .= "\n " . $key . ': ';
  47. if (null === $value) {
  48. $r .= 'null';
  49. } elseif (false === $value) {
  50. $r .= 'false';
  51. } elseif (true === $value) {
  52. $r .= 'true';
  53. } elseif (is_scalar($value)) {
  54. $r .= $value;
  55. } else {
  56. $r .= str_replace("\n", "\n ", $this->dump($value));
  57. }
  58. }
  59. } elseif ($node instanceof Comment) {
  60. return $node->getReformattedText();
  61. } else {
  62. throw new \InvalidArgumentException('Can only dump nodes and arrays.');
  63. }
  64. return $r . "\n)";
  65. }
  66. }