Explorar o código

!400 代码优化,处理destroy方法未判断$ids变量为空情况的问题
Merge pull request !400 from Henry/optimize

F4nniu %!s(int64=3) %!d(string=hai) anos
pai
achega
12e7bbf5f2
Modificáronse 1 ficheiros con 197 adicións e 174 borrados
  1. 197 174
      application/admin/library/traits/Backend.php

+ 197 - 174
application/admin/library/traits/Backend.php

@@ -9,12 +9,16 @@ use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
 use PhpOffice\PhpSpreadsheet\Reader\Xls;
 use PhpOffice\PhpSpreadsheet\Reader\Csv;
 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\ValidateException;
+use think\response\Json;
 
 trait Backend
 {
-
     /**
      * 排除前台提交过来的字段
      * @param $params
@@ -24,109 +28,114 @@ trait Backend
     {
         if (is_array($this->excludeFields)) {
             foreach ($this->excludeFields as $field) {
-                if (key_exists($field, $params)) {
+                if (array_key_exists($field, $params)) {
                     unset($params[$field]);
                 }
             }
-        } else {
-            if (key_exists($this->excludeFields, $params)) {
-                unset($params[$this->excludeFields]);
-            }
+        } else if (array_key_exists($this->excludeFields, $params)) {
+            unset($params[$this->excludeFields]);
         }
         return $params;
     }
 
-
     /**
      * 查看
+     *
+     * @return string|Json
+     * @throws \think\Exception
+     * @throws DbException
      */
     public function index()
     {
         //设置过滤方法
         $this->request->filter(['strip_tags', 'trim']);
-        if ($this->request->isAjax()) {
-            //如果发送的来源是Selectpage,则转发到Selectpage
-            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);
+        if (false === $this->request->isAjax()) {
+            return $this->view->fetch();
+        }
+        //如果发送的来源是 Selectpage,则转发到 Selectpage
+        if ($this->request->request('keyField')) {
+            return $this->selectpage();
         }
-        return $this->view->fetch();
+        [$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()
     {
         //设置过滤方法
         $this->request->filter(['strip_tags', 'trim']);
-        if ($this->request->isAjax()) {
-            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
-
-            $list = $this->model
-                ->onlyTrashed()
-                ->where($where)
-                ->order($sort, $order)
-                ->paginate($limit);
-
-            $result = array("total" => $list->total(), "rows" => $list->items());
-
-            return json($result);
+        if (false === $this->request->isAjax()) {
+            return $this->view->fetch();
         }
-        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()
     {
-        if ($this->request->isPost()) {
-            $params = $this->request->post("row/a");
-            if ($params) {
-                $params = $this->preExcludeFields($params);
+        if (false === $this->request->isPost()) {
+            return $this->view->fetch();
+        }
+        $params = $this->request->post('row/a');
+        if (empty($params)) {
+            $this->error(__('Parameter %s can not be empty', ''));
+        }
+        $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(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'));
-                }
+        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);
             }
-            $this->error(__('Parameter %s can not be empty', ''));
+            $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'));
         }
-        return $this->view->fetch();
+        $this->success();
     }
 
     /**
      * 编辑
+     *
+     * @param $ids
+     * @return string
+     * @throws DbException
+     * @throws \think\Exception
      */
     public function edit($ids = null)
     {
@@ -135,102 +144,108 @@ trait Backend
             $this->error(__('No Results were found'));
         }
         $adminIds = $this->getDataLimitAdminIds();
-        if (is_array($adminIds)) {
-            if (!in_array($row[$this->dataLimitField], $adminIds)) {
-                $this->error(__('You have no permission'));
-            }
+        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
+            $this->error(__('You have no permission'));
         }
-        if ($this->request->isPost()) {
-            $params = $this->request->post("row/a");
-            if ($params) {
-                $params = $this->preExcludeFields($params);
-                $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(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'));
-                }
-            }
+        if (false === $this->request->isPost()) {
+            $this->view->assign('row', $row);
+            return $this->view->fetch();
+        }
+        $params = $this->request->post('row/a');
+        if (empty($params)) {
             $this->error(__('Parameter %s can not be empty', ''));
         }
-        $this->view->assign("row", $row);
-        return $this->view->fetch();
+        $params = $this->preExcludeFields($params);
+        $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"));
         }
-        $ids = $ids ? $ids : $this->request->post("ids");
-        if ($ids) {
-            $pk = $this->model->getPk();
-            $adminIds = $this->getDataLimitAdminIds();
-            if (is_array($adminIds)) {
-                $this->model->where($this->dataLimitField, 'in', $adminIds);
-            }
-            $list = $this->model->where($pk, 'in', $ids)->select();
+        $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);
+        }
+        $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'));
+        $count = 0;
+        Db::startTrans();
+        try {
+            foreach ($list as $item) {
+                $count += $item->delete();
             }
+            Db::commit();
+        } catch (PDOException|Exception $e) {
+            Db::rollback();
+            $this->error($e->getMessage());
+        }
+        if ($count) {
+            $this->success();
         }
-        $this->error(__('Parameter %s can not be empty', 'ids'));
+        $this->error(__('No rows were deleted'));
     }
 
     /**
      * 真实删除
+     *
+     * @param $ids
+     * @return void
      */
-    public function destroy($ids = "")
+    public function destroy($ids = null)
     {
-        if (!$this->request->isPost()) {
+        if (false === $this->request->isPost()) {
             $this->error(__("Invalid parameters"));
         }
-        $ids = $ids ? $ids : $this->request->post("ids");
+        $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);
         }
-        if ($ids) {
-            $this->model->where($pk, 'in', $ids);
-        }
+        $this->model->where($pk, 'in', $ids);
         $count = 0;
         Db::startTrans();
         try {
             $list = $this->model->onlyTrashed()->select();
-            foreach ($list as $k => $v) {
-                $count += $v->delete(true);
+            foreach ($list as $item) {
+                $count += $item->delete(true);
             }
             Db::commit();
         } catch (PDOException|Exception $e) {
@@ -239,21 +254,22 @@ trait Backend
         }
         if ($count) {
             $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 restore($ids = "")
+    public function restore($ids = null)
     {
-        if (!$this->request->isPost()) {
-            $this->error(__("Invalid parameters"));
+        if (false === $this->request->isPost()) {
+            $this->error(__('Invalid parameters'));
         }
-        $ids = $ids ? $ids : $this->request->post("ids");
+        $ids = $ids ?: $this->request->post('ids');
         $pk = $this->model->getPk();
         $adminIds = $this->getDataLimitAdminIds();
         if (is_array($adminIds)) {
@@ -266,7 +282,7 @@ trait Backend
         Db::startTrans();
         try {
             $list = $this->model->onlyTrashed()->select();
-            foreach ($list as $index => $item) {
+            foreach ($list as $item) {
                 $count += $item->restore();
             }
             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()) {
-            $this->error(__("Invalid parameters"));
+        if (false === $this->request->isPost()) {
+            $this->error(__('Invalid parameters'));
         }
-        $ids = $ids ? $ids : $this->request->post("ids");
-        if ($ids) {
-            if ($this->request->has('params')) {
-                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) {
-                    $adminIds = $this->getDataLimitAdminIds();
-                    if (is_array($adminIds)) {
-                        $this->model->where($this->dataLimitField, 'in', $adminIds);
-                    }
-                    $count = 0;
-                    Db::startTrans();
-                    try {
-                        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
-                        foreach ($list as $index => $item) {
-                            $count += $item->allowField(true)->isUpdate(true)->save($values);
-                        }
-                        Db::commit();
-                    } catch (PDOException|Exception $e) {
-                        Db::rollback();
-                        $this->error($e->getMessage());
-                    }
-                    if ($count) {
-                        $this->success();
-                    } else {
-                        $this->error(__('No rows were updated'));
-                    }
-                } else {
-                    $this->error(__('You have no permission'));
-                }
+        $ids = $ids ?: $this->request->post('ids');
+        if (empty($ids)) {
+            $this->error(__('Parameter %s can not be empty', 'ids'));
+        }
+
+        if (false === $this->request->has('params')) {
+            $this->error(__('No rows were updated'));
+        }
+        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 (empty($values)) {
+            $this->error(__('You have no permission'));
+        }
+        $adminIds = $this->getDataLimitAdminIds();
+        if (is_array($adminIds)) {
+            $this->model->where($this->dataLimitField, 'in', $adminIds);
+        }
+        $count = 0;
+        Db::startTrans();
+        try {
+            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
+            foreach ($list as $item) {
+                $count += $item->allowField(true)->isUpdate(true)->save($values);
             }
+            Db::commit();
+        } catch (PDOException|Exception $e) {
+            Db::rollback();
+            $this->error($e->getMessage());
+        }
+        if ($count) {
+            $this->success();
         }
-        $this->error(__('Parameter %s can not be empty', 'ids'));
+        $this->error(__('No rows were updated'));
     }
 
     /**
      * 导入
+     *
+     * @return void
+     * @throws PDOException
+     * @throws BindParamException
      */
     protected function import()
     {
@@ -344,12 +367,12 @@ trait Backend
         if ($ext === 'csv') {
             $file = fopen($filePath, 'r');
             $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
-            $fp = fopen($filePath, "w");
+            $fp = fopen($filePath, 'w');
             $n = 0;
             while ($line = fgets($file)) {
                 $line = rtrim($line, "\n\r\0");
                 $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);
                 }
                 if ($n == 0 || preg_match('/^".*"$/', $line)) {