issue [#1563130] by logaritmisk Resource file:create_raw should set file status to...
[project/services.git] / servers / rest_server / includes / rest_server.views.inc
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * Provide formatter class for all standard response formats.
7 *
8 */
9
10 /**
11 * Base class for all response format views.
12 */
13 abstract class RESTServerView {
14 protected $model;
15 protected $arguments;
16
17 function __construct($model, $arguments=array()) {
18 $this->model = $model;
19 $this->arguments = $arguments;
20 }
21
22 public abstract function render();
23 }
24
25 class RESTServerViewBuiltIn extends RESTServerView {
26 public function render() {
27 switch ($this->arguments['format']) {
28 case 'json':
29 return $this->render_json($this->model);
30 case 'jsonp':
31 return $this->render_json($this->model, TRUE);
32 case 'php':
33 return $this->render_php($this->model);
34 case 'xml':
35 return $this->render_xml($this->model);
36 case 'yaml':
37 return $this->render_yaml($this->model);
38 case 'bencode':
39 return $this->render_bencode($this->model);
40 }
41 return '';
42 }
43
44 private function render_json($data, $jsonp = FALSE) {
45 $json = str_replace('\\/', '/', json_encode($data));
46 if ($jsonp && isset($_GET['callback'])) {
47 return sprintf('%s(%s);', $_GET['callback'], $json);
48 }
49 return $json;
50 }
51
52 private function render_php($data) {
53 return serialize($data);
54 }
55
56 private function render_yaml($data) {
57 include_once _rest_server_get_spyc_location();
58 return Spyc::YAMLDump($data, 4, 60);
59 }
60
61 private function render_bencode($data) {
62 module_load_include('php', 'rest_server', 'lib/bencode');
63 return bencode($data);
64 }
65
66 private function render_xml($data) {
67 $doc = new DOMDocument('1.0', 'utf-8');
68 $root = $doc->createElement('result');
69 $doc->appendChild($root);
70
71 $this->xml_recurse($doc, $root, $data);
72
73 return $doc->saveXML();
74 }
75
76 private function xml_recurse(&$doc, &$parent, $data) {
77 if (is_object($data)) {
78 $data = get_object_vars($data);
79 }
80
81 if (is_array($data)) {
82 $assoc = FALSE || empty($data);
83 foreach ($data as $key => $value) {
84 if (is_numeric($key)) {
85 $key = 'item';
86 }
87 else {
88 $assoc = TRUE;
89 $key = preg_replace('/[^A-Za-z0-9_]/', '_', $key);
90 $key = preg_replace('/^([0-9]+)/', '_$1', $key);
91 }
92 $element = $doc->createElement($key);
93 $parent->appendChild($element);
94 $this->xml_recurse($doc, $element, $value);
95 }
96
97 if (!$assoc) {
98 $parent->setAttribute('is_array', 'true');
99 }
100 }
101 elseif ($data !== NULL) {
102 $parent->appendChild($doc->createTextNode($data));
103 }
104 }
105 }