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

Commit

Permalink
Fixed bad range usage, added test to cover
Browse files Browse the repository at this point in the history
Bad range values due to copying .net code, which uses
(start, count) values, to PHP which uses (start, end) values.

Related to #4
  • Loading branch information
ssddanbrown committed Mar 29, 2024
1 parent 12ca107 commit c4ffae9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/Diff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
}
Expand Down
6 changes: 6 additions & 0 deletions tests/HtmlDiffTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,10 @@ public function test_newlines_changes_between_tags_is_tracked()
$output = Diff::excecute("<p>Section A</p><p>Section B</p>", "<p>Section A</p>\n\n<p>Section B</p>");
$this->assertEquals("<p>Section A</p><ins class=\"diffins\">\n\n</ins><p>Section B</p>", $output);
}

public function test_edge_changes_result_as_expected()
{
$output = Diff::excecute("AAA BBB CCC", "ZZZ BBB YYY");
$this->assertEquals('<del class="diffmod">AAA</del><ins class="diffmod">ZZZ</ins> BBB <del class="diffmod">CCC</del><ins class="diffmod">YYY</ins>', $output);
}
}

0 comments on commit c4ffae9

Please sign in to comment.