Bläddra i källkod

'影片演职管理'

gorden 1 år sedan
förälder
incheckning
0ecbbef8fd

+ 17 - 0
app/admin/controller/life/CinemaPerformers.php

@@ -0,0 +1,17 @@
+<?php
+
+namespace app\admin\controller\life;
+
+use app\admin\validate\life\CinemaPerformersValidate;
+use app\model\CinemaPerformers as CinemaPerformersModel;
+use app\controller\Curd;
+
+class CinemaPerformers extends Curd
+{
+    public function __construct()
+    {
+        $this->model = new CinemaPerformersModel();
+        $this->validate = true;
+        $this->validateClass = new CinemaPerformersValidate();
+    }
+}

+ 0 - 1
app/admin/service/sys_manage/FieldService.php

@@ -3,7 +3,6 @@
 namespace app\admin\service\sys_manage;
 
 use app\common\Util;
-use app\model\MemberInfo;
 use app\model\SysField;
 use Illuminate\Database\Schema\Blueprint;
 use support\Db;

+ 23 - 0
app/admin/validate/life/CinemaPerformersValidate.php

@@ -0,0 +1,23 @@
+<?php
+
+namespace app\admin\validate\life;
+
+use think\Validate;
+
+class CinemaPerformersValidate extends Validate
+{
+    protected $rule = [
+        'performers_name' => 'require|chsDash',
+        'performers_img' => 'regex:/^[0-9a-zA-Z\.]+$/',
+        'performers_type' => 'require|in:1,2',
+        'performers_introduction' => 'chsDash',
+        'performers_is_del' => 'in:0,1'
+    ];
+
+    protected $message = [];
+
+    protected $scene = [
+        'add' => ['performers_name', 'performers_img', 'performers_type', 'performers_introduction'],
+        'update' => ['performers_name', 'performers_img', 'performers_type', 'performers_introduction', 'performers_is_del']
+    ];
+}

+ 36 - 0
app/common/Auth.php

@@ -0,0 +1,36 @@
+<?php
+namespace app\common;
+
+
+
+use app\model\SysUser;
+use Tinywan\Jwt\JwtToken;
+
+class Auth
+{
+    /**
+     * 获取权限范围内的所有管理员id
+     * @param bool $with_self
+     * @return array
+     */
+    public static function getScopeAdminIds(bool $withSelf = false): array
+    {
+        $userIds = SysUser::where('user_id','!=',0)->pluck('user_id')->toArray();
+        if ($withSelf) {
+            $userIds[] = JwtToken::getCurrentId();
+        }
+        return array_unique($userIds);
+    }
+
+    /**
+     * 是否是超级管理员
+     * @param int $admin_id
+     * @return bool
+     */
+    public static function isSupperAdmin(int $admin_id = 0): bool
+    {
+        // 暂时不涉及权限
+        return true;
+    }
+
+}

+ 194 - 0
app/common/Tree.php

@@ -0,0 +1,194 @@
+<?php
+
+namespace app\common;
+
+
+class Tree
+{
+
+    /**
+     * 获取完整的树结构,包含祖先节点
+     */
+    const INCLUDE_ANCESTORS = 1;
+
+    /**
+     * 获取部分树,不包含祖先节点
+     */
+    const EXCLUDE_ANCESTORS = 0;
+
+    /**
+     * 数据
+     * @var array
+     */
+    protected $data = [];
+
+    /**
+     * 哈希树
+     * @var array
+     */
+    protected $hashTree = [];
+
+    /**
+     * 父级字段名
+     * @var string
+     */
+    protected $pidName = 'pid';
+
+    /**
+     * @param $data
+     * @param string $pid_name
+     */
+    public function __construct($data, string $pid_name = 'pid')
+    {
+        $this->pidName = $pid_name;
+        if (is_object($data) && method_exists($data, 'toArray')) {
+            $this->data = $data->toArray();
+        } else {
+            $this->data = (array)$data;
+            $this->data = array_map(function ($item) {
+                if (is_object($item) && method_exists($item, 'toArray')) {
+                    return $item->toArray();
+                }
+                return $item;
+            }, $this->data);
+        }
+        $this->hashTree = $this->getHashTree();
+    }
+
+    /**
+     * 获取子孙节点
+     * @param array $include
+     * @param bool $with_self
+     * @return array
+     */
+    public function getDescendant(array $include, bool $with_self = false): array
+    {
+        $items = [];
+        foreach ($include as $id) {
+            if (!isset($this->hashTree[$id])) {
+                return [];
+            }
+            if ($with_self) {
+                $item = $this->hashTree[$id];
+                unset($item['children']);
+                $items[$item['id']] = $item;
+            }
+            foreach ($this->hashTree[$id]['children'] ?? [] as $item) {
+                unset($item['children']);
+                $items[$item['id']] = $item;
+                foreach ($this->getDescendant([$item['id']]) as $it) {
+                    $items[$it['id']] = $it;
+                }
+            }
+        }
+        return array_values($items);
+    }
+
+    /**
+     * 获取哈希树
+     * @param array $data
+     * @return array
+     */
+    protected function getHashTree(array $data = []): array
+    {
+        $data = $data ?: $this->data;
+        $hash_tree = [];
+        foreach ($data as $item) {
+            $hash_tree[$item['id']] = $item;
+        }
+        foreach ($hash_tree as $index => $item) {
+            if ($item[$this->pidName] && isset($hash_tree[$item[$this->pidName]])) {
+                $hash_tree[$item[$this->pidName]]['children'][$hash_tree[$index]['id']] = &$hash_tree[$index];
+            }
+        }
+        return $hash_tree;
+    }
+
+    /**
+     * 获取树
+     * @param array $include
+     * @param int $type
+     * @return array|null
+     */
+    public function getTree(array $include = [], int $type = 1): ?array
+    {
+        // $type === static::EXCLUDE_ANCESTORS
+        if ($type === static::EXCLUDE_ANCESTORS) {
+            $items = [];
+            $include = array_unique($include);
+            foreach ($include as $id) {
+                if (!isset($this->hashTree[$id])) {
+                    return [];
+                }
+                $items[] = $this->hashTree[$id];
+            }
+            return static::arrayValues($items);
+        }
+
+        // $type === static::INCLUDE_ANCESTORS
+        $hash_tree = $this->hashTree;
+        $items = [];
+        if ($include) {
+            $map = [];
+            foreach ($include as $id) {
+                if (!isset($hash_tree[$id])) {
+                    continue;
+                }
+                $item = $hash_tree[$id];
+                $max_depth = 100;
+                while ($max_depth-- > 0 && $item[$this->pidName] && isset($hash_tree[$item[$this->pidName]])) {
+                    $last_item = $item;
+                    $pid = $item[$this->pidName];
+                    $item = $hash_tree[$pid];
+                    $item_id = $item['id'];
+                    if (empty($map[$item_id])) {
+                        $map[$item_id] = 1;
+                        $hash_tree[$pid]['children'] = [];
+                    }
+                    $hash_tree[$pid]['children'][$last_item['id']] = $last_item;
+                    $item = $hash_tree[$pid];
+                }
+                $items[$item['id']] = $item;
+            }
+        } else {
+            $items = $hash_tree;
+        }
+        $formatted_items = [];
+        foreach ($items as $item) {
+            if (!$item[$this->pidName] || !isset($hash_tree[$item[$this->pidName]])) {
+                $formatted_items[] = $item;
+            }
+        }
+
+        return static::arrayValues($formatted_items);
+    }
+
+    /**
+     * 递归重建数组下标
+     * @param $array
+     * @return array
+     */
+    public static function arrayValues($array): array
+    {
+        if (!$array) {
+            return [];
+        }
+        if (!isset($array['children'])) {
+            $current = current($array);
+            if (!is_array($current)) {
+                return $array;
+            }
+            $tree = array_values($array);
+            foreach ($tree as $index => $item) {
+                $tree[$index] = static::arrayValues($item);
+            }
+            return $tree;
+        }
+        $array['children'] = array_values($array['children']);
+        foreach ($array['children'] as $index => $child) {
+            $array['children'][$index] = static::arrayValues($child);
+        }
+        return $array;
+    }
+
+}

+ 459 - 0
app/controller/Curd.php

@@ -0,0 +1,459 @@
+<?php
+
+namespace app\controller;
+
+use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
+use Illuminate\Database\Query\Builder as QueryBuilder;
+use app\common\Auth;
+use app\common\Tree;
+use app\common\Util;
+use support\exception\BusinessException;
+use support\Model;
+use support\Request;
+use support\Response;
+use Tinywan\Jwt\JwtToken;
+
+class Curd
+{
+    /**
+     * @var Model
+     */
+    protected $model = null;
+
+    /**
+     * 数据限制
+     * 例如当$dataLimit='personal'时将只返回当前管理员的数据
+     * @var string
+     */
+    protected $dataLimit = null;
+
+    /**
+     * 数据限制字段
+     */
+    protected $dataLimitField = 'user_id';
+
+    /**
+     * 是否开启写操作验证
+     */
+    protected $validate = false;
+
+    /**
+     * 验证类
+     */
+    protected $validateClass = '';
+
+    /**
+     * 查询
+     * @param Request $request
+     * @return Response
+     * @throws BusinessException
+     */
+    public function select(Request $request): Response
+    {
+        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
+        $query = $this->doSelect($where, $field, $order);
+        return $this->doFormat($query, $format, $limit);
+    }
+
+    /**
+     * 添加
+     * @param Request $request
+     * @return Response
+     * @throws BusinessException
+     */
+    public function insert(Request $request): Response
+    {
+        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
+            return json_fail($this->validateClass->getError());
+        }
+
+        $data = $this->insertInput($request);
+        $this->doInsert($data);
+        return json_success('success');
+    }
+
+    /**
+     * 更新
+     * @param Request $request
+     * @return Response
+     * @throws BusinessException
+     */
+    public function update(Request $request): Response
+    {
+        if ($this->validate && !$this->validateClass->scene('update')->check($request->post())) {
+            return json_fail($this->validateClass->getError());
+        }
+
+        [$id, $data] = $this->updateInput($request);
+        $this->doUpdate($id, $data);
+        return json_success('success');
+    }
+
+    /**
+     * 删除
+     * @param Request $request
+     * @return Response
+     * @throws BusinessException
+     */
+    public function delete(Request $request): Response
+    {
+        $ids = $this->deleteInput($request);
+        $this->doDelete($ids);
+        return json_success('success');
+    }
+
+    /**
+     * 查询前置
+     * @param Request $request
+     * @return array
+     * @throws BusinessException
+     */
+    protected function selectInput(Request $request): array
+    {
+        $field = $request->get('field');
+        $order = $request->get('order', 'asc');
+        $format = $request->get('format', 'normal');
+        $limit = (int)$request->get('limit', $format === 'tree' ? 1000 : 10);
+        $limit = $limit <= 0 ? 10 : $limit;
+        $order = $order === 'asc' ? 'asc' : 'desc';
+        $where = $request->get();
+        $page = (int)$request->get('page');
+        $page = $page > 0 ? $page : 1;
+        $table = config('database.connections.mysql.prefix') . $this->model->getTable();
+
+        $allow_column = Util::db()->select("desc `$table`");
+        if (!$allow_column) {
+            throw new BusinessException('表不存在');
+        }
+        $allow_column = array_column($allow_column, 'Field', 'Field');
+        if (!in_array($field, $allow_column)) {
+            $field = null;
+        }
+        foreach ($where as $column => $value) {
+            if (
+                $value === '' || !isset($allow_column[$column]) ||
+                is_array($value) && (empty($value) || !in_array($value[0], ['null', 'not null']) && !isset($value[1]))
+            ) {
+                unset($where[$column]);
+            }
+        }
+        // 按照数据限制字段返回数据
+        if ($this->dataLimit === 'personal') {
+            $where[$this->dataLimitField] = JwtToken::getCurrentId();
+        } elseif ($this->dataLimit === 'auth') {
+            $primary_key = $this->model->getKeyName();
+            if (!Auth::isSupperAdmin() && (!isset($where[$primary_key]) || $this->dataLimitField != $primary_key)) {
+                $where[$this->dataLimitField] = ['in', Auth::getScopeAdminIds(true)];
+            }
+        }
+        return [$where, $format, $limit, $field, $order, $page];
+    }
+
+    /**
+     * 指定查询where条件,并没有真正的查询数据库操作
+     * @param array $where
+     * @param string|null $field
+     * @param string $order
+     * @return EloquentBuilder|QueryBuilder|Model
+     */
+    protected function doSelect(array $where, string $field = null, string $order = 'desc')
+    {
+        $model = $this->model;
+        foreach ($where as $column => $value) {
+            if (is_array($value)) {
+                if ($value[0] === 'like' || $value[0] === 'not like') {
+                    $model = $model->where($column, $value[0], "%$value[1]%");
+                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
+                    $model = $model->where($column, $value[0], $value[1]);
+                } elseif ($value[0] == 'in' && !empty($value[1])) {
+                    $valArr = $value[1];
+                    if (is_string($value[1])) {
+                        $valArr = explode(",", trim($value[1]));
+                    }
+                    $model = $model->whereIn($column, $valArr);
+                } elseif ($value[0] == 'not in' && !empty($value[1])) {
+                    $valArr = $value[1];
+                    if (is_string($value[1])) {
+                        $valArr = explode(",", trim($value[1]));
+                    }
+                    $model = $model->whereNotIn($column, $valArr);
+                } elseif ($value[0] == 'null') {
+                    $model = $model->whereNull($column);
+                } elseif ($value[0] == 'not null') {
+                    $model = $model->whereNotNull($column);
+                } elseif ($value[0] !== '' || $value[1] !== '') {
+                    $model = $model->whereBetween($column, $value);
+                }
+            } else {
+                $model = $model->where($column, $value);
+            }
+        }
+        if ($field) {
+            $model = $model->orderBy($field, $order);
+        }
+        return $model;
+    }
+
+    /**
+     * 执行真正查询,并返回格式化数据
+     * @param $query
+     * @param $format
+     * @param $limit
+     * @return Response
+     */
+    protected function doFormat($query, $format, $limit): Response
+    {
+        $methods = [
+            'select' => 'formatSelect',
+            'tree' => 'formatTree',
+            'table_tree' => 'formatTableTree',
+            'normal' => 'formatNormal',
+        ];
+        $paginator = $query->paginate($limit);
+        $total = $paginator->total();
+        $items = $paginator->items();
+        if (method_exists($this, "afterQuery")) {
+            $items = call_user_func([$this, "afterQuery"], $items);
+        }
+        $format_function = $methods[$format] ?? 'formatNormal';
+        return call_user_func([$this, $format_function], $items, $total);
+    }
+
+    /**
+     * 插入前置方法
+     * @param Request $request
+     * @return array
+     * @throws BusinessException
+     */
+    protected function insertInput(Request $request): array
+    {
+        $data = $this->inputFilter($request->post());
+        $password_filed = 'password';
+        if (isset($data[$password_filed])) {
+            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
+        }
+
+        if (!Auth::isSupperAdmin() && $this->dataLimit) {
+            if (!empty($data[$this->dataLimitField])) {
+                $admin_id = $data[$this->dataLimitField];
+                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
+                    throw new BusinessException('无数据权限');
+                }
+            }
+        }
+        return $data;
+    }
+
+    /**
+     * 执行插入
+     * @param array $data
+     * @return mixed|null
+     */
+    protected function doInsert(array $data)
+    {
+        $primary_key = $this->model->getKeyName();
+        $model_class = get_class($this->model);
+        $model = new $model_class;
+        foreach ($data as $key => $val) {
+            $model->{$key} = $val;
+        }
+        $model->save();
+        return $primary_key ? $model->$primary_key : null;
+    }
+
+    /**
+     * 更新前置方法
+     * @param Request $request
+     * @return array
+     * @throws BusinessException
+     */
+    protected function updateInput(Request $request): array
+    {
+        $primary_key = $this->model->getKeyName();
+        $id = $request->post($primary_key);
+        $data = $this->inputFilter($request->post());
+        $model = $this->model->find($id);
+        if (!$model) {
+            throw new BusinessException('记录不存在', 2);
+        }
+        if (!Auth::isSupperAdmin() && $this->dataLimit) {
+            $scopeAdminIds = Auth::getScopeAdminIds(true);
+            $admin_ids = [
+                $data[$this->dataLimitField] ?? false, // 检查要更新的数据admin_id是否是有权限的值
+                $model->{$this->dataLimitField} ?? false // 检查要更新的记录的admin_id是否有权限
+            ];
+            foreach ($admin_ids as $admin_id) {
+                if ($admin_id && !in_array($admin_id, $scopeAdminIds)) {
+                    throw new BusinessException('无数据权限');
+                }
+            }
+        }
+        $password_filed = 'password';
+        if (isset($data[$password_filed])) {
+            // 密码为空,则不更新密码
+            if ($data[$password_filed] === '') {
+                unset($data[$password_filed]);
+            } else {
+                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
+            }
+        }
+        unset($data[$primary_key]);
+        return [$id, $data];
+    }
+
+    /**
+     * 执行更新
+     * @param $id
+     * @param $data
+     * @return void
+     */
+    protected function doUpdate($id, $data)
+    {
+        $model = $this->model->find($id);
+        foreach ($data as $key => $val) {
+            $model->{$key} = $val;
+        }
+        $model->save();
+    }
+
+    /**
+     * 对用户输入表单过滤
+     * @param array $data
+     * @return array
+     * @throws BusinessException
+     */
+    protected function inputFilter(array $data): array
+    {
+        $table = config('database.connections.mysql.prefix') . $this->model->getTable();
+        $allow_column = $this->model->getConnection()->select("desc `$table`");
+        if (!$allow_column) {
+            throw new BusinessException('表不存在', 2);
+        }
+        $columns = array_column($allow_column, 'Type', 'Field');
+        foreach ($data as $col => $item) {
+            if (!isset($columns[$col])) {
+                unset($data[$col]);
+                continue;
+            }
+            // 非字符串类型传空则为null
+            if ($item === '' && strpos(strtolower($columns[$col]), 'varchar') === false && strpos(strtolower($columns[$col]), 'text') === false) {
+                $data[$col] = null;
+            }
+            if (is_array($item)) {
+                $data[$col] = implode(',', $item);
+            }
+        }
+        if (empty($data['created_at'])) {
+            unset($data['created_at']);
+        }
+        if (empty($data['updated_at'])) {
+            unset($data['updated_at']);
+        }
+        return $data;
+    }
+
+    /**
+     * 删除前置方法
+     * @param Request $request
+     * @return array
+     * @throws BusinessException
+     */
+    protected function deleteInput(Request $request): array
+    {
+        $primary_key = $this->model->getKeyName();
+        if (!$primary_key) {
+            throw new BusinessException('该表无主键,不支持删除');
+        }
+        $ids = (array)$request->post($primary_key, []);
+        if (!Auth::isSupperAdmin() && $this->dataLimit) {
+            $admin_ids = $this->model->where($primary_key, $ids)->pluck($this->dataLimitField)->toArray();
+            if (array_diff($admin_ids, Auth::getScopeAdminIds(true))) {
+                throw new BusinessException('无数据权限');
+            }
+        }
+        return $ids;
+    }
+
+    /**
+     * 执行删除
+     * @param array $ids
+     * @return void
+     */
+    protected function doDelete(array $ids)
+    {
+        if (!$ids) {
+            return;
+        }
+        $primary_key = $this->model->getKeyName();
+        $this->model->whereIn($primary_key, $ids)->delete();
+    }
+
+    /**
+     * 格式化树
+     * @param $items
+     * @return Response
+     */
+    protected function formatTree($items): Response
+    {
+        $format_items = [];
+        foreach ($items as $item) {
+            $format_items[] = [
+                'name' => $item->title ?? $item->name ?? $item->id,
+                'value' => (string)$item->id,
+                'id' => $item->id,
+                'pid' => $item->pid,
+            ];
+        }
+        $tree = new Tree($format_items);
+        return json_success('success', $tree->getTree());
+    }
+
+    /**
+     * 格式化表格树
+     * @param $items
+     * @return Response
+     */
+    protected function formatTableTree($items): Response
+    {
+        $tree = new Tree($items);
+        return json_success('success', $tree->getTree());
+    }
+
+    /**
+     * 格式化下拉列表
+     * @param $items
+     * @return Response
+     */
+    protected function formatSelect($items): Response
+    {
+        $formatted_items = [];
+        foreach ($items as $item) {
+            $formatted_items[] = [
+                'name' => $item->title ?? $item->name ?? $item->id,
+                'value' => $item->id
+            ];
+        }
+        return json_success('success', $formatted_items);
+    }
+
+    /**
+     * 通用格式化
+     * @param $items
+     * @param $total
+     * @return Response
+     */
+    protected function formatNormal($items, $total): Response
+    {
+        return json(['code' => 0, 'msg' => 'success', 'count' => $total, 'data' => $items]);
+    }
+
+    /**
+     * 查询数据库后置方法,可用于修改数据
+     * @param mixed $items 原数据
+     * @return mixed 修改后数据
+     */
+    protected function afterQuery($items)
+    {
+        return $items;
+    }
+}

+ 16 - 0
app/model/CinemaPerformers.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace app\model;
+
+use support\Model;
+
+class CinemaPerformers extends Model
+{
+    protected $table = 'cinema_performers';
+
+    protected $primaryKey = 'performers_id';
+
+    protected $dateFormat = 'U';
+    public const CREATED_AT = 'performers_create_time';
+    public const UPDATED_AT = 'performers_update_time';
+}

+ 12 - 0
route/api.php

@@ -82,4 +82,16 @@ Route::group('/admin', function () {
             Route::delete('/delete/{id:\d+}', [\app\admin\controller\sys_manage\Config::class, 'delConfig']);
         });
     });
+
+    /* 业务支撑 */
+    Route::group('/life', function () {
+        Route::group('/cinemaPerformers', function () {
+            Route::get('/list',[\app\admin\controller\life\CinemaPerformers::class,'select']);
+            Route::post('/add',[\app\admin\controller\life\CinemaPerformers::class,'insert']);
+            Route::post('/update',[\app\admin\controller\life\CinemaPerformers::class,'insert']);
+            Route::delete('/delete',[\app\admin\controller\life\CinemaPerformers::class,'delete']);
+        })->middleware([
+            \app\middleware\AdminAuthCheck::class
+        ]);
+    });
 });