1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* (c) Steve Nebes <[email protected]> |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
declare(strict_types=1); |
10
|
|
|
|
11
|
|
|
namespace DaisyDiff; |
12
|
|
|
|
13
|
|
|
use DaisyDiff\Html\ChangeText; |
14
|
|
|
use DaisyDiff\Html\Dom\DomTreeBuilder; |
15
|
|
|
use DaisyDiff\Html\HtmlDiffer; |
16
|
|
|
use DaisyDiff\Html\HtmlSaxDiffOutput; |
17
|
|
|
use DaisyDiff\Html\TextNodeComparator; |
18
|
|
|
use DaisyDiff\Tag\TagComparator; |
19
|
|
|
use DaisyDiff\Tag\TagDiffer; |
20
|
|
|
use DaisyDiff\Tag\TagSaxDiffOutput; |
21
|
|
|
use DaisyDiff\Xml\XMLReader; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Daisy Diff is a library that diffs (compares) HTML. |
25
|
|
|
*/ |
26
|
|
|
class DaisyDiff |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* Diffs two HTML strings, returning the result. |
30
|
|
|
* |
31
|
|
|
* @param string $oldText |
32
|
|
|
* @param string $newText |
33
|
|
|
* @return string |
34
|
|
|
*/ |
35
|
|
|
public function diff(string $oldText, string $newText): string |
36
|
|
|
{ |
37
|
|
|
// Parse $old XML. |
38
|
|
|
$oldHandler = new DomTreeBuilder(); |
39
|
|
|
$reader1 = new XMLReader($oldHandler); |
40
|
|
|
$reader1->parse($oldText); |
41
|
|
|
|
42
|
|
|
// Parse $new XML. |
43
|
|
|
$newHandler = new DomTreeBuilder(); |
44
|
|
|
$reader2 = new XMLReader($newHandler); |
45
|
|
|
$reader2->parse($newText); |
46
|
|
|
|
47
|
|
|
// Comparators. |
48
|
|
|
$leftComparator = new TextNodeComparator($oldHandler); |
49
|
|
|
$rightComparator = new TextNodeComparator($newHandler); |
50
|
|
|
|
51
|
|
|
$changeText = new ChangeText(); |
52
|
|
|
$output = new HtmlSaxDiffOutput($changeText); |
53
|
|
|
$differ = new HtmlDiffer($output); |
54
|
|
|
$differ->diff($leftComparator, $rightComparator); |
55
|
|
|
|
56
|
|
|
return $changeText->getText(); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function diffTag(string $oldText, string $newText): string |
60
|
|
|
{ |
61
|
|
|
$oldComp = new TagComparator($oldText); |
62
|
|
|
$newComp = new TagComparator($newText); |
63
|
|
|
|
64
|
|
|
$changeText = new ChangeText(); |
65
|
|
|
$output = new TagSaxDiffOutput($changeText); |
66
|
|
|
$differ = new TagDiffer($output); |
67
|
|
|
$differ->diff($oldComp, $newComp); |
68
|
|
|
|
69
|
|
|
return $changeText->getText(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|