Skip to content
This repository was archived by the owner on Jul 26, 2024. It is now read-only.

Commit c4ffae9

Browse files
committed
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
1 parent 12ca107 commit c4ffae9

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/Diff.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ private function removeOrphans(array $matches): Generator
382382
$prev = new DiffMatch(0, 0, 0);
383383
$curr = $matches[0] ?? new DiffMatch(0, 0, 0);
384384

385-
foreach (array_slice($matches, 1) as $index => $next) {
385+
foreach (array_slice($matches, 1) as $next) {
386386
// if match has no diff on the left or on the right
387387
if ($prev->getEndInOld() === $curr->startInOld && $prev->getEndInNew() === $curr->startInNew
388388
|| $curr->getEndInOld() === $next->startInOld && $curr->getEndInNew() === $next->startInNew
@@ -395,13 +395,13 @@ private function removeOrphans(array $matches): Generator
395395

396396
$oldDistanceInChars = array_sum(array_map(function($i) {
397397
return mb_strlen($this->oldWords[$i]);
398-
}, range($prev->getEndInOld(), $next->startInOld - $prev->getEndInOld())));
398+
}, range($prev->getEndInOld(), $next->startInOld - 1)));
399399
$newDistanceInChars = array_sum(array_map(function($i) {
400400
return mb_strlen($this->newWords[$i]);
401-
}, range($prev->getEndInNew(), $next->startInNew - $prev->getEndInNew())));
401+
}, range($prev->getEndInNew(), $next->startInNew - 1)));
402402
$currMatchLengthInChars = array_sum(array_map(function($i) {
403403
return mb_strlen($this->newWords[$i]);
404-
}, range($curr->startInNew, $curr->getEndInNew() - $curr->startInNew)));
404+
}, range($curr->startInNew, $curr->getEndInNew() - 1)));
405405
if ($currMatchLengthInChars > max($oldDistanceInChars, $newDistanceInChars) * $this->orphanMatchThreshold) {
406406
yield $curr;
407407
}

tests/HtmlDiffTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,10 @@ public function test_newlines_changes_between_tags_is_tracked()
116116
$output = Diff::excecute("<p>Section A</p><p>Section B</p>", "<p>Section A</p>\n\n<p>Section B</p>");
117117
$this->assertEquals("<p>Section A</p><ins class=\"diffins\">\n\n</ins><p>Section B</p>", $output);
118118
}
119+
120+
public function test_edge_changes_result_as_expected()
121+
{
122+
$output = Diff::excecute("AAA BBB CCC", "ZZZ BBB YYY");
123+
$this->assertEquals('<del class="diffmod">AAA</del><ins class="diffmod">ZZZ</ins> BBB <del class="diffmod">CCC</del><ins class="diffmod">YYY</ins>', $output);
124+
}
119125
}

0 commit comments

Comments
 (0)