Skip to content

Commit 11336f6

Browse files
committed
Ensure XMLSerializer can deal with empty token collections
1 parent 1c42705 commit 11336f6

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

src/XMLSerializer.php

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,15 @@ public function toXML(TokenCollection $tokens): string {
5757
$this->writer->startDocument();
5858
$this->writer->startElement('source');
5959
$this->writer->writeAttribute('xmlns', $this->xmlns->asString());
60-
$this->writer->startElement('line');
61-
$this->writer->writeAttribute('no', '1');
6260

63-
$this->previousToken = $tokens[0];
64-
foreach ($tokens as $token) {
65-
$this->addToken($token);
61+
if (count($tokens) > 0) {
62+
$this->writer->startElement('line');
63+
$this->writer->writeAttribute('no', '1');
64+
65+
$this->previousToken = $tokens[0];
66+
foreach ($tokens as $token) {
67+
$this->addToken($token);
68+
}
6669
}
6770

6871
$this->writer->endElement();

tests/XMLSerializerTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,11 @@ public function testCanBeSerializedToXmlWithCustomNamespace() {
4040
$this->assertEquals($expected, $serializer->toXML($this->tokens));
4141
}
4242

43+
public function testEmptyCollectionCreatesEmptyDocument() {
44+
$expected = file_get_contents(__DIR__ . '/_files/empty.xml');
45+
46+
$serializer = new XMLSerializer();
47+
$this->assertEquals($expected, $serializer->toXML((new TokenCollection())));
48+
}
49+
4350
}

tests/_files/empty.xml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<?xml version="1.0"?>
2+
<source xmlns="https://github.com/theseer/tokenizer"/>

0 commit comments

Comments
 (0)