1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Caxy\HtmlDiff; |
4
|
|
|
|
5
|
|
|
class Preprocessor |
6
|
|
|
{ |
7
|
6 |
|
public static function diffCommonPrefix($old, $new) |
8
|
|
|
{ |
9
|
|
|
// Quick check for common null cases. |
10
|
6 |
|
if (strlen($old) == 0 || strlen($new) == 0 || substr($old, 0, 1) != substr($new, 0, 1)) { |
11
|
6 |
|
return 0; |
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
// Binary Search |
15
|
4 |
|
$pointerMin = 0; |
16
|
4 |
|
$pointerMax = min(strlen($old), strlen($new)); |
17
|
4 |
|
$pointerMid = $pointerMax; |
18
|
4 |
|
$pointerStart = 0; |
19
|
4 |
View Code Duplication |
while ($pointerMin < $pointerMid) { |
|
|
|
|
20
|
4 |
|
$cmp = substr_compare( |
21
|
4 |
|
$old, |
22
|
4 |
|
substr($new, $pointerStart, $pointerMid - $pointerStart), |
23
|
4 |
|
$pointerStart, |
24
|
|
|
$pointerMid - $pointerStart |
25
|
4 |
|
); |
26
|
4 |
|
if (0 === $cmp) { |
27
|
4 |
|
$pointerMin = $pointerMid; |
28
|
4 |
|
$pointerStart = $pointerMin; |
29
|
4 |
|
} else { |
30
|
4 |
|
$pointerMax = $pointerMid; |
31
|
|
|
} |
32
|
4 |
|
$pointerMid = floor(($pointerMax - $pointerMin) / 2 + $pointerMin); |
33
|
4 |
|
} |
34
|
4 |
|
return $pointerMid; |
35
|
|
|
} |
36
|
|
|
|
37
|
6 |
|
public static function diffCommonSuffix($old, $new) |
38
|
|
|
{ |
39
|
|
|
// Quick check for common null cases. |
40
|
6 |
|
if (strlen($old) == 0 || strlen($new) == 0 || substr($old, strlen($old) - 1, 1) != substr($new, strlen($new) - 1, 1)) { |
|
|
|
|
41
|
2 |
|
return 0; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// Binary Search |
45
|
5 |
|
$pointerMin = 0; |
46
|
5 |
|
$pointerMax = min(strlen($old), strlen($new)); |
47
|
5 |
|
$pointerMid = $pointerMax; |
48
|
5 |
|
$pointerEnd = 0; |
49
|
5 |
|
$oldLen = strlen($old); |
50
|
5 |
|
$newLen = strlen($new); |
51
|
5 |
View Code Duplication |
while ($pointerMin < $pointerMid) { |
|
|
|
|
52
|
5 |
|
if (substr($old, $oldLen - $pointerMid, $pointerMid - $pointerEnd) == substr($new, $newLen - $pointerMid, $pointerMid - $pointerEnd)) { |
|
|
|
|
53
|
5 |
|
$pointerMin = $pointerMid; |
54
|
5 |
|
$pointerEnd = $pointerMin; |
55
|
5 |
|
} else { |
56
|
5 |
|
$pointerMax = $pointerMid; |
57
|
|
|
} |
58
|
5 |
|
$pointerMid = floor(($pointerMax - $pointerMin) / 2 + $pointerMin); |
59
|
5 |
|
} |
60
|
5 |
|
return $pointerMid; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.