catchAdmin/extend/catcher/base/CatchRequest.php

111 lines
2.5 KiB
PHP
Raw Normal View History

2019-12-06 09:17:40 +08:00
<?php
2020-11-29 09:29:14 +08:00
declare(strict_types=1);
2019-12-06 09:17:40 +08:00
namespace catcher\base;
use app\Request;
2019-12-15 13:38:25 +08:00
use catcher\exceptions\FailedException;
2019-12-06 09:17:40 +08:00
use catcher\exceptions\ValidateFailedException;
2021-01-17 09:39:18 +08:00
use catcher\Utils;
2019-12-06 09:17:40 +08:00
2019-12-13 17:26:54 +08:00
class CatchRequest extends Request
2019-12-06 09:17:40 +08:00
{
2020-01-09 22:20:57 +08:00
/**
* @var bool
*/
protected $needCreatorId = true;
2020-01-09 08:22:38 +08:00
/**
* 批量验证
*
* @var bool
*/
2020-01-07 17:27:55 +08:00
protected $batch = false;
2019-12-06 09:17:40 +08:00
/**
* Request constructor.
* @throws \Exception
*/
public function __construct()
{
parent::__construct();
$this->validate();
}
/**
* 初始化验证
*
* @time 2019年11月27日
* @throws \Exception
* @return mixed
*/
protected function validate()
{
2020-01-09 08:22:38 +08:00
if (method_exists($this, 'rules')) {
try {
2020-02-21 22:32:50 +08:00
$validate = app('validate');
2020-01-07 17:27:55 +08:00
// 批量验证
if ($this->batch) {
$validate->batch($this->batch);
}
2020-01-08 22:31:17 +08:00
2020-01-07 17:27:55 +08:00
// 验证
2020-10-26 11:20:42 +08:00
$message = [];
if (method_exists($this, 'message')) {
$message = $this->message();
}
2020-09-20 12:05:19 +08:00
if (!$validate->message(empty($message) ? [] : $message)->check(request()->param(), $this->rules())) {
2020-01-09 08:22:38 +08:00
throw new FailedException($validate->getError());
2019-12-15 13:38:25 +08:00
}
2020-01-09 08:22:38 +08:00
} catch (\Exception $e) {
2019-12-15 13:38:25 +08:00
throw new ValidateFailedException($e->getMessage());
2020-01-09 08:22:38 +08:00
}
2019-12-06 09:17:40 +08:00
}
2020-01-09 08:22:38 +08:00
// 设置默认参数
2020-01-09 22:20:57 +08:00
if ($this->needCreatorId) {
2020-07-13 17:06:21 +08:00
$this->param['creator_id'] = $this->user()->id;
2020-01-09 22:20:57 +08:00
}
2020-01-09 08:22:38 +08:00
2019-12-06 09:17:40 +08:00
return true;
}
/**
* rewrite post
*
* @time 2020年10月15日
* @param string $name
* @param null $default
* @param string $filter
* @return array|mixed|null
*/
public function post($name = '', $default = null, $filter = '')
{
if ($this->needCreatorId) {
$this->post['creator_id'] = $this->user()->id;
}
return parent::post($name, $default, $filter); // TODO: Change the autogenerated stub
}
2021-01-17 09:39:18 +08:00
/**
* 过滤空字段
*
* @time 2021年01月16日
* @return $this
*/
public function filterEmptyField(): CatchRequest
{
if ($this->isGet()) {
$this->get = Utils::filterEmptyValue($this->get);
} elseif ($this->isPost()) {
$this->post = Utils::filterEmptyValue($this->post);
} else {
$this->put = Utils::filterEmptyValue($this->put);
}
return $this;
}
2019-12-06 09:17:40 +08:00
}