Completed
Push — SOLID ( b29565...2dffc4 )
by Wouter
01:54
created

JsonToHtml::convert()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.3332

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
ccs 4
cts 6
cp 0.6667
rs 9.4285
cc 3
eloc 4
nc 3
nop 2
crap 3.3332
1
<?php
2
3
namespace Sioen;
4
5
use Sioen\JsonToHtml\Converter;
6
7
/**
8
 * Class JsonToHtml
9
 *
10
 * Converts a json object received from Sir Trevor to an html representation
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
class JsonToHtml
17
{
18
    /** @var array */
19
    private $converters;
20
21 5
    public function addConverter(Converter $converter)
22
    {
23 5
        $this->converters[] = $converter;
24 5
    }
25
26
    /**
27
     * Converts the outputted json from Sir Trevor to html
28
     *
29
     * @param  string $json
30
     * @return string
31
     */
32 5
    public function toHtml($json)
33
    {
34
        // convert the json to an associative array
35 5
        $input = json_decode($json, true);
36 5
        $html = '';
37
38
        // loop trough the data blocks
39 5
        foreach ($input['data'] as $block) {
40 5
            $html .= $this->convert($block['type'], $block['data']);
41 5
        }
42
43 5
        return $html;
44
    }
45
46
47
    /**
48
     * Converts on array to an html string
49
     *
50
     * @param string $type
51
     * @param array $data
52
     * @return string
53
     */
54 5
    private function convert($type, array $data)
55
    {
56 5
        foreach ($this->converters as $converter) {
57 5
            if ($converter->matches($type)) {
58 5
                return $converter->toHtml($data);
59
            }
60
        }
61
    }
62
}
63