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