XML.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. class PHPParser_Serializer_XML implements PHPParser_Serializer
  3. {
  4. protected $writer;
  5. /**
  6. * Constructs a XML serializer.
  7. */
  8. public function __construct() {
  9. $this->writer = new XMLWriter;
  10. $this->writer->openMemory();
  11. $this->writer->setIndent(true);
  12. }
  13. public function serialize(array $nodes) {
  14. $this->writer->flush();
  15. $this->writer->startDocument('1.0', 'UTF-8');
  16. $this->writer->startElement('AST');
  17. $this->writer->writeAttribute('xmlns:node', 'http://nikic.github.com/PHPParser/XML/node');
  18. $this->writer->writeAttribute('xmlns:subNode', 'http://nikic.github.com/PHPParser/XML/subNode');
  19. $this->writer->writeAttribute('xmlns:attribute', 'http://nikic.github.com/PHPParser/XML/attribute');
  20. $this->writer->writeAttribute('xmlns:scalar', 'http://nikic.github.com/PHPParser/XML/scalar');
  21. $this->_serialize($nodes);
  22. $this->writer->endElement();
  23. return $this->writer->outputMemory();
  24. }
  25. protected function _serialize($node) {
  26. if ($node instanceof PHPParser_Node) {
  27. $this->writer->startElement('node:' . $node->getType());
  28. foreach ($node->getAttributes() as $name => $value) {
  29. $this->writer->startElement('attribute:' . $name);
  30. $this->_serialize($value);
  31. $this->writer->endElement();
  32. }
  33. foreach ($node as $name => $subNode) {
  34. $this->writer->startElement('subNode:' . $name);
  35. $this->_serialize($subNode);
  36. $this->writer->endElement();
  37. }
  38. $this->writer->endElement();
  39. } elseif ($node instanceof PHPParser_Comment) {
  40. $this->writer->startElement('comment');
  41. $this->writer->writeAttribute('isDocComment', $node instanceof PHPParser_Comment_Doc ? 'true' : 'false');
  42. $this->writer->writeAttribute('line', $node->getLine());
  43. $this->writer->text($node->getText());
  44. $this->writer->endElement();
  45. } elseif (is_array($node)) {
  46. $this->writer->startElement('scalar:array');
  47. foreach ($node as $subNode) {
  48. $this->_serialize($subNode);
  49. }
  50. $this->writer->endElement();
  51. } elseif (is_string($node)) {
  52. $this->writer->writeElement('scalar:string', $node);
  53. } elseif (is_int($node)) {
  54. $this->writer->writeElement('scalar:int', $node);
  55. } elseif (is_float($node)) {
  56. $this->writer->writeElement('scalar:float', $node);
  57. } elseif (true === $node) {
  58. $this->writer->writeElement('scalar:true');
  59. } elseif (false === $node) {
  60. $this->writer->writeElement('scalar:false');
  61. } elseif (null === $node) {
  62. $this->writer->writeElement('scalar:null');
  63. } else {
  64. throw new InvalidArgumentException('Unexpected node type');
  65. }
  66. }
  67. }