<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think;
use ArrayAccess;
use think\file\UploadedFile;
use think\route\Rule;
class Request implements ArrayAccess
{
protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
protected $varPathinfo = 's';
protected $varMethod = '_method';
protected $varAjax = '_ajax';
protected $varPjax = '_pjax';
protected $rootDomain = '';
protected $httpsAgentName = '';
protected $proxyServerIp = [];
protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
protected $method;
protected $domain;
protected $host;
protected $subDomain;
protected $panDomain;
protected $url;
protected $baseUrl;
protected $baseFile;
protected $root;
protected $pathinfo;
protected $path;
protected $realIP;
protected $controller;
protected $action;
protected $param = [];
protected $get = [];
protected $post = [];
protected $request = [];
protected $rule;
protected $route = [];
protected $middleware = [];
protected $put;
protected $session;
protected $cookie = [];
protected $env;
protected $server = [];
protected $file = [];
protected $header = [];
protected $mimeType = [
'xml' => 'application/xml,text/xml,application/x-xml',
'json' => 'application/json,text/x-json,application/jsonrequest,text/json',
'js' => 'text/javascript,application/javascript,application/x-javascript',
'css' => 'text/css',
'rss' => 'application/rss+xml',
'yaml' => 'application/x-yaml,text/yaml',
'atom' => 'application/atom+xml',
'pdf' => 'application/pdf',
'text' => 'text/plain',
'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image*',
];
protected $content;
protected $filter;
protected $input;
protected $secureKey;
protected $mergeParam = false;
public function __construct()
{
$this->input = file_get_contents('php://input');
}
public static function __make(App $app)
{
$request = new static();
if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
$header = $result;
} else {
$header = [];
$server = $_SERVER;
foreach ($server as $key => $val) {
if (0 === strpos($key, 'HTTP_')) {
$key = str_replace('_', '-', strtolower(substr($key, 5)));
$header[$key] = $val;
}
}
if (isset($server['CONTENT_TYPE'])) {
$header['content-type'] = $server['CONTENT_TYPE'];
}
if (isset($server['CONTENT_LENGTH'])) {
$header['content-length'] = $server['CONTENT_LENGTH'];
}
}
$request->header = array_change_key_case($header);
$request->server = $_SERVER;
$request->env = $app->env;
$inputData = $request->getInputData($request->input);
$request->get = $_GET;
$request->post = $_POST ?: $inputData;
$request->put = $inputData;
$request->request = $_REQUEST;
$request->cookie = $_COOKIE;
$request->file = $_FILES ?? [];
return $request;
}
public function setDomain(string $domain)
{
$this->domain = $domain;
return $this;
}
public function domain(bool $port = false): string
{
return $this->scheme() . '://' . $this->host($port);
}
public function rootDomain(): string
{
$root = $this->rootDomain;
if (!$root) {
$item = explode('.', $this->host());
$count = count($item);
$root = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
}
return $root;
}
public function setSubDomain(string $domain)
{
$this->subDomain = $domain;
return $this;
}
public function subDomain(): string
{
if (is_null($this->subDomain)) {
$rootDomain = $this->rootDomain();
if ($rootDomain) {
$this->subDomain = rtrim(stristr($this->host(), $rootDomain, true), '.');
} else {
$this->subDomain = '';
}
}
return $this->subDomain;
}
public function setPanDomain(string $domain)
{
$this->panDomain = $domain;
return $this;
}
public function panDomain(): string
{
return $this->panDomain ?: '';
}
public function setUrl(string $url)
{
$this->url = $url;
return $this;
}
public function url(bool $complete = false): string
{
if ($this->url) {
$url = $this->url;
} elseif ($this->server('HTTP_X_REWRITE_URL')) {
$url = $this->server('HTTP_X_REWRITE_URL');
} elseif ($this->server('REQUEST_URI')) {
$url = $this->server('REQUEST_URI');
} elseif ($this->server('ORIG_PATH_INFO')) {
$url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
} elseif (isset($_SERVER['argv'][1])) {
$url = $_SERVER['argv'][1];
} else {
$url = '';
}
return $complete ? $this->domain() . $url : $url;
}
public function setBaseUrl(string $url)
{
$this->baseUrl = $url;
return $this;
}
public function baseUrl(bool $complete = false): string
{
if (!$this->baseUrl) {
$str = $this->url();
$this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
}
return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
}
public function baseFile(bool $complete = false): string
{
if (!$this->baseFile) {
$url = '';
if (!$this->isCli()) {
$script_name = basename($this->server('SCRIPT_FILENAME'));
if (basename($this->server('SCRIPT_NAME')) === $script_name) {
$url = $this->server('SCRIPT_NAME');
} elseif (basename($this->server('PHP_SELF')) === $script_name) {
$url = $this->server('PHP_SELF');
} elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
$url = $this->server('ORIG_SCRIPT_NAME');
} elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
$url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
} elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
$url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
}
}
$this->baseFile = $url;
}
return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
}
public function setRoot(string $url)
{
$this->root = $url;
return $this;
}
public function root(bool $complete = false): string
{
if (!$this->root) {
$file = $this->baseFile();
if ($file && 0 !== strpos($this->url(), $file)) {
$file = str_replace('\\', '/', dirname($file));
}
$this->root = rtrim($file, '/');
}
return $complete ? $this->domain() . $this->root : $this->root;
}
public function rootUrl(): string
{
$base = $this->root();
$root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
if ('' != $root) {
$root = '/' . ltrim($root, '/');
}
return $root;
}
public function setPathinfo(string $pathinfo)
{
$this->pathinfo = $pathinfo;
return $this;
}
public function pathinfo(): string
{
if (is_null($this->pathinfo)) {
if (isset($_GET[$this->varPathinfo])) {
$pathinfo = $_GET[$this->varPathinfo];
unset($_GET[$this->varPathinfo]);
unset($this->get[$this->varPathinfo]);
} elseif ($this->server('PATH_INFO')) {
$pathinfo = $this->server('PATH_INFO');
} elseif (false !== strpos(PHP_SAPI, 'cli')) {
$pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
}
if (!isset($pathinfo)) {
foreach ($this->pathinfoFetch as $type) {
if ($this->server($type)) {
$pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
break;
}
}
}
if (!empty($pathinfo)) {
unset($this->get[$pathinfo], $this->request[$pathinfo]);
}
$this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
}
return $this->pathinfo;
}
public function ext(): string
{
return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
}
public function time(bool $float = false)
{
return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
}
public function type(): string
{
$accept = $this->server('HTTP_ACCEPT');
if (empty($accept)) {
return '';
}
foreach ($this->mimeType as $key => $val) {
$array = explode(',', $val);
foreach ($array as $k => $v) {
if (stristr($accept, $v)) {
return $key;
}
}
}
return '';
}
public function mimeType($type, $val = ''): void
{
if (is_array($type)) {
$this->mimeType = array_merge($this->mimeType, $type);
} else {
$this->mimeType[$type] = $val;
}
}
public function setMethod(string $method)
{
$this->method = strtoupper($method);
return $this;
}
public function method(bool $origin = false): string
{
if ($origin) {
return $this->server('REQUEST_METHOD') ?: 'GET';
} elseif (!$this->method) {
if (isset($this->post[$this->varMethod])) {
$method = strtolower($this->post[$this->varMethod]);
if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
$this->method = strtoupper($method);
$this->{$method} = $this->post;
} else {
$this->method = 'POST';
}
unset($this->post[$this->varMethod]);
} elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
} else {
$this->method = $this->server('REQUEST_METHOD') ?: 'GET';
}
}
return $this->method;
}
public function isGet(): bool
{
return $this->method() == 'GET';
}
public function isPost(): bool
{
return $this->method() == 'POST';
}
public function isPut(): bool
{
return $this->method() == 'PUT';
}
public function isDelete(): bool
{
return $this->method() == 'DELETE';
}
public function isHead(): bool
{
return $this->method() == 'HEAD';
}
public function isPatch(): bool
{
return $this->method() == 'PATCH';
}
public function isOptions(): bool
{
return $this->method() == 'OPTIONS';
}
public function isCli(): bool
{
return PHP_SAPI == 'cli';
}
public function isCgi(): bool
{
return strpos(PHP_SAPI, 'cgi') === 0;
}
public function param($name = '', $default = null, $filter = '')
{
if (empty($this->mergeParam)) {
$method = $this->method(true);
switch ($method) {
case 'POST':
$vars = $this->post(false);
break;
case 'PUT':
case 'DELETE':
case 'PATCH':
$vars = $this->put(false);
break;
default:
$vars = [];
}
$this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
$this->mergeParam = true;
}
if (is_array($name)) {
return $this->only($name, $this->param, $filter);
}
return $this->input($this->param, $name, $default, $filter);
}
public function setRule(Rule $rule)
{
$this->rule = $rule;
return $this;
}
public function rule()
{
return $this->rule;
}
public function setRoute(array $route)
{
$this->route = array_merge($this->route, $route);
$this->mergeParam = false;
return $this;
}
public function route($name = '', $default = null, $filter = '')
{
if (is_array($name)) {
return $this->only($name, $this->route, $filter);
}
return $this->input($this->route, $name, $default, $filter);
}
public function get($name = '', $default = null, $filter = '')
{
if (is_array($name)) {
return $this->only($name, $this->get, $filter);
}
return $this->input($this->get, $name, $default, $filter);
}
public function middleware($name, $default = null)
{
return $this->middleware[$name] ?? $default;
}
public function post($name = '', $default = null, $filter = '')
{
if (is_array($name)) {
return $this->only($name, $this->post, $filter);
}
return $this->input($this->post, $name, $default, $filter);
}
public function put($name = '', $default = null, $filter = '')
{
if (is_array($name)) {
return $this->only($name, $this->put, $filter);
}
return $this->input($this->put, $name, $default, $filter);
}
protected function getInputData($content): array
{
$contentType = $this->contentType();
if ('application/x-www-form-urlencoded' == $contentType) {
parse_str($content, $data);
return $data;
} elseif (false !== strpos($contentType, 'json')) {
return (array) json_decode($content, true);
}
return [];
}
public function delete($name = '', $default = null, $filter = '')
{
return $this->put($name, $default, $filter);
}
public function patch($name = '', $default = null, $filter = '')
{
return $this->put($name, $default, $filter);
}
public function request($name = '', $default = null, $filter = '')
{
if (is_array($name)) {
return $this->only($name, $this->request, $filter);
}
return $this->input($this->request, $name, $default, $filter);
}
public function env(string $name = '', string $default = null)
{
if (empty($name)) {
return $this->env->get();
} else {
$name = strtoupper($name);
}
return $this->env->get($name, $default);
}
public function session(string $name = '', $default = null)
{
if ('' === $name) {
return $this->session->all();
}
return $this->session->get($name, $default);
}
public function cookie(string $name = '', $default = null, $filter = '')
{
if (!empty($name)) {
$data = $this->getData($this->cookie, $name, $default);
} else {
$data = $this->cookie;
}
$filter = $this->getFilter($filter, $default);
if (is_array($data)) {
array_walk_recursive($data, [$this, 'filterValue'], $filter);
} else {
$this->filterValue($data, $name, $filter);
}
return $data;
}
public function server(string $name = '', string $default = '')
{
if (empty($name)) {
return $this->server;
} else {
$name = strtoupper($name);
}
return $this->server[$name] ?? $default;
}
public function file(string $name = '')
{
$files = $this->file;
if (!empty($files)) {
if (strpos($name, '.')) {
[$name, $sub] = explode('.', $name);
}
$array = $this->dealUploadFile($files, $name);
if ('' === $name) {
return $array;
} elseif (isset($sub) && isset($array[$name][$sub])) {
return $array[$name][$sub];
} elseif (isset($array[$name])) {
return $array[$name];
}
}
}
protected function dealUploadFile(array $files, string $name): array
{
$array = [];
foreach ($files as $key => $file) {
if (is_array($file['name'])) {
$item = [];
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
if ($file['error'][$i] > 0) {
if ($name == $key) {
$this->throwUploadFileError($file['error'][$i]);
} else {
continue;
}
}
$temp['key'] = $key;
foreach ($keys as $_key) {
$temp[$_key] = $file[$_key][$i];
}
$item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
}
$array[$key] = $item;
} else {
if ($file instanceof File) {
$array[$key] = $file;
} else {
if ($file['error'] > 0) {
if ($key == $name) {
$this->throwUploadFileError($file['error']);
} else {
continue;
}
}
$array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
}
}
}
return $array;
}
protected function throwUploadFileError($error)
{
static $fileUploadErrors = [
1 => 'upload File size exceeds the maximum value',
2 => 'upload File size exceeds the maximum value',
3 => 'only the portion of file is uploaded',
4 => 'no file to uploaded',
6 => 'upload temp dir not found',
7 => 'file write error',
];
$msg = $fileUploadErrors[$error];
throw new Exception($msg, $error);
}
public function header(string $name = '', string $default = null)
{
if ('' === $name) {
return $this->header;
}
$name = str_replace('_', '-', strtolower($name));
return $this->header[$name] ?? $default;
}
public function input(array $data = [], $name = '', $default = null, $filter = '')
{
if (false === $name) {
return $data;
}
$name = (string) $name;
if ('' != $name) {
if (strpos($name, '/')) {
[$name, $type] = explode('/', $name);
}
$data = $this->getData($data, $name);
if (is_null($data)) {
return $default;
}
if (is_object($data)) {
return $data;
}
}
$data = $this->filterData($data, $filter, $name, $default);
if (isset($type) && $data !== $default) {
$this->typeCast($data, $type);
}
return $data;
}
protected function filterData($data, $filter, $name, $default)
{
$filter = $this->getFilter($filter, $default);
if (is_array($data)) {
array_walk_recursive($data, [$this, 'filterValue'], $filter);
} else {
$this->filterValue($data, $name, $filter);
}
return $data;
}
private function typeCast(&$data, string $type)
{
switch (strtolower($type)) {
case 'a':
$data = (array) $data;
break;
case 'd':
$data = (int) $data;
break;
case 'f':
$data = (float) $data;
break;
case 'b':
$data = (boolean) $data;
break;
case 's':
if (is_scalar($data)) {
$data = (string) $data;
} else {
throw new \InvalidArgumentException('variable type error:' . gettype($data));
}
break;
}
}
protected function getData(array $data, string $name, $default = null)
{
foreach (explode('.', $name) as $val) {
if (isset($data[$val])) {
$data = $data[$val];
} else {
return $default;
}
}
return $data;
}
public function filter($filter = null)
{
if (is_null($filter)) {
return $this->filter;
}
$this->filter = $filter;
return $this;
}
protected function getFilter($filter, $default): array
{
if (is_null($filter)) {
$filter = [];
} else {
$filter = $filter ?: $this->filter;
if (is_string($filter) && false === strpos($filter, '/')) {
$filter = explode(',', $filter);
} else {
$filter = (array) $filter;
}
}
$filter[] = $default;
return $filter;
}
public function filterValue(&$value, $key, $filters)
{
$default = array_pop($filters);
foreach ($filters as $filter) {
if (is_callable($filter)) {
$value = call_user_func($filter, $value);
} elseif (is_scalar($value)) {
if (is_string($filter) && false !== strpos($filter, '/')) {
if (!preg_match($filter, $value)) {
$value = $default;
break;
}
} elseif (!empty($filter)) {
$value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
if (false === $value) {
$value = $default;
break;
}
}
}
}
return $value;
}
public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
{
if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
return false;
}
$param = empty($this->$type) ? $this->$type() : $this->$type;
if (is_object($param)) {
return $param->has($name);
}
foreach (explode('.', $name) as $val) {
if (isset($param[$val])) {
$param = $param[$val];
} else {
return false;
}
}
return ($checkEmpty && '' === $param) ? false : true;
}
public function only(array $name, $data = 'param', $filter = ''): array
{
$data = is_array($data) ? $data : $this->$data();
$item = [];
foreach ($name as $key => $val) {
if (is_int($key)) {
$default = null;
$key = $val;
if (!isset($data[$key])) {
continue;
}
} else {
$default = $val;
}
$item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
}
return $item;
}
public function except(array $name, string $type = 'param'): array
{
$param = $this->$type();
foreach ($name as $key) {
if (isset($param[$key])) {
unset($param[$key]);
}
}
return $param;
}
public function isSsl(): bool
{
if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
return true;
} elseif ('https' == $this->server('REQUEST_SCHEME')) {
return true;
} elseif ('443' == $this->server('SERVER_PORT')) {
return true;
} elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
return true;
} elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
return true;
}
return false;
}
public function isJson(): bool
{
$acceptType = $this->type();
return false !== strpos($acceptType, 'json');
}
public function isAjax(bool $ajax = false): bool
{
$value = $this->server('HTTP_X_REQUESTED_WITH');
$result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
if (true === $ajax) {
return $result;
}
return $this->param($this->varAjax) ? true : $result;
}
public function isPjax(bool $pjax = false): bool
{
$result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
if (true === $pjax) {
return $result;
}
return $this->param($this->varPjax) ? true : $result;
}
public function ip(): string
{
if (!empty($this->realIP)) {
return $this->realIP;
}
$this->realIP = $this->server('REMOTE_ADDR', '');
$proxyIp = $this->proxyServerIp;
$proxyIpHeader = $this->proxyServerIpHeader;
if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
foreach ($proxyIpHeader as $header) {
$tempIP = $this->server($header);
if (empty($tempIP)) {
continue;
}
$tempIP = trim(explode(',', $tempIP)[0]);
if (!$this->isValidIP($tempIP)) {
$tempIP = null;
} else {
break;
}
}
if (!empty($tempIP)) {
$realIPBin = $this->ip2bin($this->realIP);
foreach ($proxyIp as $ip) {
$serverIPElements = explode('/', $ip);
$serverIP = $serverIPElements[0];
$serverIPPrefix = $serverIPElements[1] ?? 128;
$serverIPBin = $this->ip2bin($serverIP);
if (strlen($realIPBin) !== strlen($serverIPBin)) {
continue;
}
if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
$this->realIP = $tempIP;
break;
}
}
}
}
if (!$this->isValidIP($this->realIP)) {
$this->realIP = '0.0.0.0';
}
return $this->realIP;
}
public function isValidIP(string $ip, string $type = ''): bool
{
switch (strtolower($type)) {
case 'ipv4':
$flag = FILTER_FLAG_IPV4;
break;
case 'ipv6':
$flag = FILTER_FLAG_IPV6;
break;
default:
$flag = null;
break;
}
return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
}
public function ip2bin(string $ip): string
{
if ($this->isValidIP($ip, 'ipv6')) {
$IPHex = str_split(bin2hex(inet_pton($ip)), 4);
foreach ($IPHex as $key => $value) {
$IPHex[$key] = intval($value, 16);
}
$IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
} else {
$IPHex = str_split(bin2hex(inet_pton($ip)), 2);
foreach ($IPHex as $key => $value) {
$IPHex[$key] = intval($value, 16);
}
$IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
}
return $IPBin;
}
public function isMobile(): bool
{
if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
return true;
} elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
return true;
} elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
return true;
} elseif ($this->server('HTTP_USER_AGENT') && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $this->server('HTTP_USER_AGENT'))) {
return true;
}
return false;
}
public function scheme(): string
{
return $this->isSsl() ? 'https' : 'http';
}
public function query(): string
{
return $this->server('QUERY_STRING', '');
}
public function setHost(string $host)
{
$this->host = $host;
return $this;
}
public function host(bool $strict = false): string
{
if ($this->host) {
$host = $this->host;
} else {
$host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
}
return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
}
public function port(): int
{
return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
}
public function protocol(): string
{
return $this->server('SERVER_PROTOCOL', '');
}
public function remotePort(): int
{
return (int) $this->server('REMOTE_PORT', '');
}
public function contentType(): string
{
$contentType = $this->header('Content-Type');
if ($contentType) {
if (strpos($contentType, ';')) {
[$type] = explode(';', $contentType);
} else {
$type = $contentType;
}
return trim($type);
}
return '';
}
public function secureKey(): string
{
if (is_null($this->secureKey)) {
$this->secureKey = uniqid('', true);
}
return $this->secureKey;
}
public function setController(string $controller)
{
$this->controller = $controller;
return $this;
}
public function setAction(string $action)
{
$this->action = $action;
return $this;
}
public function controller(bool $convert = false): string
{
$name = $this->controller ?: '';
return $convert ? strtolower($name) : $name;
}
public function action(bool $convert = false): string
{
$name = $this->action ?: '';
return $convert ? strtolower($name) : $name;
}
public function getContent(): string
{
if (is_null($this->content)) {
$this->content = $this->input;
}
return $this->content;
}
public function getInput(): string
{
return $this->input;
}
public function buildToken(string $name = '__token__', $type = 'md5'): string
{
$type = is_callable($type) ? $type : 'md5';
$token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
$this->session->set($name, $token);
return $token;
}
public function checkToken(string $token = '__token__', array $data = []): bool
{
if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
return true;
}
if (!$this->session->has($token)) {
return false;
}
if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
$this->session->delete($token); return true;
}
if (empty($data)) {
$data = $this->post();
}
if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
$this->session->delete($token); return true;
}
$this->session->delete($token);
return false;
}
public function withMiddleware(array $middleware)
{
$this->middleware = array_merge($this->middleware, $middleware);
return $this;
}
public function withGet(array $get)
{
$this->get = $get;
return $this;
}
public function withPost(array $post)
{
$this->post = $post;
return $this;
}
public function withCookie(array $cookie)
{
$this->cookie = $cookie;
return $this;
}
public function withSession(Session $session)
{
$this->session = $session;
return $this;
}
public function withServer(array $server)
{
$this->server = array_change_key_case($server, CASE_UPPER);
return $this;
}
public function withHeader(array $header)
{
$this->header = array_change_key_case($header);
return $this;
}
public function withEnv(Env $env)
{
$this->env = $env;
return $this;
}
public function withInput(string $input)
{
$this->input = $input;
if (!empty($input)) {
$inputData = $this->getInputData($input);
if (!empty($inputData)) {
$this->post = $inputData;
$this->put = $inputData;
}
}
return $this;
}
public function withFiles(array $files)
{
$this->file = $files;
return $this;
}
public function withRoute(array $route)
{
$this->route = $route;
return $this;
}
public function __set(string $name, $value)
{
$this->middleware[$name] = $value;
}
public function __get(string $name)
{
return $this->middleware($name);
}
public function __isset(string $name): bool
{
return isset($this->middleware[$name]);
}
public function offsetExists($name): bool
{
return $this->has($name);
}
public function offsetGet($name)
{
return $this->param($name);
}
public function offsetSet($name, $value)
{}
public function offsetUnset($name)
{}
}