51 lines
1.5 KiB
PHP
51 lines
1.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace app\crm\controller;
|
||
|
|
|
||
|
|
use support\Request;
|
||
|
|
use support\Response;
|
||
|
|
use support\exception\BusinessException;
|
||
|
|
use app\common\traits\ResponseTrait;
|
||
|
|
use think\Validate;
|
||
|
|
|
||
|
|
abstract class BaseController
|
||
|
|
{
|
||
|
|
use ResponseTrait;
|
||
|
|
|
||
|
|
protected mixed $validator = null;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 验证数据
|
||
|
|
*
|
||
|
|
* @param Validate $validator 验证器实例
|
||
|
|
* @param array $data 待验证的数据
|
||
|
|
* @param string $scene 验证场景
|
||
|
|
* @return array 验证后的数据
|
||
|
|
* @throws BusinessException 验证失败时抛出业务异常
|
||
|
|
*/
|
||
|
|
public function validate(Validate $validator, array $data, string $scene = ''): array
|
||
|
|
{
|
||
|
|
// 如果指定了验证场景,并且验证器支持场景方法,则设置验证场景
|
||
|
|
if ($scene && method_exists($validator, 'scene')) {
|
||
|
|
$validator->scene($scene);
|
||
|
|
}
|
||
|
|
// 执行数据验证
|
||
|
|
if (!$validator->check($data)) {
|
||
|
|
// 验证失败,抛出业务异常,异常信息为验证器返回的错误信息
|
||
|
|
throw new BusinessException($validator->getError());
|
||
|
|
}
|
||
|
|
// 验证成功,返回原始数据
|
||
|
|
return $data;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function page($result){
|
||
|
|
$current = $result->currentPage();
|
||
|
|
$total = $result->total();
|
||
|
|
$size = $result->perPage();
|
||
|
|
$result = $result->toArray();
|
||
|
|
$result['current'] = $current;
|
||
|
|
$result['total'] = $total;
|
||
|
|
$result['size'] = $size;
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
}
|