| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jfcherng\Diff\Renderer\Html\LineRenderer; |
| 6 |
|
| 7 |
use Jfcherng\Diff\Renderer\RendererConstant; |
| 8 |
use Jfcherng\Utility\MbString; |
| 9 |
|
| 10 |
final class Line extends AbstractLineRenderer |
| 11 |
{ |
| 12 |
/** |
| 13 |
* @return static |
| 14 |
*/ |
| 15 |
public function render(MbString $mbOld, MbString $mbNew): LineRendererInterface |
| 16 |
{ |
| 17 |
[$start, $end] = $this->getChangedExtentRegion($mbOld, $mbNew); |
| 18 |
|
| 19 |
// two strings are the same |
| 20 |
if ($end === 0) { |
| 21 |
return $this; |
| 22 |
} |
| 23 |
|
| 24 |
// two strings are different, we do rendering |
| 25 |
$mbOld->str_enclose_i( |
| 26 |
RendererConstant::HTML_CLOSURES, |
| 27 |
$start, |
| 28 |
$end + $mbOld->strlen() - $start + 1, |
| 29 |
); |
| 30 |
$mbNew->str_enclose_i( |
| 31 |
RendererConstant::HTML_CLOSURES, |
| 32 |
$start, |
| 33 |
$end + $mbNew->strlen() - $start + 1, |
| 34 |
); |
| 35 |
|
| 36 |
return $this; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Given two strings, determine where the changes in the two strings begin, |
| 41 |
* and where the changes in the two strings end. |
| 42 |
* |
| 43 |
* @param MbString $mbOld the old megabytes line |
| 44 |
* @param MbString $mbNew the new megabytes line |
| 45 |
* |
| 46 |
* @return int[] Array containing the starting position (non-negative) and the ending position (negative) |
| 47 |
* [0, 0] if two strings are the same |
| 48 |
*/ |
| 49 |
protected function getChangedExtentRegion(MbString $mbOld, MbString $mbNew): array |
| 50 |
{ |
| 51 |
// two strings are the same |
| 52 |
// most lines should be this cases, an early return could save many function calls |
| 53 |
if ($mbOld->getRaw() === $mbNew->getRaw()) { |
| 54 |
return [0, 0]; |
| 55 |
} |
| 56 |
|
| 57 |
// calculate $start |
| 58 |
$start = 0; |
| 59 |
$startMax = min($mbOld->strlen(), $mbNew->strlen()); |
| 60 |
while ( |
| 61 |
$start < $startMax // index out of range |
| 62 |
&& $mbOld->getAtRaw($start) === $mbNew->getAtRaw($start) |
| 63 |
) { |
| 64 |
++$start; |
| 65 |
} |
| 66 |
|
| 67 |
// calculate $end |
| 68 |
$end = -1; // trick |
| 69 |
$endMin = $startMax - $start; |
| 70 |
while ( |
| 71 |
-$end <= $endMin // index out of range |
| 72 |
&& $mbOld->getAtRaw($end) === $mbNew->getAtRaw($end) |
| 73 |
) { |
| 74 |
--$end; |
| 75 |
} |
| 76 |
|
| 77 |
return [$start, $end]; |
| 78 |
} |
| 79 |
} |