/// * or // */ protected $args = Array(); /** * Property: file * Stores the input of the PUT request */ protected $file = Null; /** * Constructor: __construct * Allow for CORS, assemble and pre-process the data */ public function __construct($request) { $this->args = explode('/', rtrim($request, '/')); $this->endpoint = array_shift($this->args); if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) { $this->verb = array_shift($this->args); } $this->method = $_SERVER['REQUEST_METHOD']; if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) { if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') { $this->method = 'DELETE'; } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') { $this->method = 'PUT'; } else { throw new Exception("Unexpected header"); } } switch($this->method) { // @TODO: 200 only if authorization header present? // Preflight request case 'OPTIONS': $this->request = array(); $this->_response('Got it', 200); break; // Delete case 'DELETE': $this->request = $this->_cleanInputs($_GET); break; // Create case 'POST': $this->request = $this->_cleanInputs($_POST); break; // Read case 'GET': $this->request = $this->_cleanInputs($_GET); break; // Update case 'PUT': $this->request = $this->_cleanInputs($_GET); $this->file = file_get_contents("php://input"); break; default: $this->_response('Invalid method', 405); break; } } public function process() { if (method_exists($this, $this->endpoint)) { try { $this->log($this->args, $this->verb); return $this->_response($this->{$this->endpoint}($this->args, $this->verb)); } catch (Exception $e) { return $this->_response($e->getMessage(), 405); } } return $this->_response("No endpoint: $this->endpoint", 404); } private function _response($data, $status = 200) { header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status)); return json_encode($data); } private function _cleanInputs($data) { $clean_input = Array(); if (is_array($data)) { foreach ($data as $k => $v) { $clean_input[$k] = $this->_cleanInputs($v); } } else { $clean_input = trim($data);//trim(strip_tags($data)); } return $clean_input; } private function _requestStatus($code) { $status = array( 200 => 'OK', 404 => 'Not Found', 405 => 'Method Not Allowed', 500 => 'Internal Server Error', ); return ($status[$code])?$status[$code]:$status[500]; } } ?>