Files
2026-03-18 11:22:12 +08:00

95 lines
2.6 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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/postpost 优先)
* @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;
}
}