1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of graze/console-diff-renderer. |
4
|
|
|
* |
5
|
|
|
* Copyright (c) 2017 Nature Delivered Ltd. <https://www.graze.com> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
* |
10
|
|
|
* @license https://github.com/graze/console-diff-renderer/blob/master/LICENSE.md |
11
|
|
|
* @link https://github.com/graze/console-diff-renderer |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Graze\DiffRenderer\Diff; |
15
|
|
|
|
16
|
|
|
class FirstDiff |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Loop through each line, and produce a difference report of what to write out to the terminal |
20
|
|
|
* |
21
|
|
|
* Assumes the beginning of old and new are the same line |
22
|
|
|
* |
23
|
|
|
* @param string[] $old |
24
|
|
|
* @param string[] $new |
25
|
|
|
* |
26
|
|
|
* @return array [[:col, :str]] |
27
|
|
|
*/ |
28
|
|
|
public function lines(array $old, array $new) |
29
|
|
|
{ |
30
|
|
|
$out = []; |
31
|
|
|
$newLen = count($new); |
32
|
|
|
$oldLen = count($old); |
33
|
|
|
for ($i = 0; $i < $oldLen || $i < $newLen; $i++) { |
34
|
|
|
if ($i >= $oldLen) { |
35
|
|
|
$out[] = ['col' => 0, 'str' => $new[$i]]; // write out the entire line for extra lines |
36
|
|
|
} elseif ($i >= $newLen) { |
37
|
|
|
$out[] = ['col' => 0, 'str' => '']; // clear the line if the new array has less entries than the old one |
38
|
|
|
} else { |
39
|
|
|
$col = $this->firstDifference($old[$i], $new[$i]); |
40
|
|
|
if ($col === -1) { |
41
|
|
|
$out[] = null; |
42
|
|
|
} else { |
43
|
|
|
$out[] = ['col' => $col, 'str' => mb_substr($new[$i], $col)]; |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
return $out; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Looks through a line to find the character to of the first difference between the 2 strings. |
52
|
|
|
* |
53
|
|
|
* If no difference is found, returns -1 |
54
|
|
|
* |
55
|
|
|
* @param string $old |
56
|
|
|
* @param string $new |
57
|
|
|
* |
58
|
|
|
* @return int |
59
|
|
|
*/ |
60
|
|
|
public function firstDifference($old, $new) |
61
|
|
|
{ |
62
|
|
|
// loop through old and new character by character and compare |
63
|
|
|
$oldLen = mb_strlen($old); |
64
|
|
|
$newLen = mb_strlen($new); |
65
|
|
|
|
66
|
|
|
if ($oldLen === 0) { |
67
|
|
|
return 0; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
for ($i = 0; $i < $oldLen && $i < $newLen; $i++) { |
71
|
|
|
if (mb_substr($old, $i, 1) !== mb_substr($new, $i, 1)) { |
72
|
|
|
return $i; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
if ($i < $oldLen || $i < $newLen) { |
76
|
|
|
return $i; |
77
|
|
|
} |
78
|
|
|
return -1; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|