6 * Provide formatter class for all standard response formats.
11 * Base class for all response format views.
13 abstract
class RESTServerView
{
17 function __construct($model, $arguments=array()) {
18 $this->model
= $model;
19 $this->arguments
= $arguments;
22 public abstract
function render();
25 class RESTServerViewBuiltIn
extends RESTServerView
{
26 public
function render() {
27 switch ($this->arguments
['format']) {
29 return $this->render_json($this->model
);
31 return $this->render_json($this->model
, TRUE
);
33 return $this->render_php($this->model
);
35 return $this->render_xml($this->model
);
37 return $this->render_yaml($this->model
);
39 return $this->render_bencode($this->model
);
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);
52 private
function render_php($data) {
53 return serialize($data);
56 private
function render_yaml($data) {
57 include_once
_rest_server_get_spyc_location();
58 return Spyc
::YAMLDump($data, 4, 60);
61 private
function render_bencode($data) {
62 module_load_include('php', 'rest_server', 'lib/bencode');
63 return bencode($data);
66 private
function render_xml($data) {
67 $doc = new
DOMDocument('1.0', 'utf-8');
68 $root = $doc->createElement('result');
69 $doc->appendChild($root);
71 $this->xml_recurse($doc, $root, $data);
73 return $doc->saveXML();
76 private
function xml_recurse(&$doc, &$parent, $data) {
77 if (is_object($data)) {
78 $data = get_object_vars($data);
81 if (is_array($data)) {
82 $assoc = FALSE
|| empty($data);
83 foreach ($data as
$key => $value) {
84 if (is_numeric($key)) {
89 $key = preg_replace('/[^A-Za-z0-9_]/', '_', $key);
90 $key = preg_replace('/^([0-9]+)/', '_$1', $key);
92 $element = $doc->createElement($key);
93 $parent->appendChild($element);
94 $this->xml_recurse($doc, $element, $value);
98 $parent->setAttribute('is_array', 'true');
101 elseif ($data !== NULL
) {
102 $parent->appendChild($doc->createTextNode($data));