KumbiaPHP  beta2
Framework PHP
 Todo Estructuras de Datos Namespaces Archivos Funciones Variables Páginas
kumbia_rest.php
Ir a la documentación de este archivo.
1 <?php
2 
3 require_once dirname(__FILE__) . '/controller.php';
4 
17 class KumbiaRest extends Controller {
18 
24  protected $_fInput = null;
25 
32  protected $_inputType = array(
33  'application/json' => array('RestController', 'parseJSON'),
34  'application/xml' => array('RestController', 'parseXML'),
35  'text/xml' => array('RestController', 'parseXML'),
36  'text/csv' => array('RestController', 'parseCSV'),
37  'application/x-www-form-urlencoded' => array('RestController', 'parseForm'),
38  );
39 
44  protected $_fOutput = null;
45 
51  protected $_outputType = array(
52  'application/json' => 'json',
53  'application/xml' => 'xml',
54  'text/xml' => 'xml',
55  'text/csv' => 'csv',
56  );
57 
58  public function __construct($module, $controller, $action, $parameters) {
59  parent::__construct($module, $controller, $action, $parameters);
60  $this->initREST();
61  }
62 
67  protected function initREST() {
68  /* formato de entrada */
69  $this->_fInput = isset($_SERVER["CONTENT_TYPE"]) ? $_SERVER["CONTENT_TYPE"] : '';
70  /* busco un posible formato de salida */
71  $accept = self::accept();
72  $keys = array_keys($this->_outputType);
73  foreach ($accept as $key => $a) {
74  if (in_array($key, $keys)) {
75  $this->_fOutput = $this->_outputType[$key];
76  break;
77  }
78  }
79  /* por defecto uso json
80  * ¿o debería mandar un 415?
81  */
82  $this->_fOutput = empty($this->_fOutput) ? 'json' : $this->_fOutput;
83  View::select(null, $this->_fOutput);
88  $action = $this->action_name;
89  $method = strtolower(Router::get('method'));
90  $rewrite = "{$method}_{$action}";
91  if ($this->actionExist($rewrite)) {
92  $this->action_name = $rewrite;
93  } elseif ($action == 'index' && $method != 'post') {
94  $this->action_name = 'getAll';
95  } else {
96  $this->action_name = $method;
97  $this->parameters = ($action == 'index') ? $this->parameters : array($action) + $this->parameters;
98  }
99  }
100 
106  protected function actionExist($name) {
107  if (method_exists($this, $name)) {
108  $reflection = new ReflectionMethod($this, $name);
109  return $reflection->isPublic();
110  }
111  return false;
112  }
113 
118  protected function param() {
119  $input = file_get_contents('php://input');
120  $format = $this->_fInput;
121  /* verifica si el formato tiene un parser válido */
122  if (isset($this->_inputType[$format]) && is_callable($this->_inputType[$format])) {
123  $result = call_user_func($this->_inputType[$format], $input);
124  if ($result) {
125  return $result;
126  }
127  }
128  return $input;
129  }
130 
135  protected function setCode($num) {
136  $code = array(
137  //Informational 1xx
138  100 => '100 Continue',
139  101 => '101 Switching Protocols',
140  //Successful 2xx
141  200 => '200 OK',
142  201 => '201 Created',
143  202 => '202 Accepted',
144  203 => '203 Non-Authoritative Information',
145  204 => '204 No Content',
146  205 => '205 Reset Content',
147  206 => '206 Partial Content',
148  //Redirection 3xx
149  300 => '300 Multiple Choices',
150  301 => '301 Moved Permanently',
151  302 => '302 Found',
152  303 => '303 See Other',
153  304 => '304 Not Modified',
154  305 => '305 Use Proxy',
155  306 => '306 (Unused)',
156  307 => '307 Temporary Redirect',
157  //Client Error 4xx
158  400 => '400 Bad Request',
159  401 => '401 Unauthorized',
160  402 => '402 Payment Required',
161  403 => '403 Forbidden',
162  404 => '404 Not Found',
163  405 => '405 Method Not Allowed',
164  406 => '406 Not Acceptable',
165  407 => '407 Proxy Authentication Required',
166  408 => '408 Request Timeout',
167  409 => '409 Conflict',
168  410 => '410 Gone',
169  411 => '411 Length Required',
170  412 => '412 Precondition Failed',
171  413 => '413 Request Entity Too Large',
172  414 => '414 Request-URI Too Long',
173  415 => '415 Unsupported Media Type',
174  416 => '416 Requested Range Not Satisfiable',
175  417 => '417 Expectation Failed',
176  422 => '422 Unprocessable Entity',
177  423 => '423 Locked',
178  //Server Error 5xx
179  500 => '500 Internal Server Error',
180  501 => '501 Not Implemented',
181  502 => '502 Bad Gateway',
182  503 => '503 Service Unavailable',
183  504 => '504 Gateway Timeout',
184  505 => '505 HTTP Version Not Supported'
185  );
186  if (isset($code[$num])) {
187  header(sprintf('HTTP/1.1 %d %s', $num, $code[$num]));
188  }
189  }
190 
196  static function accept() {
197  /* para almacenar los valores acceptados por el cliente */
198  $aTypes = array();
199  /* Elimina espacios, convierte a minusculas, y separa */
200  $accept = explode(',', strtolower(str_replace(' ', '', $_SERVER['HTTP_ACCEPT'])));
201  foreach ($accept as $a) {
202  $q = 1; /* Por defecto la proridad es uno, el siguiente verifica si es otra */
203  if (strpos($a, ';q=')) {
204  /* parte el "mime/type;q=X" en dos: "mime/type" y "X" */
205  list($a, $q) = explode(';q=', $a);
206  }
207  $aTypes[$a] = $q;
208  }
209  /* ordena por prioridad (mayor a menor) */
210  arsort($aTypes);
211  return $aTypes;
212  }
213 
221  protected static function parseJSON($input) {
222  if (function_exists('json_decode')) {
223  $result = json_decode($input, true);
224  if ($result) {
225  return $result;
226  }
227  }
228  }
229 
239  protected static function parseXML($input) {
240  if (class_exists('SimpleXMLElement')) {
241  try {
242  return new SimpleXMLElement($input);
243  } catch (Exception $e) {
244  // Do nothing
245  }
246  }
247 
248  return $input;
249  }
250 
259  protected static function parseCSV($input) {
260  $temp = fopen('php://memory', 'rw');
261  fwrite($temp, $input);
262  fseek($temp, 0);
263  $res = array();
264  while (($data = fgetcsv($temp)) !== false) {
265  $res[] = $data;
266  }
267  fclose($temp);
268  return $res;
269  }
270 
277  protected static function parseForm($input) {
278  parse_str($input, $vars);
279  return $vars;
280  }
281 
282 }