-
Notifications
You must be signed in to change notification settings - Fork 0
/
Format.php
302 lines (251 loc) · 6.73 KB
/
Format.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
/**
* Format class
*
* Help convert between various formats such as XML, JSON, CSV, etc.
*
* @author Phil Sturgeon
* @license http://philsturgeon.co.uk/code/dbad-license
*/
class Format {
// Array to convert
protected $_data = array();
// View filename
protected $_from_type = null;
/**
* Returns an instance of the Format object.
*
* echo $this->format->factory(array('foo' => 'bar'))->to_xml();
*
* @param mixed general date to be converted
* @param string data format the file was provided in
* @return Factory
*/
public function factory($data, $from_type = null)
{
// Stupid stuff to emulate the "new static()" stuff in this libraries PHP 5.3 equivalent
$class = __CLASS__;
return new $class($data, $from_type);
}
/**
* Do not use this directly, call factory()
*/
public function __construct($data = null, $from_type = null)
{
get_instance()->load->helper('inflector');
// If the provided data is already formatted we should probably convert it to an array
if ($from_type !== null)
{
if (method_exists($this, '_from_' . $from_type))
{
$data = call_user_func(array($this, '_from_' . $from_type), $data);
}
else
{
throw new Exception('Format class does not support conversion from "' . $from_type . '".');
}
}
$this->_data = $data;
}
// FORMATING OUTPUT ---------------------------------------------------------
public function to_array($data = null)
{
// If not just null, but nothing is provided
if ($data === null and ! func_num_args())
{
$data = $this->_data;
}
$array = array();
foreach ((array) $data as $key => $value)
{
if (is_object($value) or is_array($value))
{
$array[$key] = $this->to_array($value);
}
else
{
$array[$key] = $value;
}
}
return $array;
}
// Format XML for output
public function to_xml($data = null, $structure = null, $basenode = 'xml')
{
if ($data === null and ! func_num_args())
{
$data = $this->_data;
}
// turn off compatibility mode as simple xml throws a wobbly if you don't.
if (ini_get('zend.ze1_compatibility_mode') == 1)
{
ini_set('zend.ze1_compatibility_mode', 0);
}
if ($structure === null)
{
$structure = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$basenode />");
}
// Force it to be something useful
if ( ! is_array($data) AND ! is_object($data))
{
$data = (array) $data;
}
foreach ($data as $key => $value)
{
//change false/true to 0/1
if(is_bool($value))
{
$value = (int) $value;
}
// no numeric keys in our xml please!
if (is_numeric($key))
{
// make string key...
$key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
}
// replace anything not alpha numeric
$key = preg_replace('/[^a-z_\-0-9]/i', '', $key);
if ($key === '_attributes' && (is_array($value) || is_object($value)))
{
$attributes = $value;
if (is_object($attributes)) $attributes = get_object_vars($attributes);
foreach ($attributes as $attributeName => $attributeValue)
{
$structure->addAttribute($attributeName, $attributeValue);
}
}
// if there is another array found recursively call this function
else if (is_array($value) || is_object($value))
{
$node = $structure->addChild($key);
// recursive call.
$this->to_xml($value, $node, $key);
}
else
{
// add single node.
$value = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, "UTF-8");
$structure->addChild($key, $value);
}
}
return $structure->asXML();
}
// Format HTML for output
public function to_html()
{
$data = (array)$this->_data;
// Multi-dimensional array
if (isset($data[0]) && is_array($data[0]))
{
$headings = array_keys($data[0]);
}
// Single array
else
{
$headings = array_keys($data);
$data = array($data);
}
$ci = get_instance();
$ci->load->library('table');
$ci->table->set_heading($headings);
foreach ($data as &$row)
{
$ci->table->add_row($row);
}
return $ci->table->generate();
}
// Format CSV for output
public function to_csv()
{
$data = (array)$this->_data;
// Multi-dimensional array
if (isset($data[0]) && is_array($data[0]))
{
$headings = array_keys($data[0]);
}
// Single array
else
{
$headings = array_keys($data);
$data = array($data);
}
$output = '"'.implode('","', $headings).'"'.PHP_EOL;
foreach ($data as &$row)
{
if (is_array($row)) {
throw new Exception('Format class does not support multi-dimensional arrays');
} else {
$row = str_replace('"', '""', $row); // Escape dbl quotes per RFC 4180
$output .= '"'.implode('","', $row).'"'.PHP_EOL;
}
}
return $output;
}
// Encode as JSON
public function to_json()
{
$callback = isset($_GET['callback']) ? $_GET['callback'] : '';
if ($callback === '')
{
return json_encode($this->_data);
}
// we only honour jsonp callback which are valid javascript identifiers
else if (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
{
// this is a jsonp request, the content-type must be updated to be text/javascript
header("Content-Type: application/javascript");
return $callback . "(" . json_encode($this->_data) . ");";
}
else
{
// we have an invalid jsonp callback identifier, we'll return plain json with a warning field
$this->_data['warning'] = "invalid jsonp callback provided: ".$callback;
return json_encode($this->_data);
}
}
// Encode as Serialized array
public function to_serialized()
{
return serialize($this->_data);
}
// Output as a string representing the PHP structure
public function to_php()
{
return var_export($this->_data, TRUE);
}
// Format XML for output
protected function _from_xml($string)
{
return $string ? (array) simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array();
}
// Format CSV for output
// This function is DODGY! Not perfect CSV support but works with my REST_Controller
protected function _from_csv($string)
{
$data = array();
// Splits
$rows = explode("\n", trim($string));
$headings = explode(',', array_shift($rows));
foreach ($rows as $row)
{
// The substr removes " from start and end
$data_fields = explode('","', trim(substr($row, 1, -1)));
if (count($data_fields) == count($headings))
{
$data[] = array_combine($headings, $data_fields);
}
}
return $data;
}
// Encode as JSON
private function _from_json($string)
{
return json_decode(trim($string));
}
// Encode as Serialized array
private function _from_serialize($string)
{
return unserialize(trim($string));
}
}
/* End of file format.php */