Repository navigation
Expand file tree
/
Copy pathInline.php
More file actions
92 lines (78 loc) · 2.68 KB
/
Copy pathInline.php
File metadata and controls
92 lines (78 loc) · 2.68 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
<?php
declare(strict_types=1);
namespace Pharaonic\Diff\Text;
use Pharaonic\Diff\Algorithm\Myers;
use Pharaonic\Diff\ChangeType;
use Pharaonic\Diff\InlineMode;
use Pharaonic\Diff\InlineSegment;
/**
* Splits a removed line and its paired added line into unchanged, removed and added pieces
*
* Word mode compares words, runs of whitespace and single punctuation characters; character mode
* compares grapheme clusters, or bytes when a line is not valid UTF-8. The pieces of each line
* join back into the line exactly.
*
* @internal
*/
final class Inline
{
/**
* @return array{list<InlineSegment>, list<InlineSegment>} The removed line's pieces, then the added line's
*/
public static function segments(string $old, string $new, string $mode): array
{
$oldTokens = self::tokens($old, $mode);
$newTokens = self::tokens($new, $mode);
$oldPieces = [];
$newPieces = [];
foreach (Myers::diff($oldTokens, $newTokens) as [$operation, $oldIndex, $newIndex]) {
if ($operation === Myers::EQUAL) {
self::append($oldPieces, ChangeType::UNCHANGED, $oldTokens[$oldIndex]);
self::append($newPieces, ChangeType::UNCHANGED, $newTokens[$newIndex]);
} elseif ($operation === Myers::DELETE) {
self::append($oldPieces, ChangeType::REMOVED, $oldTokens[$oldIndex]);
} else {
self::append($newPieces, ChangeType::ADDED, $newTokens[$newIndex]);
}
}
return [self::build($oldPieces), self::build($newPieces)];
}
/**
* @return list<string>
*/
private static function tokens(string $line, string $mode): array
{
if ($line === '') {
return [];
}
if ($mode === InlineMode::WORD) {
return Tokens::words($line, true);
}
if (preg_match_all('/\X/u', $line, $matches) !== false && $matches[0] !== []) {
return $matches[0];
}
return str_split($line);
}
/**
* @param list<array{string, string}> $pieces
*/
private static function append(array &$pieces, string $type, string $text): void
{
$last = array_pop($pieces);
if ($last !== null && $last[0] === $type) {
$text = $last[1] . $text;
} elseif ($last !== null) {
$pieces[] = $last;
}
$pieces[] = [$type, $text];
}
/**
* @param list<array{string, string}> $pieces
*
* @return list<InlineSegment>
*/
private static function build(array $pieces): array
{
return array_map(static fn(array $piece): InlineSegment => new InlineSegment($piece[0], $piece[1]), $pieces);
}
}