HtmlToJson   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 90.91%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 7
c 5
b 0
f 0
lcom 1
cbo 0
dl 0
loc 56
ccs 20
cts 22
cp 0.9091
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addConverter() 0 4 1
B toJson() 0 24 3
A convert() 0 8 3
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
        // Load UTF-8 HTML hack (from http://bit.ly/pVDyCt)
39 3
        $document->loadHTML('<?xml encoding="UTF-8">' . $html);
40 3
        $document->encoding = 'UTF-8';
41
42
        // fetch the body of the document. All html is stored in there
43 3
        $body = $document->getElementsByTagName("body")->item(0);
44
45 3
        $data = array();
46
47
        // loop trough the child nodes and convert them
48 3
        if ($body) {
49 3
            foreach ($body->childNodes as $node) {
50 3
                $data[] = $this->convert($node);
51 3
            }
52 3
        }
53
54 3
        return json_encode(array('data' => $data));
55
    }
56
57
    /**
58
     * Converts one node to json
59
     *
60
     * @param \DOMElement $node
61
     * @return array
62
     */
63 3
    private function convert(\DOMElement $node)
64
    {
65 3
        foreach ($this->converters as $converter) {
66 3
            if ($converter->matches($node)) {
67 3
                return $converter->toJson($node);
68
            }
69
        }
70
    }
71
}
72