diff --git a/app/Router/Collection.php b/app/Router/Collection.php index dc2fa08..a2ac4f6 100644 --- a/app/Router/Collection.php +++ b/app/Router/Collection.php @@ -56,20 +56,19 @@ class Collection /** * Resolve route by path and method. - * @param string $method - * @param string $path + * @param Request $request * @return mixed */ - public function resolve($method, $path) + public function resolve(Request $request) { - $path = trim(parse_url($path, PHP_URL_PATH), '/'); + $path = trim(parse_url($request->path, PHP_URL_PATH), '/'); - if (!array_key_exists($method, $this->paths) - || !array_key_exists($path, $this->paths[$method])) { + if (!array_key_exists($request->method, $this->paths) + || !array_key_exists($path, $this->paths[$request->method])) { throw new \Exception; } - return $this->paths[$method][$path]->fire(); + return $this->paths[$request->method][$path]->fire(); } /** diff --git a/app/Router/Request.php b/app/Router/Request.php new file mode 100644 index 0000000..e05a546 --- /dev/null +++ b/app/Router/Request.php @@ -0,0 +1,77 @@ + + */ +class Request +{ + public $path; + public $method; + public $query; + public $data; + public $body; + public $ip; + public $accept; + public $charset; + public $language; + public $host; + public $referrer; + public $agent; + public $secure; + public $username; + public $password; + + public static function fromServer($server, $get, $post) + { + $instance = new static; + + $instance->path = $server['REQUEST_URI']; + $instance->method = $server['REQUEST_METHOD']; + $instance->query = $get ?? []; + $instance->data = $post ?? []; + $instance->body = file_get_contents('php://input'); + $instance->ip = $server['REMOTE_ADDR']; + $instance->accept = self::parseAcceptHeader($server['HTTP_ACCEPT'] ?? ''); + $instance->charset = $server['HTTP_ACCEPT_CHARSET'] ?? 'utf-8'; + $instance->language = self::parseAcceptHeader($server['HTTP_ACCEPT_LANGUAGE'] ?? 'en'); + $instance->host = $server['HTTP_HOST']; + $instance->referrer = $server['HTTP_REFERER'] ?? null; + $instance->agent = $server['HTTP_USER_AGENT'] ?? ''; + $instance->secure = $server['HTTPS'] ?? null === '1'; + $instance->username = $server['PHP_AUTH_USER'] ?? null; + $instance->password = $server['PHP_AUTH_PW'] ?? null; + + return $instance; + } + + private static function parseAcceptHeader($header) + { + $accepted = []; + $header = explode(',', strtolower($header)); + + foreach ($header as $accepts) { + $quality = 1; + + if (strpos($accepts, ';q=')) { + list($accepts, $quality) = explode(';q=', $accepts); + } + + // if the quality is 0 its not supported + if ($quality === 0) { + continue; + } + + $accepted[$accepts] = $quality; + } + + return $accepted; + } +}