Mercurial > hg > cmmr2012-drupal-site
comparison vendor/theseer/tokenizer/src/XMLSerializer.php @ 2:5311817fb629
Theme updates
author | Chris Cannam |
---|---|
date | Tue, 10 Jul 2018 13:19:18 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
1:0b0e5f3b1e83 | 2:5311817fb629 |
---|---|
1 <?php declare(strict_types = 1); | |
2 namespace TheSeer\Tokenizer; | |
3 | |
4 use DOMDocument; | |
5 | |
6 class XMLSerializer { | |
7 | |
8 /** | |
9 * @var \XMLWriter | |
10 */ | |
11 private $writer; | |
12 | |
13 /** | |
14 * @var Token | |
15 */ | |
16 private $previousToken; | |
17 | |
18 /** | |
19 * @var NamespaceUri | |
20 */ | |
21 private $xmlns; | |
22 | |
23 /** | |
24 * XMLSerializer constructor. | |
25 * | |
26 * @param NamespaceUri $xmlns | |
27 */ | |
28 public function __construct(NamespaceUri $xmlns = null) { | |
29 if ($xmlns === null) { | |
30 $xmlns = new NamespaceUri('https://github.com/theseer/tokenizer'); | |
31 } | |
32 $this->xmlns = $xmlns; | |
33 } | |
34 | |
35 /** | |
36 * @param TokenCollection $tokens | |
37 * | |
38 * @return DOMDocument | |
39 */ | |
40 public function toDom(TokenCollection $tokens): DOMDocument { | |
41 $dom = new DOMDocument(); | |
42 $dom->preserveWhiteSpace = false; | |
43 $dom->loadXML($this->toXML($tokens)); | |
44 | |
45 return $dom; | |
46 } | |
47 | |
48 /** | |
49 * @param TokenCollection $tokens | |
50 * | |
51 * @return string | |
52 */ | |
53 public function toXML(TokenCollection $tokens): string { | |
54 $this->writer = new \XMLWriter(); | |
55 $this->writer->openMemory(); | |
56 $this->writer->setIndent(true); | |
57 $this->writer->startDocument(); | |
58 $this->writer->startElement('source'); | |
59 $this->writer->writeAttribute('xmlns', $this->xmlns->asString()); | |
60 $this->writer->startElement('line'); | |
61 $this->writer->writeAttribute('no', '1'); | |
62 | |
63 $this->previousToken = $tokens[0]; | |
64 foreach ($tokens as $token) { | |
65 $this->addToken($token); | |
66 } | |
67 | |
68 $this->writer->endElement(); | |
69 $this->writer->endElement(); | |
70 $this->writer->endDocument(); | |
71 | |
72 return $this->writer->outputMemory(); | |
73 } | |
74 | |
75 /** | |
76 * @param Token $token | |
77 */ | |
78 private function addToken(Token $token) { | |
79 if ($this->previousToken->getLine() < $token->getLine()) { | |
80 $this->writer->endElement(); | |
81 | |
82 $this->writer->startElement('line'); | |
83 $this->writer->writeAttribute('no', (string)$token->getLine()); | |
84 $this->previousToken = $token; | |
85 } | |
86 | |
87 if ($token->getValue() !== '') { | |
88 $this->writer->startElement('token'); | |
89 $this->writer->writeAttribute('name', $token->getName()); | |
90 $this->writer->writeRaw(htmlspecialchars($token->getValue(), ENT_NOQUOTES | ENT_DISALLOWED | ENT_XML1)); | |
91 $this->writer->endElement(); | |
92 } | |
93 } | |
94 } |