代码优化

pull/400/head
Henry 2022-05-04 11:49:25 +08:00
parent 8e48aa7edd
commit 940d4f0410
1 changed files with 209 additions and 186 deletions

View File

@ -9,12 +9,16 @@ use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv; use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db; use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException; use think\exception\PDOException;
use think\exception\ValidateException; use think\exception\ValidateException;
use think\response\Json;
trait Backend trait Backend
{ {
/** /**
* 排除前台提交过来的字段 * 排除前台提交过来的字段
* @param $params * @param $params
@ -24,109 +28,114 @@ trait Backend
{ {
if (is_array($this->excludeFields)) { if (is_array($this->excludeFields)) {
foreach ($this->excludeFields as $field) { foreach ($this->excludeFields as $field) {
if (key_exists($field, $params)) { if (array_key_exists($field, $params)) {
unset($params[$field]); unset($params[$field]);
} }
} }
} else { } else if (array_key_exists($this->excludeFields, $params)) {
if (key_exists($this->excludeFields, $params)) { unset($params[$this->excludeFields]);
unset($params[$this->excludeFields]);
}
} }
return $params; return $params;
} }
/** /**
* 查看 * 查看
*
* @return string|Json
* @throws \think\Exception
* @throws DbException
*/ */
public function index() public function index()
{ {
//设置过滤方法 //设置过滤方法
$this->request->filter(['strip_tags', 'trim']); $this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) { if (false === $this->request->isAjax()) {
//如果发送的来源是Selectpage则转发到Selectpage return $this->view->fetch();
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->where($where)
->order($sort, $order)
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
} }
return $this->view->fetch(); //如果发送的来源是 Selectpage则转发到 Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
[$where, $sort, $order, $offset, $limit] = $this->buildparams();
$list = $this->model
->where($where)
->order($sort, $order)
->paginate($limit);
$result = ['total' => $list->total(), 'rows' => $list->items()];
return json($result);
} }
/** /**
* 回收站 * 回收站
*
* @return string|Json
* @throws \think\Exception
*/ */
public function recyclebin() public function recyclebin()
{ {
//设置过滤方法 //设置过滤方法
$this->request->filter(['strip_tags', 'trim']); $this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) { if (false === $this->request->isAjax()) {
list($where, $sort, $order, $offset, $limit) = $this->buildparams(); return $this->view->fetch();
$list = $this->model
->onlyTrashed()
->where($where)
->order($sort, $order)
->paginate($limit);
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
} }
return $this->view->fetch(); [$where, $sort, $order, $offset, $limit] = $this->buildparams();
$list = $this->model
->onlyTrashed()
->where($where)
->order($sort, $order)
->paginate($limit);
$result = ['total' => $list->total(), 'rows' => $list->items()];
return json($result);
} }
/** /**
* 添加 * 添加
*
* @return string
* @throws \think\Exception
*/ */
public function add() public function add()
{ {
if ($this->request->isPost()) { if (false === $this->request->isPost()) {
$params = $this->request->post("row/a"); return $this->view->fetch();
if ($params) { }
$params = $this->preExcludeFields($params); $params = $this->request->post('row/a');
if (empty($params)) {
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException(true)->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were inserted'));
}
}
$this->error(__('Parameter %s can not be empty', '')); $this->error(__('Parameter %s can not be empty', ''));
} }
return $this->view->fetch(); $params = $this->preExcludeFields($params);
if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$params[$this->dataLimitField] = $this->auth->id;
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
$this->model->validateFailException()->validate($validate);
}
$result = $this->model->allowField(true)->save($params);
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result === false) {
$this->error(__('No rows were inserted'));
}
$this->success();
} }
/** /**
* 编辑 * 编辑
*
* @param $ids
* @return string
* @throws DbException
* @throws \think\Exception
*/ */
public function edit($ids = null) public function edit($ids = null)
{ {
@ -135,102 +144,69 @@ trait Backend
$this->error(__('No Results were found')); $this->error(__('No Results were found'));
} }
$adminIds = $this->getDataLimitAdminIds(); $adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) { if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) { $this->error(__('You have no permission'));
$this->error(__('You have no permission'));
}
} }
if ($this->request->isPost()) { if (false === $this->request->isPost()) {
$params = $this->request->post("row/a"); $this->view->assign('row', $row);
if ($params) { return $this->view->fetch();
$params = $this->preExcludeFields($params); }
$result = false; $params = $this->request->post('row/a');
Db::startTrans(); if (empty($params)) {
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', '')); $this->error(__('Parameter %s can not be empty', ''));
} }
$this->view->assign("row", $row); $params = $this->preExcludeFields($params);
return $this->view->fetch(); $result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException()->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if (false === $result) {
$this->error(__('No rows were updated'));
}
$this->success();
} }
/** /**
* 删除 * 删除
*
* @param $ids
* @return void
* @throws DbException
* @throws DataNotFoundException
* @throws ModelNotFoundException
*/ */
public function del($ids = "") public function del($ids = null)
{ {
if (!$this->request->isPost()) { if (false === $this->request->isPost()) {
$this->error(__("Invalid parameters")); $this->error(__("Invalid parameters"));
} }
$ids = $ids ? $ids : $this->request->post("ids"); $ids = $ids ?: $this->request->post("ids");
if ($ids) { if (empty($ids)) {
$pk = $this->model->getPk(); $this->error(__('Parameter %s can not be empty', 'ids'));
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($pk, 'in', $ids)->select();
$count = 0;
Db::startTrans();
try {
foreach ($list as $k => $v) {
$count += $v->delete();
}
Db::commit();
} catch (PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
} else {
$this->error(__('No rows were deleted'));
}
} }
$this->error(__('Parameter %s can not be empty', 'ids'));
}
/**
* 真实删除
*/
public function destroy($ids = "")
{
if (!$this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ? $ids : $this->request->post("ids");
$pk = $this->model->getPk(); $pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds(); $adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) { if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds); $this->model->where($this->dataLimitField, 'in', $adminIds);
} }
if ($ids) { $list = $this->model->where($pk, 'in', $ids)->select();
$this->model->where($pk, 'in', $ids);
}
$count = 0; $count = 0;
Db::startTrans(); Db::startTrans();
try { try {
$list = $this->model->onlyTrashed()->select(); foreach ($list as $item) {
foreach ($list as $k => $v) { $count += $item->delete();
$count += $v->delete(true);
} }
Db::commit(); Db::commit();
} catch (PDOException|Exception $e) { } catch (PDOException|Exception $e) {
@ -239,21 +215,61 @@ trait Backend
} }
if ($count) { if ($count) {
$this->success(); $this->success();
} else {
$this->error(__('No rows were deleted'));
} }
$this->error(__('Parameter %s can not be empty', 'ids')); $this->error(__('No rows were deleted'));
}
/**
* 真实删除
*
* @param $ids
* @return void
*/
public function destroy($ids = null)
{
if (false === $this->request->isPost()) {
$this->error(__("Invalid parameters"));
}
$ids = $ids ?: $this->request->post('ids');
if (empty($ids)) {
$this->error(__('Parameter %s can not be empty', 'ids'));
}
$pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$this->model->where($pk, 'in', $ids);
$count = 0;
Db::startTrans();
try {
$list = $this->model->onlyTrashed()->select();
foreach ($list as $item) {
$count += $item->delete(true);
}
Db::commit();
} catch (PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($count) {
$this->success();
}
$this->error(__('No rows were deleted'));
} }
/** /**
* 还原 * 还原
*
* @param $ids
* @return void
*/ */
public function restore($ids = "") public function restore($ids = null)
{ {
if (!$this->request->isPost()) { if (false === $this->request->isPost()) {
$this->error(__("Invalid parameters")); $this->error(__('Invalid parameters'));
} }
$ids = $ids ? $ids : $this->request->post("ids"); $ids = $ids ?: $this->request->post('ids');
$pk = $this->model->getPk(); $pk = $this->model->getPk();
$adminIds = $this->getDataLimitAdminIds(); $adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) { if (is_array($adminIds)) {
@ -266,7 +282,7 @@ trait Backend
Db::startTrans(); Db::startTrans();
try { try {
$list = $this->model->onlyTrashed()->select(); $list = $this->model->onlyTrashed()->select();
foreach ($list as $index => $item) { foreach ($list as $item) {
$count += $item->restore(); $count += $item->restore();
} }
Db::commit(); Db::commit();
@ -282,49 +298,56 @@ trait Backend
/** /**
* 批量更新 * 批量更新
*
* @param $ids
* @return void
*/ */
public function multi($ids = "") public function multi($ids = null)
{ {
if (!$this->request->isPost()) { if (false === $this->request->isPost()) {
$this->error(__("Invalid parameters")); $this->error(__('Invalid parameters'));
} }
$ids = $ids ? $ids : $this->request->post("ids"); $ids = $ids ?: $this->request->post('ids');
if ($ids) { if (empty($ids)) {
if ($this->request->has('params')) { $this->error(__('Parameter %s can not be empty', 'ids'));
parse_str($this->request->post("params"), $values); }
$values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
if ($values) { if (false === $this->request->has('params')) {
$adminIds = $this->getDataLimitAdminIds(); $this->error(__('No rows were updated'));
if (is_array($adminIds)) { }
$this->model->where($this->dataLimitField, 'in', $adminIds); parse_str($this->request->post('params'), $values);
} $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
$count = 0; if (empty($values)) {
Db::startTrans(); $this->error(__('You have no permission'));
try { }
$list = $this->model->where($this->model->getPk(), 'in', $ids)->select(); $adminIds = $this->getDataLimitAdminIds();
foreach ($list as $index => $item) { if (is_array($adminIds)) {
$count += $item->allowField(true)->isUpdate(true)->save($values); $this->model->where($this->dataLimitField, 'in', $adminIds);
} }
Db::commit(); $count = 0;
} catch (PDOException|Exception $e) { Db::startTrans();
Db::rollback(); try {
$this->error($e->getMessage()); $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
} foreach ($list as $item) {
if ($count) { $count += $item->allowField(true)->isUpdate(true)->save($values);
$this->success();
} else {
$this->error(__('No rows were updated'));
}
} else {
$this->error(__('You have no permission'));
}
} }
Db::commit();
} catch (PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
} }
$this->error(__('Parameter %s can not be empty', 'ids')); if ($count) {
$this->success();
}
$this->error(__('No rows were updated'));
} }
/** /**
* 导入 * 导入
*
* @return void
* @throws PDOException
* @throws BindParamException
*/ */
protected function import() protected function import()
{ {
@ -344,12 +367,12 @@ trait Backend
if ($ext === 'csv') { if ($ext === 'csv') {
$file = fopen($filePath, 'r'); $file = fopen($filePath, 'r');
$filePath = tempnam(sys_get_temp_dir(), 'import_csv'); $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
$fp = fopen($filePath, "w"); $fp = fopen($filePath, 'w');
$n = 0; $n = 0;
while ($line = fgets($file)) { while ($line = fgets($file)) {
$line = rtrim($line, "\n\r\0"); $line = rtrim($line, "\n\r\0");
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']); $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
if ($encoding != 'utf-8') { if ($encoding !== 'utf-8') {
$line = mb_convert_encoding($line, 'utf-8', $encoding); $line = mb_convert_encoding($line, 'utf-8', $encoding);
} }
if ($n == 0 || preg_match('/^".*"$/', $line)) { if ($n == 0 || preg_match('/^".*"$/', $line)) {