95 lines
2.6 KiB
PHP
95 lines
2.6 KiB
PHP
<?php
|
||
/**
|
||
* This file is part of webman.
|
||
*
|
||
* Licensed under The MIT License
|
||
* For full copyright and license information, please see the MIT-LICENSE.txt
|
||
* Redistributions of files must retain the above copyright notice.
|
||
*
|
||
* @author walkor<walkor@workerman.net>
|
||
* @copyright walkor<walkor@workerman.net>
|
||
* @link http://www.workerman.net/
|
||
* @license http://www.opensource.org/licenses/mit-license.php MIT License
|
||
*/
|
||
|
||
namespace support;
|
||
|
||
/**
|
||
* Class Request
|
||
* @package support
|
||
*/
|
||
class Request extends \Webman\Http\Request
|
||
{
|
||
/** @var callable|null 参数过滤器,用于兼容 ThinkPHP 的 filter() */
|
||
protected $filter = null;
|
||
|
||
/**
|
||
* 获取请求路径(兼容 ThinkPHP:去除 index.php 前缀,使 /index.php/api/xxx 等价于 /api/xxx)
|
||
*/
|
||
public function path(): string
|
||
{
|
||
$path = parent::path();
|
||
if (str_starts_with($path, '/index.php')) {
|
||
$path = substr($path, 10) ?: '/';
|
||
}
|
||
return $path;
|
||
}
|
||
|
||
/**
|
||
* 获取请求参数(兼容 ThinkPHP param,合并 get/post,post 优先)
|
||
* @param string|null $name 参数名,null 返回全部
|
||
* @param mixed $default 默认值
|
||
* @return mixed
|
||
*/
|
||
public function param(?string $name = null, $default = null)
|
||
{
|
||
$data = $this->post() + $this->get();
|
||
if ($name === null) {
|
||
return $this->applyFilter($data);
|
||
}
|
||
if (!array_key_exists($name, $data)) {
|
||
return $default;
|
||
}
|
||
return $this->applyFilter($data[$name]);
|
||
}
|
||
|
||
/**
|
||
* 设置参数过滤器(兼容 ThinkPHP filter)
|
||
* @param string $filter 过滤器名,如 'clean_xss'、'trim'
|
||
* @return $this
|
||
*/
|
||
public function filter(string $filter)
|
||
{
|
||
if ($filter === 'clean_xss' && function_exists('clean_xss')) {
|
||
$this->filter = 'clean_xss';
|
||
} elseif ($filter === 'trim') {
|
||
$this->filter = 'trim';
|
||
} else {
|
||
$this->filter = null;
|
||
}
|
||
return $this;
|
||
}
|
||
|
||
/**
|
||
* 对值应用已设置的过滤器
|
||
*/
|
||
protected function applyFilter($value)
|
||
{
|
||
if ($this->filter === null) {
|
||
return $value;
|
||
}
|
||
if (is_array($value)) {
|
||
foreach ($value as $k => $v) {
|
||
$value[$k] = $this->applyFilter($v);
|
||
}
|
||
return $value;
|
||
}
|
||
if (is_string($value) && $this->filter === 'clean_xss') {
|
||
return clean_xss($value);
|
||
}
|
||
if (is_string($value) && $this->filter === 'trim') {
|
||
return trim($value);
|
||
}
|
||
return $value;
|
||
}
|
||
} |