1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sioen; |
4
|
|
|
|
5
|
|
|
use Sioen\JsonToHtml\BlockquoteConverter; |
6
|
|
|
use Sioen\JsonToHtml\HeadingConverter; |
7
|
|
|
use Sioen\JsonToHtml\IframeConverter; |
8
|
|
|
use Sioen\JsonToHtml\ImageConverter; |
9
|
|
|
use Sioen\JsonToHtml\BaseConverter; |
10
|
|
|
use Sioen\JsonToHtml\Converter; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class JsonToHtml |
14
|
|
|
* |
15
|
|
|
* Converts a json object received from Sir Trevor to an html representation |
16
|
|
|
* |
17
|
|
|
* @version 1.1.0 |
18
|
|
|
* @author Wouter Sioen <[email protected]> |
19
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php MIT |
20
|
|
|
*/ |
21
|
|
|
class JsonToHtml |
22
|
|
|
{ |
23
|
|
|
/** @var array */ |
24
|
|
|
private $converters; |
25
|
|
|
|
26
|
1 |
|
public function __construct() |
27
|
|
|
{ |
28
|
1 |
|
$this->addConverter(new HeadingConverter()); |
29
|
1 |
|
$this->addConverter(new BlockquoteConverter()); |
30
|
1 |
|
$this->addConverter(new IframeConverter()); |
31
|
1 |
|
$this->addConverter(new ImageConverter()); |
32
|
1 |
|
$this->addConverter(new BaseConverter()); |
33
|
1 |
|
} |
34
|
|
|
|
35
|
1 |
|
public function addConverter(Converter $converter) |
36
|
|
|
{ |
37
|
1 |
|
$this->converters[] = $converter; |
38
|
1 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Converts the outputted json from Sir Trevor to html |
42
|
|
|
* |
43
|
|
|
* @param string $json |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
1 |
|
public function toHtml($json) |
47
|
|
|
{ |
48
|
|
|
// convert the json to an associative array |
49
|
1 |
|
$input = json_decode($json, true); |
50
|
1 |
|
$html = ''; |
51
|
|
|
|
52
|
|
|
// loop trough the data blocks |
53
|
1 |
|
foreach ($input['data'] as $block) { |
54
|
1 |
|
$html .= $this->convert($block['type'], $block['data']); |
55
|
1 |
|
} |
56
|
|
|
|
57
|
1 |
|
return $html; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Converts on array to an html string |
63
|
|
|
* |
64
|
|
|
* @param string $type |
65
|
|
|
* @param array $data |
66
|
|
|
* @return string |
67
|
|
|
*/ |
68
|
1 |
|
private function convert($type, array $data) |
69
|
|
|
{ |
70
|
1 |
|
foreach ($this->converters as $converter) { |
71
|
1 |
|
if ($converter->matches($type)) { |
72
|
1 |
|
return $converter->toHtml($data); |
73
|
|
|
} |
74
|
1 |
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|