60 lines
1.6 KiB
PHP
60 lines
1.6 KiB
PHP
<?php
|
|
// +----------------------------------------------------------------------
|
|
// | Author: ScottPan Team
|
|
// +----------------------------------------------------------------------
|
|
|
|
namespace app\services\dao;
|
|
|
|
use think\helper\Str;
|
|
|
|
/**
|
|
* 本项目自有搜索条件构建器,不依赖 CRMEB 商业授权基础类。
|
|
*/
|
|
class SearchConditionBuilder
|
|
{
|
|
/**
|
|
* 根据模型搜索器和表字段拆分 withSearch 字段与普通 where 字段。
|
|
*
|
|
* @param array $whereKeys 请求条件 key 列表
|
|
* @param string|object $model 模型类名或模型实例
|
|
* @return array{0: array, 1: array}
|
|
* @throws \ReflectionException
|
|
*/
|
|
public function build(array $whereKeys, $model): array
|
|
{
|
|
$modelClass = is_object($model) ? $model::class : $model;
|
|
$reflection = new \ReflectionClass($modelClass);
|
|
$fields = $this->getTableFields($model);
|
|
|
|
$with = [];
|
|
$whereKey = [];
|
|
foreach ($whereKeys as $key) {
|
|
$key = (string)$key;
|
|
if ($key === 'timeKey') {
|
|
continue;
|
|
}
|
|
|
|
if ($reflection->hasMethod('search' . Str::studly($key) . 'Attr')) {
|
|
$with[] = $key;
|
|
continue;
|
|
}
|
|
|
|
if (!$fields || in_array($key, $fields, true)) {
|
|
$whereKey[] = $key;
|
|
}
|
|
}
|
|
|
|
return [$with, $whereKey];
|
|
}
|
|
|
|
protected function getTableFields($model): array
|
|
{
|
|
try {
|
|
$model = is_object($model) ? $model : new $model();
|
|
return $model->getTableFields();
|
|
} catch (\Throwable $e) {
|
|
return [];
|
|
}
|
|
}
|
|
}
|