From c4ffae9ed27950729e7ad399f21de11d1c44507d Mon Sep 17 00:00:00 2001 From: Dan Brown Date: Fri, 29 Mar 2024 16:47:39 +0000 Subject: [PATCH] Fixed bad range usage, added test to cover Bad range values due to copying .net code, which uses (start, count) values, to PHP which uses (start, end) values. Related to #4 --- src/Diff.php | 8 ++++---- tests/HtmlDiffTest.php | 6 ++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Diff.php b/src/Diff.php index b4c1496..b4a1090 100644 --- a/src/Diff.php +++ b/src/Diff.php @@ -382,7 +382,7 @@ private function removeOrphans(array $matches): Generator $prev = new DiffMatch(0, 0, 0); $curr = $matches[0] ?? new DiffMatch(0, 0, 0); - foreach (array_slice($matches, 1) as $index => $next) { + foreach (array_slice($matches, 1) as $next) { // if match has no diff on the left or on the right if ($prev->getEndInOld() === $curr->startInOld && $prev->getEndInNew() === $curr->startInNew || $curr->getEndInOld() === $next->startInOld && $curr->getEndInNew() === $next->startInNew @@ -395,13 +395,13 @@ private function removeOrphans(array $matches): Generator $oldDistanceInChars = array_sum(array_map(function($i) { return mb_strlen($this->oldWords[$i]); - }, range($prev->getEndInOld(), $next->startInOld - $prev->getEndInOld()))); + }, range($prev->getEndInOld(), $next->startInOld - 1))); $newDistanceInChars = array_sum(array_map(function($i) { return mb_strlen($this->newWords[$i]); - }, range($prev->getEndInNew(), $next->startInNew - $prev->getEndInNew()))); + }, range($prev->getEndInNew(), $next->startInNew - 1))); $currMatchLengthInChars = array_sum(array_map(function($i) { return mb_strlen($this->newWords[$i]); - }, range($curr->startInNew, $curr->getEndInNew() - $curr->startInNew))); + }, range($curr->startInNew, $curr->getEndInNew() - 1))); if ($currMatchLengthInChars > max($oldDistanceInChars, $newDistanceInChars) * $this->orphanMatchThreshold) { yield $curr; } diff --git a/tests/HtmlDiffTest.php b/tests/HtmlDiffTest.php index f18998b..0b770d8 100644 --- a/tests/HtmlDiffTest.php +++ b/tests/HtmlDiffTest.php @@ -116,4 +116,10 @@ public function test_newlines_changes_between_tags_is_tracked() $output = Diff::excecute("

Section A

Section B

", "

Section A

\n\n

Section B

"); $this->assertEquals("

Section A

\n\n

Section B

", $output); } + + public function test_edge_changes_result_as_expected() + { + $output = Diff::excecute("AAA BBB CCC", "ZZZ BBB YYY"); + $this->assertEquals('AAAZZZ BBB CCCYYY', $output); + } } \ No newline at end of file