Ei kuvausta

DOMNodeComparator.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of sebastian/comparator.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace SebastianBergmann\Comparator;
  11. use DOMDocument;
  12. use DOMNode;
  13. /**
  14. * Compares DOMNode instances for equality.
  15. */
  16. class DOMNodeComparator extends ObjectComparator
  17. {
  18. /**
  19. * Returns whether the comparator can compare two values.
  20. *
  21. * @param mixed $expected The first value to compare
  22. * @param mixed $actual The second value to compare
  23. *
  24. * @return bool
  25. */
  26. public function accepts($expected, $actual)
  27. {
  28. return $expected instanceof DOMNode && $actual instanceof DOMNode;
  29. }
  30. /**
  31. * Asserts that two values are equal.
  32. *
  33. * @param mixed $expected First value to compare
  34. * @param mixed $actual Second value to compare
  35. * @param float $delta Allowed numerical distance between two values to consider them equal
  36. * @param bool $canonicalize Arrays are sorted before comparison when set to true
  37. * @param bool $ignoreCase Case is ignored when set to true
  38. * @param array $processed List of already processed elements (used to prevent infinite recursion)
  39. *
  40. * @throws ComparisonFailure
  41. */
  42. public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = [])
  43. {
  44. $expectedAsString = $this->nodeToText($expected, true, $ignoreCase);
  45. $actualAsString = $this->nodeToText($actual, true, $ignoreCase);
  46. if ($expectedAsString !== $actualAsString) {
  47. $type = $expected instanceof DOMDocument ? 'documents' : 'nodes';
  48. throw new ComparisonFailure(
  49. $expected,
  50. $actual,
  51. $expectedAsString,
  52. $actualAsString,
  53. false,
  54. \sprintf("Failed asserting that two DOM %s are equal.\n", $type)
  55. );
  56. }
  57. }
  58. /**
  59. * Returns the normalized, whitespace-cleaned, and indented textual
  60. * representation of a DOMNode.
  61. */
  62. private function nodeToText(DOMNode $node, bool $canonicalize, bool $ignoreCase): string
  63. {
  64. if ($canonicalize) {
  65. $document = new DOMDocument;
  66. @$document->loadXML($node->C14N());
  67. $node = $document;
  68. }
  69. $document = $node instanceof DOMDocument ? $node : $node->ownerDocument;
  70. $document->formatOutput = true;
  71. $document->normalizeDocument();
  72. $text = $node instanceof DOMDocument ? $node->saveXML() : $document->saveXML($node);
  73. return $ignoreCase ? \strtolower($text) : $text;
  74. }
  75. }