12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace Juju\Http;
- require_once('uri.class.php');
- class Request implements \JsonSerializable {
- private $verb;
- private $url;
- private $headers;
- private $body;
- public function __construct($verb, $url, array $headers = [], string $body = ''){
- if(is_string($url) || is_array($url)){
- $this->url = new Uri($url);
- }elseif($url instanceof Uri){
- $this->url = $url;
- }else{
- throw new \Exception("Invalid url {$url}");
- }
- if(is_array($headers)){
- $this->headers = $headers;
- }else{
- $this->headers = [];
- }
- $this->verb = $verb;
- $this->body = $body;
- }
- public function __get($name){
- switch($name){
- case 'headers':case 'url':case 'body':case 'verb':
- return $this->$name;
- break;
- case 'locale':
- return \Locale::acceptFromHttp($this->header('Accept-Language'));
- break;
- }
- }
- public function jsonSerialize(){
- return [
- 'verb'=> $this->verb,
- 'url'=> $this->url,
- 'headers'=> $this->headers,
- 'body'=> $this->body
- ];
- }
- public function header($name){
- return $this->headers[$name] ?? null;
- }
- public function text(){
- return $this->body;
- }
- public function json(bool $assoc = true){
- return json_decode($this->body, $assoc);
- }
- public function xml(string $classname = 'SimpleXMLElement', int $options, string $ns = '', bool $is_prefix = false){
- return simplexml_load_string($this->body, $classname, $options, $ns, $is_prefix);
- }
- public function msgpack(){
- if(!extension_loaded("msgpack")){
- throw new \Exception("Unable to load msgpack extension");
- }
- return msgpack_unpack($this->body);
- }
- public static function get_url(){
- $url = $_SERVER['REDIRECT_URL'] ?? $_SERVER['REQUEST_URI'];
- if(!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])){
- $root = $_SERVER['HTTP_X_FORWARDED_PROTO'].'://';
- }else{
- $root = !empty($_SERVER['HTTPS']) ? "https://" : "http://";
- }
- // @todo - determine if http or http and also check cloudflare
- return parse_url($root.$_SERVER['HTTP_HOST'].$url);
- }
- public static function get_headers(){
- return getallheaders();
- }
- public static function get_body(){
- return file_get_contents( 'php://input','r');
- }
- public static function get_verb(){
- return $_SERVER['REQUEST_METHOD'];
- }
- public static function get_locale(){
- Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
- }
- }
- ?>
|