forked from baraja-core/simple-php-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleDiff.php
More file actions
70 lines (58 loc) · 1.99 KB
/
SimpleDiff.php
File metadata and controls
70 lines (58 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
declare(strict_types=1);
namespace Baraja\DiffGenerator;
final class SimpleDiff
{
public function compare(string $left, string $right, bool $strict = false): Diff
{
if ($strict === false) {
$left = str_replace(["\r\n", "\r"], "\n", trim($left));
$right = str_replace(["\r\n", "\r"], "\n", trim($right));
}
$return = [];
$from = explode("\n", $left);
$to = explode("\n", $right);
$padLength = strlen((string) max(count($from), count($to)));
$changedLines = [];
$captureBuffer = [];
for ($i = 0; isset($from[$i]); $i++) {
$original = $from[$i];
$target = $to[$i] ?? '';
$lineNumber = sprintf('%s| ', str_pad((string) ($i + 1), $padLength, ' ', STR_PAD_LEFT));
if ($original === $target) {
if ($captureBuffer !== []) {
foreach ($captureBuffer as $captureLines) {
foreach ($captureLines as $captureLine) {
$return[] = $captureLine;
}
}
$captureBuffer = [];
}
$return[] = sprintf(' %s%s', $lineNumber, $original);
} else {
$captureBuffer['-'][] = sprintf('- %s%s', $lineNumber, $this->prettyRender($original));
$captureBuffer['+'][] = sprintf('+ %s%s', $lineNumber, $this->prettyRender($target));
$changedLines[] = $i + 1;
}
}
return new Diff($left, $right, implode("\n", $return), $changedLines);
}
public function renderDiff(Diff|string $diff): string
{
$return = [];
foreach (explode("\n", is_string($diff) ? $diff : $diff->getDiff()) as $line) {
if (($line[0] ?? '') === '+') {
$return[] = sprintf('<div style="background:#a2f19c">%s</div>', htmlspecialchars($line));
} elseif (($line[0] ?? '') === '-') {
$return[] = sprintf('<div style="background:#e7acac">%s</div>', htmlspecialchars($line));
} else {
$return[] = sprintf('<div>%s</div>', htmlspecialchars($line));
}
}
return sprintf('<pre class="code">%s</pre>', implode("\n", $return));
}
private function prettyRender(string $haystack): string
{
return str_replace(["\t", ' '], ['→→→→', '·'], $haystack);
}
}