Skip to content

Commit

Permalink
Add xml declaration to force utf-8
Browse files Browse the repository at this point in the history
  • Loading branch information
b1rdex committed Jul 10, 2020
1 parent 988baa0 commit f6f39fd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/DOMNodeComparator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use function strtolower;
use DOMDocument;
use DOMNode;
use DOMEntity;

/**
* Compares DOMNode instances for equality.
Expand Down Expand Up @@ -71,7 +72,11 @@ private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase)
{
if ($canonicalize) {
$document = new DOMDocument;
@$document->loadXML($node->C14N());
@$document->loadXML(
''
. '<?xml version="1.0" encoding="' . $this->getNodeEncoding($node) . '"?>' . PHP_EOL
. $node->C14N()
);

$node = $document;
}
Expand All @@ -85,4 +90,20 @@ private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase)

return $ignoreCase ? strtolower($text) : $text;
}

/**
* Tries to get the encoding from DOMNode or falls back to UTF-8.
*/
private function getNodeEncoding(DOMNode $node): string
{
$encoding = '';

if ($node->ownerDocument) {
$encoding = $node->ownerDocument->xmlEncoding ?: $node->ownerDocument->encoding;
} elseif ($node instanceof DOMEntity) {
$encoding = $node->encoding;
}

return $encoding ?: 'UTF-8';
}
}
25 changes: 25 additions & 0 deletions tests/DOMNodeComparatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ public function assertEqualsSucceedsProvider()
$this->createDOMDocument("<a x='' a=''/>"),
$this->createDOMDocument("<a a='' x=''/>"),
],
[
$this->createDOMDocument('<root>Тест кириллицы</root>'),
$this->createDOMDocument('<root>Тест кириллицы</root>'),
],
[
$this->createDOMDocument('<root>Тест кириллицы</root>'),
$this->createDOMDocument('<root>&#x422;&#x435;&#x441;&#x442; &#x43A;&#x438;&#x440;&#x438;&#x43B;&#x43B;&#x438;&#x446;&#x44B;</root>'),
],
];
}

Expand Down Expand Up @@ -169,6 +177,23 @@ public function testAssertEqualsFails($expected, $actual): void
$this->comparator->assertEquals($expected, $actual);
}

public function testCyrillicText(): void
{
try {
$this->comparator->assertEquals(
$this->createDOMDocument('<root>Тест кириллицы</root>'),
$this->createDOMDocument('<root>Тест кириллицы 1</root>'),
);
} catch (ComparisonFailure $exception) {
self::assertStringContainsString('Тест кириллицы', $exception->getExpectedAsString());
self::assertStringContainsString('Тест кириллицы', $exception->getActualAsString());

return;
}

self::fail('Should not happen');
}

private function createDOMDocument($content)
{
$document = new DOMDocument;
Expand Down

0 comments on commit f6f39fd

Please sign in to comment.