Ejemplo n.º 1
0
 public static function processRequest()
 {
     // What is the method used ?
     $request_method = strtolower($_SERVER['REQUEST_METHOD']);
     $request = new RestRequest();
     // Storing the requested data
     $data = array();
     switch ($request_method) {
         /* *** GET *** */
         case 'get':
             // Because of the htaccess ...
             // Extra parameters in the request URI
             $params = array();
             $parts = preg_split("~=|&~", $_SERVER['REQUEST_URI'], -1, PREG_SPLIT_NO_EMPTY);
             // Skip through the segments by 2
             for ($i = 0; $i < count($parts); $i = $i + 2) {
                 // First segment needs a lift because it contains the script name (method actually)
                 if ($i == 0) {
                     $parts[$i] = preg_replace("/(\\/[^\\?]*\\?)(.*)/", "\$2", $parts[$i]);
                 }
                 if (isset($parts[$i]) && isset($parts[$i + 1])) {
                     // First segment is the param name, second is the value
                     $params[$parts[$i]] = $parts[$i + 1];
                 }
             }
             $data = $params;
             $request->validateRequest();
             break;
             /* *** POST *** */
         /* *** POST *** */
         case 'post':
             $data = $_POST;
             $request->invalidateRequest();
             break;
             /* *** PUT *** */
         /* *** PUT *** */
         case 'put':
             // basically, we read a string from PHP's special input location,
             // and then parse it out into an array via parse_str... per the PHP docs:
             // Parses str  as if it were the query string passed via a URL and sets
             // variables in the current scope.
             parse_str(file_get_contents('php://input'), $put_vars);
             $data = $put_vars;
             $request->invalidateRequest();
             break;
     }
     // Storing the data into data (redundant for GET, but well)
     $request->setData((object) $data);
     // Storing the method used
     $request->setMethod($request_method);
     // Set the raw data, so we can access it if needed (there may be
     // other pieces to your requests)
     $request->setRequestVars($data);
     // If we have data (as per in a post request), we store it
     if (isset($data['data'])) {
         // translate the JSON to an Object for use however you want
         $request->setData(json_decode($data['data']));
     }
     // If we force JSON or XML instead of ACCEPT
     if (isset($data['alt']) && ($data['alt'] == 'json' || $data['alt'] == 'xml')) {
         $request->setHttpAccept($data['alt']);
     }
     return $request;
 }