Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/XMLSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace TheSeer\Tokenizer;

use DOMDocument;
use XMLWriter;

class XMLSerializer {

Expand Down Expand Up @@ -32,7 +33,15 @@ public function toXML(TokenCollection $tokens): string {
$writer = new \XMLWriter();
$writer->openMemory();
$writer->setIndent(true);

$writer->startDocument();
$this->appendToWriter($writer, $tokens);
$writer->endDocument();

return $writer->outputMemory();
}

public function appendToWriter(XMLWriter $writer, TokenCollection $tokens): void {
Copy link
Contributor Author

@staabm staabm Nov 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

extracted the inner parts of toXML into a new separate method.

toXML itself did not change from a caller point of view

$writer->startElement('source');
$writer->writeAttribute('xmlns', $this->xmlns->asString());

Expand Down Expand Up @@ -67,8 +76,5 @@ public function toXML(TokenCollection $tokens): string {
}

$writer->endElement();
$writer->endDocument();

return $writer->outputMemory();
}
}
15 changes: 15 additions & 0 deletions tests/XMLSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,21 @@ public function testCanBeSerializedToXml(): void {
$this->assertEquals($expected, $serializer->toXML($this->tokens));
}

public function testCanAppendToWriter(): void {
$expected = \file_get_contents(__DIR__ . '/_files/test.php.xml');

$writer = new \XMLWriter();
$writer->openMemory();
$writer->setIndent(true);

$serializer = new XMLSerializer();
$writer->startDocument();
$serializer->appendToWriter($writer, $this->tokens);
$writer->endDocument();

$this->assertEquals($expected, $writer->outputMemory());
}

public function testCanBeSerializedToDomDocument(): void {
$serializer = new XMLSerializer();
$result = $serializer->toDom($this->tokens);
Expand Down