request.class.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Juju\Http;
  3. require_once('uri.class.php');
  4. class Request implements \JsonSerializable {
  5. private $verb;
  6. private $url;
  7. private $headers;
  8. private $body;
  9. public function __construct($verb, $url, array $headers = [], string $body = ''){
  10. if(is_string($url) || is_array($url)){
  11. $this->url = new Uri($url);
  12. }elseif($url instanceof Uri){
  13. $this->url = $url;
  14. }else{
  15. throw new \Exception("Invalid url {$url}");
  16. }
  17. if(is_array($headers)){
  18. $this->headers = $headers;
  19. }else{
  20. $this->headers = [];
  21. }
  22. $this->verb = $verb;
  23. $this->body = $body;
  24. }
  25. public function __get($name){
  26. switch($name){
  27. case 'headers':case 'url':case 'body':case 'verb':
  28. return $this->$name;
  29. break;
  30. case 'locale':
  31. return \Locale::acceptFromHttp($this->header('Accept-Language'));
  32. break;
  33. }
  34. }
  35. public function jsonSerialize(){
  36. return [
  37. 'verb'=> $this->verb,
  38. 'url'=> $this->url,
  39. 'headers'=> $this->headers,
  40. 'body'=> $this->body
  41. ];
  42. }
  43. public function header($name){
  44. return $this->headers[$name] ?? null;
  45. }
  46. public function text(){
  47. return $this->body;
  48. }
  49. public function json(bool $assoc = true){
  50. return json_decode($this->body, $assoc);
  51. }
  52. public function xml(string $classname = 'SimpleXMLElement', int $options, string $ns = '', bool $is_prefix = false){
  53. return simplexml_load_string($this->body, $classname, $options, $ns, $is_prefix);
  54. }
  55. public function msgpack(){
  56. if(!extension_loaded("msgpack")){
  57. throw new \Exception("Unable to load msgpack extension");
  58. }
  59. return msgpack_unpack($this->body);
  60. }
  61. public static function get_url(){
  62. $url = $_SERVER['REDIRECT_URL'] ?? $_SERVER['REQUEST_URI'];
  63. if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])){
  64. $root = $_SERVER['HTTP_X_FORWARDED_PROTO'].'://';
  65. }else{
  66. $root = !empty($_SERVER['HTTPS']) ? "https://" : "http://";
  67. }
  68. // @todo - determine if http or http and also check cloudflare
  69. return parse_url($root.$_SERVER['HTTP_HOST'].$url);
  70. }
  71. public static function get_headers(){
  72. return getallheaders();
  73. }
  74. public static function get_body(){
  75. return file_get_contents( 'php://input','r');
  76. }
  77. public static function get_verb(){
  78. return $_SERVER['REQUEST_METHOD'];
  79. }
  80. public static function get_locale(){
  81. Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  82. }
  83. }
  84. ?>