Completed
Pull Request — master (#7)
by Steve
03:38
created

DaisyDiff::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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