1 | <?php |
---|
2 | |
---|
3 | require_once('collection.php'); |
---|
4 | |
---|
5 | class Hypermedia { |
---|
6 | |
---|
7 | public $collection; |
---|
8 | public $version = '0.1'; |
---|
9 | |
---|
10 | function setCollection($collection) { |
---|
11 | $this->collection = $collection; |
---|
12 | } |
---|
13 | |
---|
14 | function getCollection() { |
---|
15 | return $this->collection; |
---|
16 | } |
---|
17 | |
---|
18 | function toUtf8($data) { |
---|
19 | |
---|
20 | if (!is_array($data)) |
---|
21 | return is_string($data) ? mb_convert_encoding($data, 'UTF-8', 'UTF-8 , ISO-8859-1') : $data; |
---|
22 | |
---|
23 | $return = array(); |
---|
24 | |
---|
25 | foreach ($data as $i => &$v){ |
---|
26 | if(is_object($v)) |
---|
27 | $v = get_object_vars($v); |
---|
28 | $return[$this->toUtf8($i)] = $this->toUtf8($v); |
---|
29 | } |
---|
30 | return $return; |
---|
31 | } |
---|
32 | |
---|
33 | function generateValidXmlFromObj(stdClass $obj, $node_block = 'nodes', $node_name = 'node') { |
---|
34 | $arr = get_object_vars($obj); |
---|
35 | return self::generateValidXmlFromArray($arr, $node_block, $node_name); |
---|
36 | } |
---|
37 | |
---|
38 | function generateValidXmlFromArray($array, $node_block = 'nodes', $node_name = 'node') { |
---|
39 | $xml = '<?xml version="1.0" encoding="UTF-8" ?>'; |
---|
40 | |
---|
41 | $xml .= '<' . $node_block . '>'; |
---|
42 | $xml .= self::generateXmlFromArray($array, $node_name); |
---|
43 | $xml .= '</' . $node_block . '>'; |
---|
44 | |
---|
45 | return $xml; |
---|
46 | } |
---|
47 | |
---|
48 | function generateXmlFromArray($array, $node_name) { |
---|
49 | $xml = ''; |
---|
50 | |
---|
51 | if (is_array($array) || is_object($array)) { |
---|
52 | foreach ($array as $key => $value) { |
---|
53 | if (is_numeric($key)) { |
---|
54 | $key = $node_name; |
---|
55 | } |
---|
56 | |
---|
57 | $xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>'; |
---|
58 | } |
---|
59 | } else { |
---|
60 | $xml = htmlspecialchars($array, ENT_QUOTES); |
---|
61 | } |
---|
62 | |
---|
63 | return $xml; |
---|
64 | } |
---|
65 | |
---|
66 | function getHypermedia($accept = 'json') { |
---|
67 | |
---|
68 | $data = $this->toUtf8(get_object_vars($this)); |
---|
69 | |
---|
70 | switch ($accept) { |
---|
71 | case 'json': |
---|
72 | return json_encode($data); |
---|
73 | break; |
---|
74 | case 'xml': |
---|
75 | return $this->generateValidXmlFromArray($data); |
---|
76 | default : |
---|
77 | return json_encode($data); |
---|
78 | } |
---|
79 | } |
---|
80 | |
---|
81 | } |
---|
82 | |
---|
83 | ?> |
---|