From 963c3e1abac4a39733d75059e1dc36813e861387 Mon Sep 17 00:00:00 2001 From: Anatoly Pashin Date: Fri, 10 Jul 2020 18:09:23 +1000 Subject: [PATCH] More tries to detect the encoding + add the test --- src/DOMNodeComparator.php | 19 ++++++++++++++++++- tests/DOMNodeComparatorTest.php | 26 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/DOMNodeComparator.php b/src/DOMNodeComparator.php index ae5da1d..a6c9155 100644 --- a/src/DOMNodeComparator.php +++ b/src/DOMNodeComparator.php @@ -9,6 +9,7 @@ */ namespace SebastianBergmann\Comparator; +use DOMEntity; use function sprintf; use function strtolower; use DOMDocument; @@ -72,7 +73,8 @@ private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase) if ($canonicalize) { $document = new DOMDocument; @$document->loadXML( - 'ownerDocument->encoding ?: 'UTF-8') . '"?>' . \PHP_EOL + '' + . 'getNodeEncoding($node) . '"?>' . \PHP_EOL . $node->C14N() ); @@ -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'; + } } diff --git a/tests/DOMNodeComparatorTest.php b/tests/DOMNodeComparatorTest.php index 8d52fc2..5dc9b7a 100644 --- a/tests/DOMNodeComparatorTest.php +++ b/tests/DOMNodeComparatorTest.php @@ -84,6 +84,14 @@ public function assertEqualsSucceedsProvider() $this->createDOMDocument(""), $this->createDOMDocument(""), ], + [ + $this->createDOMDocument('Тест кириллицы'), + $this->createDOMDocument('Тест кириллицы'), + ], + [ + $this->createDOMDocument('Тест кириллицы'), + $this->createDOMDocument('Тест кириллицы'), + ], ]; } @@ -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('Тест кириллицы'), + $this->createDOMDocument('Тест кириллицы 1'), + ); + } 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;