Skip to content

Commit

Permalink
More tries to detect the encoding + add the test
Browse files Browse the repository at this point in the history
  • Loading branch information
b1rdex committed Jul 10, 2020
1 parent 6ecb7fa commit 963c3e1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/DOMNodeComparator.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/
namespace SebastianBergmann\Comparator;

use DOMEntity;
use function sprintf;
use function strtolower;
use DOMDocument;
Expand Down Expand Up @@ -72,7 +73,8 @@ private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase)
if ($canonicalize) {
$document = new DOMDocument;
@$document->loadXML(
'<?xml version="1.0" encoding="' . ($node->ownerDocument->encoding ?: 'UTF-8') . '"?>' . \PHP_EOL
''
. '<?xml version="1.0" encoding="' . $this->getNodeEncoding($node) . '"?>' . \PHP_EOL
. $node->C14N()
);

Expand All @@ -88,4 +90,19 @@ 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';
}
}
26 changes: 26 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,24 @@ 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;
}

// should not happen
self::assertFalse(false);
}

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

0 comments on commit 963c3e1

Please sign in to comment.