[6351] | 1 | <?php |
---|
| 2 | |
---|
[6395] | 3 | require_once('collection.php'); |
---|
[6351] | 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 | |
---|
[6559] | 18 | function toUtf8($data) { |
---|
[6351] | 19 | |
---|
[6559] | 20 | if (!is_array($data)) |
---|
| 21 | return is_string($data) ? mb_convert_encoding($data, 'UTF-8', 'UTF-8 , ISO-8859-1') : $data; |
---|
[6351] | 22 | |
---|
[6559] | 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); |
---|
[6351] | 29 | } |
---|
[6559] | 30 | return $return; |
---|
[6351] | 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 | |
---|
[6559] | 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 | |
---|
[6351] | 81 | } |
---|
| 82 | |
---|
| 83 | ?> |
---|