XMLSerializer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php declare(strict_types = 1);
  2. namespace TheSeer\Tokenizer;
  3. use DOMDocument;
  4. class XMLSerializer {
  5. /** @var \XMLWriter */
  6. private $writer;
  7. /** @var Token */
  8. private $previousToken;
  9. /** @var NamespaceUri */
  10. private $xmlns;
  11. /**
  12. * XMLSerializer constructor.
  13. *
  14. * @param NamespaceUri $xmlns
  15. */
  16. public function __construct(NamespaceUri $xmlns = null) {
  17. if ($xmlns === null) {
  18. $xmlns = new NamespaceUri('https://github.com/theseer/tokenizer');
  19. }
  20. $this->xmlns = $xmlns;
  21. }
  22. public function toDom(TokenCollection $tokens): DOMDocument {
  23. $dom = new DOMDocument();
  24. $dom->preserveWhiteSpace = false;
  25. $dom->loadXML($this->toXML($tokens));
  26. return $dom;
  27. }
  28. public function toXML(TokenCollection $tokens): string {
  29. $this->writer = new \XMLWriter();
  30. $this->writer->openMemory();
  31. $this->writer->setIndent(true);
  32. $this->writer->startDocument();
  33. $this->writer->startElement('source');
  34. $this->writer->writeAttribute('xmlns', $this->xmlns->asString());
  35. if (\count($tokens) > 0) {
  36. $this->writer->startElement('line');
  37. $this->writer->writeAttribute('no', '1');
  38. $this->previousToken = $tokens[0];
  39. foreach ($tokens as $token) {
  40. $this->addToken($token);
  41. }
  42. }
  43. $this->writer->endElement();
  44. $this->writer->endElement();
  45. $this->writer->endDocument();
  46. return $this->writer->outputMemory();
  47. }
  48. private function addToken(Token $token): void {
  49. if ($this->previousToken->getLine() < $token->getLine()) {
  50. $this->writer->endElement();
  51. $this->writer->startElement('line');
  52. $this->writer->writeAttribute('no', (string)$token->getLine());
  53. $this->previousToken = $token;
  54. }
  55. if ($token->getValue() !== '') {
  56. $this->writer->startElement('token');
  57. $this->writer->writeAttribute('name', $token->getName());
  58. $this->writer->writeRaw(\htmlspecialchars($token->getValue(), \ENT_NOQUOTES | \ENT_DISALLOWED | \ENT_XML1));
  59. $this->writer->endElement();
  60. }
  61. }
  62. }