Repository navigation
Expand file tree
/
Copy pathDiffScript.php
More file actions
106 lines (94 loc) · 2.98 KB
/
Copy pathDiffScript.php
File metadata and controls
106 lines (94 loc) · 2.98 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
declare(strict_types=1);
namespace PHPForge\Diff\Tests\Support;
use PHPForge\Diff\DiffLine;
use PHPForge\Diff\DiffOp;
use function array_map;
use function implode;
/**
* Converts edit scripts returned by {@see \PHPForge\Diff\DifferInterface} implementations into comparable values.
*
* Shared by the unit tests to reconstruct either side of a diff, render it as readable snapshot lines, encode its
* operations and count its edits.
*/
final class DiffScript
{
/**
* Counts the lines of a diff that are not {@see DiffOp::Context}.
*
* @param list<DiffLine> $diff Edit script to inspect.
*
* @return int<0, max> Number of removed and added lines.
*/
public static function editCount(array $diff): int
{
$count = 0;
foreach ($diff as $line) {
if ($line->op !== DiffOp::Context) {
$count++;
}
}
return $count;
}
/**
* Encodes the operations of a diff as one character per line: `=` kept, `-` removed and `+` added.
*
* @param list<DiffLine> $diff Edit script to encode.
*
* @return string Operations in script order.
*/
public static function operations(array $diff): string
{
return implode(
'',
array_map(
static fn(DiffLine $line): string => match ($line->op) {
DiffOp::Context => '=',
DiffOp::Remove => '-',
DiffOp::Add => '+',
},
$diff,
),
);
}
/**
* Reconstructs one side of the comparison by dropping the edits that belong to the other side.
*
* Excluding {@see DiffOp::Add} leaves the old side; excluding {@see DiffOp::Remove} leaves the new side.
*
* @param list<DiffLine> $diff Edit script to reconstruct from.
* @param DiffOp $exclude Operation whose lines are dropped.
*
* @return string Lines of the reconstructed side joined with `\n`.
*/
public static function reconstruct(array $diff, DiffOp $exclude): string
{
$lines = [];
foreach ($diff as $line) {
if ($line->op !== $exclude) {
$lines[] = $line->line;
}
}
return implode("\n", $lines);
}
/**
* Renders a diff as one prefixed string per line for exact, readable alignment snapshots.
*
* Context lines are prefixed with two spaces, removed lines with `- ` and added lines with `+ `.
*
* @param list<DiffLine> $diff Edit script to render.
*
* @return list<string> Rendered lines in script order.
*/
public static function render(array $diff): array
{
return array_map(
static fn(DiffLine $line): string => match ($line->op) {
DiffOp::Context => " {$line->line}",
DiffOp::Remove => "- {$line->line}",
DiffOp::Add => "+ {$line->line}",
},
$diff,
);
}
}