| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- <?php
- namespace app\validate;
- use think\facade\Request;
- use think\Validate;
- class CommonValidate extends Validate
- {
- protected $request;
- public function __construct(Request $request)
- {
- $this->request = $request;
- parent::__construct();
- }
- // 自定义验证规则:验证是否为有效的JSON格式
- protected function isJson($value): bool
- {
- json_decode($value);
- return (json_last_error() == JSON_ERROR_NONE);
- }
- /**
- * 通用验证方法
- * 使用父类验证规则进行数据验证
- *
- * @param array $data 要验证的数据
- * @param string|null $entityClass 数据实体类名,如果不传则返回原始数据
- * @return array
- */
- public function validate(array $data, ?string $entityClass = null): array
- {
- if (!$this->check($data)) {
- return [
- 'status' => 'error',
- 'message' => $this->getError()
- ];
- }
-
- $resultData = $data;
- if ($entityClass && class_exists($entityClass)) {
- $resultData = $entityClass::newInstance($data);
- }
-
- return [
- 'status' => 'success',
- 'data' => $resultData
- ];
- }
- }
|