Completed
Pull Request — master (#8)
by
unknown
02:09
created

HtmlToJson::addConverter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Sioen;
4
5
use Sioen\HtmlToJson\Converter;
6
7
/**
8
 * Class HtmlToJson
9
 *
10
 * Converts html to a json object that can be understood by Sir Trevor
11
 *
12
 * @version 1.1.0
13
 * @author Wouter Sioen <[email protected]>
14
 * @license http://www.opensource.org/licenses/mit-license.php MIT
15
 */
16
final class HtmlToJson
17
{
18
    /** @var array */
19
    private $converters = array();
20
21 3
    public function addConverter(Converter $converter)
22
    {
23 3
        $this->converters[] = $converter;
24 3
    }
25
26
    /**
27
     * Converts html to the json Sir Trevor requires
28
     *
29
     * @param  string $html
30
     * @return string The json string
31
     */
32 3
    public function toJson($html)
33
    {
34
        // Strip white space between tags to prevent creation of empty #text nodes
35 3
        $html = preg_replace('~>\s+<~', '><', $html);
36 3
        $document = new \DOMDocument();
37
38 3
        libxml_use_internal_errors(true);
39
        // Load UTF-8 HTML hack (from http://bit.ly/pVDyCt)
40 3
        $document->loadHTML('<?xml encoding="UTF-8">' . $html);
41 3
        $document->encoding = 'UTF-8';
42
43
        // fetch the body of the document. All html is stored in there
44 3
        $body = $document->getElementsByTagName("body")->item(0);
45
46 3
        $data = array();
47
48
        // loop trough the child nodes and convert them
49 3
        if ($body) {
50 3
            foreach ($body->childNodes as $node) {
51 3
                $data[] = $this->convert($node);
52 3
            }
53 3
        }
54
55 3
        return json_encode(array('data' => $data), JSON_UNESCAPED_UNICODE);
56
    }
57
58
    /**
59
     * Converts one node to json
60
     *
61
     * @param \DOMElement $node
62
     * @return array
63
     */
64 3
    private function convert(\DOMElement $node)
65
    {
66 3
        foreach ($this->converters as $converter) {
67 3
            if ($converter->matches($node)) {
68 3
                return $converter->toJson($node);
69
            }
70
        }
71
    }
72
}
73