Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Donate
Please sign in before you donate.
Scan WeChat QR to Pay
Cancel
Complete
Prompt
Switch to Alipay.
OK
Cancel
1 Star 2 Fork 2

MADONG/Query

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
main
Branches (1)
Tags (1)
main
v1.0.1
main
Branches (1)
Tags (1)
main
v1.0.1
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
main
Branches (1)
Tags (1)
main
v1.0.1
query
/
src
/
QuerySelectHelper.php
query
/
src
/
QuerySelectHelper.php
QuerySelectHelper.php 16.26 KB
Copy Edit Raw Blame History
Mr.April authored 2026年03月11日 11:46 +08:00 . initial commit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
<?php
/**
*+------------------
* madong
*+------------------
* Copyright (c) https://gitee.com/motion-code All rights reserved.
*+------------------
* Author: Mr. April (405784684@qq.com)
*+------------------
* Official Website: http://www.madong.tech
*/
namespace madong\query;
use Illuminate\Database\Eloquent\Model;
use madong\helper\DateTime;
use madong\helper\Arr;
/**
* QuerySelect 辅助类
* 提供灵活的参数解析和过滤功能
*/
class QuerySelectHelper
{
/**
* 配置对象
* @var QuerySelectConfig
*/
private QuerySelectConfig $config;
/**
* 数据库字段列表
* @var array
*/
private array $dbFields = [];
/**
* 构造函数
*
* @param \madong\query\QuerySelectConfig $config
* @param array $dbFields
*/
public function __construct(QuerySelectConfig $config, array $dbFields = [])
{
$this->config = $config;
$this->dbFields = $dbFields;
}
/**
* 处理输入参数
*
* @param array $input
* @param Model|null $model
* @return array|object
*/
public function process(array $input, ?Model $model = null): object|array
{
// 获取数据库字段
if ($model && empty($this->dbFields)) {
$this->dbFields = $model->getFields();
}
// 解析基本参数
$field = $this->parseField($input);
$format = $this->parseFormat($input);
$limit = $this->parseLimit($input);
$page = $this->parsePage($input);
$order = $this->parseSort($input);
// 解析查询条件
$where = $this->parseWhere($input);
// 解析自定义字段
$customFields = $this->parseCustomFields($input);
// 构建结果
$result = array_merge($customFields, [
'where' => $where,
'format' => $format,
'limit' => $limit,
'field' => $field,
'order' => $order,
'page' => $page,
]);
// 添加配置到结果(如果需要)
if ($this->config->isDebugMode()) {
$result['_config'] = $this->config->toArray();
$result['_original_input'] = $input;
}
// 根据返回格式处理
return $this->formatResult($result);
}
/**
* 解析字段参数
*
* @param array $input
* @return string
*/
private function parseField(array $input): string
{
$field = $input['field'] ?? '*';
// 检查字段是否在允许列表中
if (!empty($this->config->getAllowedFields())) {
$allowed = $this->config->getAllowedFields();
if ($field !== '*' && !in_array($field, $allowed, true)) {
return '*';
}
}
// 检查字段是否在数据库字段中
if ($field !== '*' && !empty($this->dbFields)) {
if (!in_array($field, $this->dbFields, true)) {
return '*';
}
}
return $field;
}
/**
* 解析格式参数
*
* @param array $input
* @return string
*/
private function parseFormat(array $input): string
{
return $input['format'] ?? 'normal';
}
/**
* 解析限制参数
*
* @param array $input
* @return int
*/
private function parseLimit(array $input): int
{
$format = $input['format'] ?? 'normal';
$defaultLimit = $format === 'tree' ? 10000 : $this->config->getDefaultPageSize();
$limit = (int)($input['limit'] ?? $defaultLimit);
$limit = max(1, $limit);
$limit = min($limit, $this->config->getMaxPageSize());
return $limit;
}
/**
* 解析页码参数
*
* @param array $input
* @return int
*/
private function parsePage(array $input): int
{
$page = (int)($input['page'] ?? $this->config->getDefaultPage());
return max(1, $page);
}
/**
* 解析排序参数
*
* @param array $input
* @return string
*/
private function parseSort(array $input): string
{
$orders = [];
// 获取排序字段白名单
$sortFields = $this->config->getSortFields() ?? $this->dbFields;
// 场景1: order=id 或 order=id desc
if (isset($input['order']) && !isset($input['sort']) && !isset($input['orderBy'])) {
$orderValue = $input['order'];
$parts = explode(' ', $orderValue, 2);
$field = $parts[0];
$direction = strtolower($parts[1] ?? 'desc');
if (in_array($field, $sortFields)) {
$orders[] = "$field$direction";
}
}
// 场景2: sort=id:asc,create_time:desc 或 sort[]=id:asc&sort[]=create_time:desc
if (isset($input['sort'])) {
$sortValues = is_array($input['sort']) ? $input['sort'] : explode(',', $input['sort']);
foreach ($sortValues as $sortValue) {
$parts = explode(':', trim($sortValue), 2);
$field = $parts[0];
$direction = strtolower($parts[1] ?? 'desc');
if (in_array($field, $sortFields)) {
$orders[] = "$field$direction";
}
}
}
// 场景3: orderBy=id&orderDirection=desc (兼容旧版)
if (isset($input['orderBy']) && !isset($input['sort']) && empty($orders)) {
$field = $input['orderBy'];
$direction = strtolower($input['orderDirection'] ?? 'desc');
if (in_array($field, $sortFields)) {
$orders[] = "$field$direction";
}
}
// 如果没有排序,使用默认排序
if (empty($orders) && !empty($this->config->getDefaultSort())) {
foreach ($this->config->getDefaultSort() as $field => $direction) {
if (in_array($field, $sortFields)) {
$orders[] = "$field$direction";
}
}
}
return implode(', ', $orders);
}
/**
* 解析 where 条件
*
* @param array $input
* @return array
*/
private function parseWhere(array $input): array
{
$where = [];
$skipFields = array_merge(
$this->config->getSkipFields(),
['field', 'order', 'orderBy', 'orderDirection', 'sort', 'format', 'limit', 'page']
);
// 检查是否包含三元素数组格式
$hasTripleArray = false;
foreach ($input as $key => $value) {
if (is_numeric($key) && is_array($value) && count($value) === 3) {
$hasTripleArray = true;
break;
}
}
// 如果有三元素数组格式,直接保留原格式
if ($hasTripleArray) {
foreach ($input as $key => $value) {
// 跳过非查询参数
if (in_array($key, $skipFields, true)) {
continue;
}
// 三元素数组直接添加
if (is_numeric($key) && is_array($value) && count($value) === 3) {
if ($this->isValidCondition($value)) {
$where[] = $value;
}
continue;
}
// 处理大写前缀格式
if (preg_match('/^([A-Z_]+)_(.+)$/', $key, $matches)) {
$condition = $this->parseUppercaseFormat($matches[1], $matches[2], $value);
if ($condition) {
$where[] = $condition;
}
continue;
}
// 处理普通字段
if ($this->isValidField($key)) {
if (!$this->isSkipValue($value)) {
$where[] = [$key, '=', $value];
}
}
}
} else {
// 转换为标准格式
$where['filters'] = [];
// 处理关键词搜索
if ($this->config->isEnableKeywordSearch() && !empty($input[$this->config->getKeywordParam()])) {
$keyword = $input[$this->config->getKeywordParam()];
$keywordFields = $this->config->getKeywordFields();
if (!empty($keywordFields)) {
foreach ($keywordFields as $field) {
if ($this->isValidField($field)) {
$where['filters'][$field] = "like:%{$keyword}%";
}
}
}
}
foreach ($input as $key => $value) {
// 跳过非查询参数
if (in_array($key, $skipFields, true)) {
continue;
}
// 跳过关键词参数
if ($key === $this->config->getKeywordParam()) {
continue;
}
// 处理大写前缀格式
if (preg_match('/^([A-Z_]+)_(.+)$/', $key, $matches)) {
$field = $matches[2];
if ($this->isValidField($field)) {
$operatorLower = $this->convertOperator($matches[1]);
$valueString = $this->formatValue($operatorLower, $value);
if ($valueString !== null) {
$where['filters'][$field] = "{$operatorLower}:{$valueString}";
}
}
continue;
}
// 处理普通字段
if ($this->isValidField($key)) {
if (!$this->isSkipValue($value)) {
$where['filters'][$key] = "eq:{$value}";
}
}
}
}
return $where;
}
/**
* 解析自定义字段
*
* @param array $input
* @return array
*/
private function parseCustomFields(array $input): array
{
$customFields = [];
foreach ($this->config->getCustomFields() as $key => $defaultValue) {
if (isset($input[$key])) {
$customFields[$key] = $input[$key];
} elseif ($defaultValue !== null) {
$customFields[$key] = $defaultValue;
}
}
return $customFields;
}
/**
* 解析大写前缀格式
*
* @param string $operatorUpper
* @param string $field
* @param mixed $value
* @return array|null
*/
private function parseUppercaseFormat(string $operatorUpper, string $field, mixed $value): ?array
{
if (!$this->isValidField($field)) {
return null;
}
if ($this->isSkipValue($value, $operatorUpper)) {
return null;
}
$operatorMap = [
'IN' => 'IN',
'LIKE' => 'LIKE',
'GT' => '>',
'LT' => '<',
'GTE' => '>=',
'LTE' => '<=',
'NE' => '!=',
'BETWEEN' => 'BETWEEN',
'EQ' => '=',
];
$operator = $operatorMap[$operatorUpper] ?? '=';
// 特殊处理 LIKE 操作符
if ($operatorUpper === 'LIKE' && $this->config->isEnableLikeQuery()) {
return [$field, $operator, "%{$value}%"];
}
// 特殊处理 IN 操作符
if ($operatorUpper === 'IN') {
$value = is_array($value) ? $value : Arr::normalize($value);
return [$field, 'IN', $value];
}
// 特殊处理 BETWEEN 操作符
if ($operatorUpper === 'BETWEEN' && $this->config->isEnableRangeQuery()) {
if (is_array($value) && count($value) === 2) {
if ($this->config->isAutoConvertDateTime()) {
$start = DateTime::dateTimeStringToTimestamp($value[0]);
$end = DateTime::dateTimeStringToTimestamp($value[1]);
return [$field, '>', $start] + [$field, '<', $end];
}
return [$field, '>', $value[0]] + [$field, '<', $value[1]];
}
}
return [$field, $operator, $value];
}
/**
* 转换操作符
*
* @param string $operatorUpper
* @return string
*/
private function convertOperator(string $operatorUpper): string
{
$map = [
'IN' => 'in',
'LIKE' => 'like',
'GT' => 'gt',
'LT' => 'lt',
'GTE' => 'gte',
'LTE' => 'lte',
'NE' => 'ne',
'BETWEEN' => 'between',
'EQ' => 'eq',
];
return $map[$operatorUpper] ?? 'eq';
}
/**
* 格式化值
*
* @param string $operator
* @param mixed $value
* @return string|null
*/
private function formatValue(string $operator, mixed $value): ?string
{
if ($this->isSkipValue($value)) {
return null;
}
if ($operator === 'like' && $this->config->isEnableLikeQuery()) {
return "%{$value}%";
}
if ($operator === 'in') {
$value = is_array($value) ? $value : Arr::normalize($value);
return json_encode($value);
}
return (string)$value;
}
/**
* 检查字段是否有效
*
* @param string $field
* @return bool
*/
private function isValidField(string $field): bool
{
// 检查跳过字段
if (in_array($field, $this->config->getSkipFields(), true)) {
return false;
}
// 检查允许字段
if (!empty($this->config->getAllowedFields())) {
return in_array($field, $this->config->getAllowedFields(), true);
}
// 检查数据库字段
if (!empty($this->dbFields)) {
return in_array($field, $this->dbFields, true);
}
return true;
}
/**
* 检查是否跳过值
*
* @param mixed $value
* @param string $operator
* @return bool
*/
private function isSkipValue(mixed $value, string $operator = ''): bool
{
if (!$this->config->isSkipEmptyValues()) {
return false;
}
// null 值无效
if ($value === null) {
return true;
}
// 空字符串无效
if ($value === '') {
return true;
}
// 空数组无效
if (is_array($value) && empty($value)) {
return true;
}
// 对于 BETWEEN 操作,需要检查数组元素
if ($operator === 'BETWEEN' && is_array($value) && count($value) === 2) {
return ($value[0] === '' || $value[0] === null) ||
($value[1] === '' || $value[1] === null);
}
return false;
}
/**
* 检查三元素数组条件是否有效
*
* @param array $condition
* @return bool
*/
private function isValidCondition(array $condition): bool
{
if (count($condition) !== 3) {
return false;
}
// 检查字段是否有效
if (!$this->isValidField($condition[0])) {
return false;
}
// 检查值是否有效
return !$this->isSkipValue($condition[2]);
}
/**
* 格式化结果
*
* @param array $result
* @return array|object
*/
private function formatResult(array $result)
{
$format = $this->config->getReturnFormat();
switch ($format) {
case 'object':
return (object)$result;
case 'compact':
return [
$result['where'],
$result['format'],
$result['limit'],
$result['field'],
$result['order'],
$result['page'],
];
case 'array':
default:
return $result;
}
}
/**
* 获取配置对象
*
* @return QuerySelectConfig
*/
public function getConfig(): QuerySelectConfig
{
return $this->config;
}
/**
* 设置数据库字段
*
* @param array $fields
* @return self
*/
public function setDbFields(array $fields): self
{
$this->dbFields = $fields;
return $this;
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

About

一个强大的查询参数解析和过滤库,为 PHP 8.1+ 项目提供灵活、类型安全的查询构建能力。
Cancel

Releases

No release

Contributors

All

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/motion-code/query.git
git@gitee.com:motion-code/query.git
motion-code
query
Query
main
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /