1 <?php
2 3 4 5 6 7
8 defined('FOF_INCLUDED') or die;
9
10 11 12 13 14 15
16 class FOFHalRenderJson implements FOFHalRenderInterface
17 {
18 19 20 21 22
23 private $_dataKey = '_list';
24
25 26 27 28 29
30 protected $_document;
31
32 33 34 35 36
37 public function __construct(&$document)
38 {
39 $this->_document = $document;
40 }
41
42 43 44 45 46 47 48
49 public function render($options = array())
50 {
51 if (isset($options['data_key']))
52 {
53 $this->_dataKey = $options['data_key'];
54 }
55
56 if (isset($options['json_options']))
57 {
58 $jsonOptions = $options['json_options'];
59 }
60 else
61 {
62 $jsonOptions = 0;
63 }
64
65 $serialiseThis = new stdClass;
66
67
68 $collection = $this->_document->getLinks();
69 $serialiseThis->_links = new stdClass;
70
71 foreach ($collection as $rel => $links)
72 {
73 if (!is_array($links))
74 {
75 $serialiseThis->_links->$rel = $this->_getLink($links);
76 }
77 else
78 {
79 $serialiseThis->_links->$rel = array();
80
81 foreach ($links as $link)
82 {
83 array_push($serialiseThis->_links->$rel, $this->_getLink($link));
84 }
85 }
86 }
87
88
89
90 $collection = $this->_document->getEmbedded();
91
92 if (!empty($collection))
93 {
94 $serialiseThis->_embedded->$rel = new stdClass;
95
96 foreach ($collection as $rel => $embeddeddocs)
97 {
98 if (!is_array($embeddeddocs))
99 {
100 $embeddeddocs = array($embeddeddocs);
101 }
102
103 foreach ($embeddeddocs as $embedded)
104 {
105 $renderer = new FOFHalRenderJson($embedded);
106 array_push($serialiseThis->_embedded->$rel, $renderer->render($options));
107 }
108 }
109 }
110
111
112 $data = $this->_document->getData();
113
114 if (is_object($data))
115 {
116 if ($data instanceof FOFTable)
117 {
118 $data = $data->getData();
119 }
120 else
121 {
122 $data = (array) $data;
123 }
124
125 if (!empty($data))
126 {
127 foreach ($data as $k => $v)
128 {
129 $serialiseThis->$k = $v;
130 }
131 }
132 }
133 elseif (is_array($data))
134 {
135 $serialiseThis->{$this->_dataKey} = $data;
136 }
137
138 return json_encode($serialiseThis, $jsonOptions);
139 }
140
141 142 143 144 145 146 147 148
149 protected function _getLink(FOFHalLink $link)
150 {
151 $ret = array(
152 'href' => $link->href
153 );
154
155 if ($link->templated)
156 {
157 $ret['templated'] = 'true';
158 }
159
160 if (!empty($link->name))
161 {
162 $ret['name'] = $link->name;
163 }
164
165 if (!empty($link->hreflang))
166 {
167 $ret['hreflang'] = $link->hreflang;
168 }
169
170 if (!empty($link->title))
171 {
172 $ret['title'] = $link->title;
173 }
174
175 return (object) $ret;
176 }
177 }
178