[625] | 1 | <?php |
---|
| 2 | |
---|
| 3 | /** |
---|
| 4 | * @class Request |
---|
| 5 | */ |
---|
| 6 | class Request { |
---|
| 7 | public $restful, $method, $controller, $action, $id, $params; |
---|
| 8 | public function __construct($params) { |
---|
| 9 | $this->restful = (isset($params["restful"])) ? $params["restful"] : false; |
---|
| 10 | $this->method = $_SERVER["REQUEST_METHOD"]; |
---|
| 11 | $this->parseRequest(); |
---|
| 12 | } |
---|
| 13 | public function isRestful() { |
---|
| 14 | return $this->restful; |
---|
| 15 | } |
---|
| 16 | public function to_string() { |
---|
| 17 | return "controller: " . $this->controller . ', action: ' . $this->action . ', id: ' . $this->id; |
---|
| 18 | } |
---|
| 19 | protected function parseRequest() { |
---|
| 20 | if ($this->method == 'PUT') { // <-- Have to jump through hoops to get PUT data |
---|
| 21 | $raw = ''; |
---|
| 22 | $httpContent = fopen('php://input', 'r'); |
---|
| 23 | while ($kb = fread($httpContent, 1024)) { |
---|
| 24 | $raw .= $kb; |
---|
| 25 | } |
---|
| 26 | fclose($httpContent); |
---|
| 27 | $params = array(); |
---|
| 28 | parse_str($raw, $params); |
---|
| 29 | $this->id = (isset($params['id'])) ? $params['id'] : null; |
---|
| 30 | $this->params = (isset($params['data'])) ? json_decode(stripslashes($params['data']), true) : null; |
---|
| 31 | } else { |
---|
| 32 | // grab JSON data if there... |
---|
| 33 | $this->params = (isset($_REQUEST['data'])) ? json_decode(stripslashes($_REQUEST['data']), true) : null; |
---|
| 34 | $this->id = (isset($_REQUEST['id'])) ? json_decode(stripslashes($_REQUEST['id']), true) : null; |
---|
| 35 | } |
---|
| 36 | // parse path info |
---|
| 37 | if (isset($_SERVER["PATH_INFO"])){ |
---|
| 38 | $cai = '/^\/([a-z]+\w)\/([a-z]+\w)\/([0-9]+)$/'; // /controller/action/id |
---|
| 39 | $ca = '/^\/([a-z]+\w)\/([a-z]+\w)$/'; // /controller/action |
---|
| 40 | $ci = '/^\/([a-z]+\w)\/([0-9]+)$/'; // /controller/id |
---|
| 41 | $c = '/^\/([a-z]+)$/'; // /controller |
---|
| 42 | $i = '/^\/([0-9]+)$/'; // /id |
---|
| 43 | $matches = array(); |
---|
| 44 | if (preg_match($cai, $_SERVER["PATH_INFO"], $matches)) { |
---|
| 45 | $this->controller = $matches[1]; |
---|
| 46 | $this->action = $matches[2]; |
---|
| 47 | $this->id = $matches[3]; |
---|
| 48 | } else if (preg_match($ca, $_SERVER["PATH_INFO"], $matches)) { |
---|
| 49 | $this->controller = $matches[1]; |
---|
| 50 | $this->action = $matches[2]; |
---|
| 51 | } else if (preg_match($ci, $_SERVER["PATH_INFO"], $matches)) { |
---|
| 52 | $this->controller = $matches[1]; |
---|
| 53 | $this->id = $matches[2]; |
---|
| 54 | } else if (preg_match($c, $_SERVER["PATH_INFO"], $matches)) { |
---|
| 55 | $this->controller = $matches[1]; |
---|
| 56 | } else if (preg_match($i, $_SERVER["PATH_INFO"], $matches)) { |
---|
| 57 | $this->id = $matches[1]; |
---|
| 58 | } |
---|
| 59 | } |
---|
| 60 | } |
---|
| 61 | } |
---|
| 62 | |
---|