Martin 5 anni fa
parent
commit
29dbc24890

+ 0 - 31
app/AppService.php

@@ -1,31 +0,0 @@
-<?php
-declare (strict_types=1);
-
-namespace app;
-
-use think\Service;
-use think\facade\Log;
-use think\facade\Request;
-
-/**
- * 应用服务类
- */
-class AppService extends Service
-{
-    // 服务注册
-    public function register()
-    {
-
-    }
-
-    // 服务启动
-    public function boot()
-    {
-//        // 记录访问日志
-//        if (!is_debug()) {
-//            Log::record('[ URL ] ' . print_r(Request::baseUrl(), true), 'begin');
-//            Log::record('[ HEADER ] ' . print_r(Request::header(), true), 'begin');
-//            Log::record('[ PARAM ] ' . print_r(Request::param(), true), 'begin');
-//        }
-    }
-}

+ 0 - 103
app/BaseController.php

@@ -1,103 +0,0 @@
-<?php
-// +----------------------------------------------------------------------
-// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
-// +----------------------------------------------------------------------
-// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
-// +----------------------------------------------------------------------
-// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
-// +----------------------------------------------------------------------
-// | Author: 萤火科技 <admin@yiovo.com>
-// +----------------------------------------------------------------------
-declare (strict_types = 1);
-
-namespace app;
-
-use think\App;
-use think\exception\ValidateException;
-use think\Validate;
-
-/**
- * 控制器基础类
- */
-abstract class BaseController
-{
-    /**
-     * Request实例
-     * @var \think\Request
-     */
-    protected $request;
-
-    /**
-     * 应用实例
-     * @var \think\App
-     */
-    protected $app;
-
-    /**
-     * 是否批量验证
-     * @var bool
-     */
-    protected $batchValidate = false;
-
-    /**
-     * 控制器中间件
-     * @var array
-     */
-    protected $middleware = [];
-
-    /**
-     * 构造方法
-     * @access public
-     * @param  App  $app  应用对象
-     */
-    public function __construct(App $app)
-    {
-        $this->app     = $app;
-        $this->request = $this->app->request;
-
-        // 控制器初始化
-        $this->initialize();
-    }
-
-    // 初始化
-    protected function initialize()
-    {}
-
-    /**
-     * 验证数据
-     * @access protected
-     * @param  array        $data     数据
-     * @param  string|array $validate 验证器名或者验证规则数组
-     * @param  array        $message  提示信息
-     * @param  bool         $batch    是否批量验证
-     * @return array|string|true
-     * @throws ValidateException
-     */
-    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
-    {
-        if (is_array($validate)) {
-            $v = new Validate();
-            $v->rule($validate);
-        } else {
-            if (strpos($validate, '.')) {
-                // 支持场景
-                [$validate, $scene] = explode('.', $validate);
-            }
-            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
-            $v     = new $class();
-            if (!empty($scene)) {
-                $v->scene($scene);
-            }
-        }
-
-        $v->message($message);
-
-        // 是否批量验证
-        if ($batch || $this->batchValidate) {
-            $v->batch(true);
-        }
-
-        return $v->failException(true)->check($data);
-    }
-
-}

+ 0 - 11
app/Request.php

@@ -1,11 +0,0 @@
-<?php
-
-namespace app;
-
-// 应用请求对象类
-class Request extends \think\Request
-{
-    // 全局过滤规则
-    protected $filter = ['my_trim', 'my_htmlspecialchars', 'filter_emoji'];
-
-}

+ 4 - 3
app/provider.php

@@ -1,9 +1,10 @@
 <?php
-use app\ExceptionHandle;
-use app\Request;
+
+use cores\Request;
+use cores\ExceptionHandle;
 
 // 容器Provider定义文件
 return [
-    'think\Request'          => Request::class,
+    'think\Request' => Request::class,
     'think\exception\Handle' => ExceptionHandle::class,
 ];

+ 1 - 1
app/service.php

@@ -1,6 +1,6 @@
 <?php
 
-use app\AppService;
+use cores\AppService;
 
 // 系统服务定义文件
 // 服务在完成全局初始化之后执行

+ 40 - 0
cores/AppService.php

@@ -0,0 +1,40 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace cores;
+
+use think\Service;
+use think\facade\Log;
+use think\facade\Request;
+
+/**
+ * 应用服务类
+ */
+class AppService extends Service
+{
+    // 服务注册
+    public function register()
+    {
+
+    }
+
+    // 服务启动
+    public function boot()
+    {
+//        // 记录访问日志
+//        if (!is_debug()) {
+//            Log::record('[ URL ] ' . print_r(Request::baseUrl(), true), 'begin');
+//            Log::record('[ HEADER ] ' . print_r(Request::header(), true), 'begin');
+//            Log::record('[ PARAM ] ' . print_r(Request::param(), true), 'begin');
+//        }
+    }
+}

+ 296 - 0
cores/BaseController.php

@@ -0,0 +1,296 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace cores;
+
+use Exception;
+use think\App;
+use think\Validate;
+use cores\authorize\Http;
+use cores\authorize\Tools;
+use cores\authorize\AuthFile;
+use app\common\exception\BaseException;
+use think\exception\ValidateException;
+
+/**
+ * 控制器基础类
+ */
+abstract class BaseController
+{
+    /**
+     * Request实例
+     * @var \think\Request
+     */
+    protected $request;
+
+    /**
+     * 应用实例
+     * @var \think\App
+     */
+    protected $app;
+
+    /**
+     * 是否批量验证
+     * @var bool
+     */
+    protected $batchValidate = false;
+
+    /**
+     * 控制器中间件
+     * @var array
+     */
+    protected $middleware = [];
+
+    // 当前是否初始化了 [如果为false 那么基类里的方法不允许被调用]
+    private $isInitialized = false;
+
+    /**
+     * 构造方法
+     * BaseController constructor.
+     * @param App $app
+     * @throws BaseException
+     */
+    public function __construct(App $app)
+    {
+        $this->app = $app;
+        $this->request = $this->app->request;
+
+        // 控制器初始化
+        $this->initialize();
+
+        // 授权验证
+        $this->authorize();
+    }
+
+    // 初始化
+    protected function initialize()
+    {
+    }
+
+    /**
+     * 系统授权验证
+     * @throws BaseException
+     */
+    private final function authorize()
+    {
+        // 验证auth文件是否合法[3.1%概率]
+        Tools::probability(3.1) && $this->___();
+        // 验证授权域名是否合法[0.4%概率]
+        Tools::probability(0.4) && $this->____();
+        // 标记为已初始化
+        $this->isInitialized = true;
+    }
+
+    /**
+     * 验证auth文件是否合法
+     * @return bool
+     * @throws BaseException
+     */
+    private final function ___()
+    {
+        $this->o00oo000o();
+        return true;
+    }
+
+    /**
+     * 验证授权域名是否合法
+     * @return mixed|bool
+     * @throws BaseException
+     */
+    private final function ____()
+    {
+        // 获取当前域名
+        $host = $this->o0ooo00oo();
+        // 实例化一个http类
+        $Http = $this->o0ooo000o();
+        // 请求api:根据域名查询是否已授权
+        $result = $Http->domain($host);
+        $result === false && throwError('很抱歉,检测到域名授权异常,系统将无法正常运行');
+        return $result;
+    }
+
+    /**
+     * 实例化一个http类
+     * @return Http
+     * @throws BaseException
+     */
+    private final function o0ooo000o()
+    {
+        // 获取auth文件中的注册码数据[解密后的]
+        $authData = $this->o00oo000o();
+        // 实例化一个http类
+        $Http = new Http();
+        $Http->setAppToken($authData['AppID'], $authData['AppSecret']);
+        return $Http;
+    }
+
+    /**
+     * 获取auth文件中的注册码数据[解密后的]
+     * @return array
+     * @throws BaseException
+     */
+    private final function o00oo000o()
+    {
+        // 获取auth文件中的注册码数据[解密后的]
+        $AuthFile = AuthFile::getInstance();
+        $auth = $AuthFile->getAuthFile();
+        $authData = $AuthFile->getActivationData($auth);
+        $this->oo0000oo($auth, $authData);
+        return $authData;
+    }
+
+    /**
+     * 比较授权文件合法性(明文和密文是否吻合)
+     * @param array $auth
+     * @param array $authData
+     * @return bool
+     * @throws BaseException
+     * @throws \Exception
+     */
+    private final function oo0000oo(array $auth, array $authData)
+    {
+        // 验证授权文件签名
+        $temp = Tools::pick($auth, ['name', 'contact', 'UserKey', 'AppID', 'expirationTime', 'ActivationCode', 'CoreData']);
+        $sign = Tools::myhash(Tools::jsonEncode($temp) . "_{$temp['UserKey']}", 32);
+        if ($sign !== $auth['sign']) {
+            throwError('很抱歉,检测到授权文件异常,系统将无法正常运行,请检查后端根目录auth文件是否被篡改');
+        }
+        // 验证授权文件到期时间
+        $date = new \DateTime($authData['expirationTime']);
+        if (date('Ymd') > $date->format('Ymd')) {
+            throwError('很抱歉,检测到授权文件授权时间已过期,系统将无法正常运行');
+        }
+        return true;
+    }
+
+    /**
+     * 获取当前域名
+     * @return string
+     */
+    private final function o0ooo00oo()
+    {
+        $host = strval($_SERVER['HTTP_X_FORWARDED_HOST'] ?? getenv()['HTTP_HOST']);
+        if (request()->host() !== $host) {
+            return '';
+        }
+        return request()->host();
+    }
+
+    /**
+     * 验证当前是否已经初始化过
+     * @throws Exception
+     */
+    private final function checkInitialized()
+    {
+        if (!$this->isInitialized) {
+            throw new Exception('Currently not initialized');
+        }
+    }
+
+    /**
+     * 验证数据
+     * @access protected
+     * @param array $data 数据
+     * @param string|array $validate 验证器名或者验证规则数组
+     * @param array $message 提示信息
+     * @param bool $batch 是否批量验证
+     * @return array|string|true
+     * @throws ValidateException
+     */
+    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
+    {
+        if (is_array($validate)) {
+            $v = new Validate();
+            $v->rule($validate);
+        } else {
+            if (strpos($validate, '.')) {
+                // 支持场景
+                [$validate, $scene] = explode('.', $validate);
+            }
+            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
+            $v = new $class();
+            if (!empty($scene)) {
+                $v->scene($scene);
+            }
+        }
+
+        $v->message($message);
+
+        // 是否批量验证
+        if ($batch || $this->batchValidate) {
+            $v->batch(true);
+        }
+
+        return $v->failException(true)->check($data);
+    }
+
+    /**
+     * 返回封装后的 API 数据到客户端
+     * @param int|null $status
+     * @param string $message
+     * @param array $data
+     * @return \think\response\Json|array
+     */
+    protected final function renderJson(int $status = null, string $message = '', array $data = [])
+    {
+        $this->checkInitialized();
+        return json(compact('status', 'message', 'data'));
+    }
+
+    /**
+     * 返回操作成功json
+     * @param array|string $data
+     * @param string $message
+     * @return array
+     */
+    protected final function renderSuccess($data = [], string $message = 'success')
+    {
+        if (is_string($data)) {
+            $message = $data;
+            $data = [];
+        }
+        return $this->renderJson(config('status.success'), $message, $data);
+    }
+
+    /**
+     * 返回操作失败json
+     * @param string $message
+     * @param array $data
+     * @return array
+     */
+    protected final function renderError(string $message = 'error', array $data = [])
+    {
+        return $this->renderJson(config('status.error'), $message, $data);
+    }
+
+    /**
+     * 获取post数据 (数组)
+     * @param $key
+     * @return mixed
+     */
+    protected final function postData($key = null)
+    {
+        $this->checkInitialized();
+        return $this->request->post(empty($key) ? '' : "{$key}/a");
+    }
+
+    /**
+     * 获取post数据 (数组)
+     * @param $key
+     * @return mixed
+     */
+    protected final function postForm($key = 'form')
+    {
+        return $this->postData($key);
+    }
+
+}

+ 367 - 0
cores/BaseModel.php

@@ -0,0 +1,367 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace cores;
+
+use think\Model;
+use think\db\Query;
+use think\Paginator;
+use think\model\Collection;
+use cores\extension\ModelExt;
+use app\common\exception\BaseException;
+
+/**
+ * 模型基类
+ * Class BaseModel
+ * @package app\common\model
+ */
+abstract class BaseModel extends Model
+{
+    // 当前访问的商城ID
+    public static $storeId;
+
+    // 定义表名
+    protected $name;
+
+    // 模型别名
+    protected $alias = '';
+
+    // 定义全局的查询范围
+    protected $globalScope = ['store_id'];
+
+    // 是否允许全局查询store_id
+    protected $isGlobalScopeStoreId = true;
+
+    // 错误信息
+    protected $error = '';
+
+    // 模型基类扩展
+    /* @var ModelExt $ModelExt */
+    private static $ModelExt;
+
+    /**
+     * 模型基类初始化
+     * @throws BaseException
+     */
+    public static function init()
+    {
+        parent::init();
+        // 绑定ModelExt
+        if (!self::$ModelExt) {
+            self::$ModelExt = ModelExt::getInstance();
+        }
+        // 绑定store_id
+        self::getStoreId();
+    }
+
+    /**
+     * 获取当前操作的商城ID
+     * @return int|null
+     */
+    private static function getStoreId()
+    {
+        if (empty(self::$storeId) && in_array(app_name(), ['store', 'api'])) {
+            self::$storeId = getStoreId();
+        }
+        return self::$storeId;
+    }
+
+    /**
+     * 获取当前调用来源的应用名称
+     * 例如:admin, api, store
+     * @return string|bool
+     */
+    protected final static function getCalledModule()
+    {
+        if (preg_match('/app\\\(\w+)/', get_called_class(), $class)) {
+            return $class[1];
+        }
+        return 'common';
+    }
+
+    /**
+     * 查找单条记录
+     * @param mixed $data 查询条件
+     * @param array $with 关联查询
+     * @return array|static|null
+     */
+    public static function get($data, $with = [])
+    {
+        try {
+            $query = (new static)->with($with);
+            return is_array($data) ? $query->where($data)->find() : $query->find((int)$data);
+        } catch (\Exception $e) {
+            return null;
+        }
+    }
+
+    /**
+     * 定义全局的查询范围
+     * @param Query $query
+     * @return bool
+     */
+    public function scopeStore_id(Query $query)
+    {
+        if (!$this->isGlobalScopeStoreId) return false;
+        $storeId = self::getStoreId();
+        $storeId > 0 && $query->where($query->getTable() . '.store_id', $storeId);
+        return true;
+    }
+
+    /**
+     * 设置默认的检索数据
+     * @param array $query
+     * @param array $default
+     * @return array
+     */
+    public function setQueryDefaultValue(array $query, array $default = [])
+    {
+        $data = array_merge($default, $query);
+        foreach ($query as $field => $value) {
+            // 不存在默认值跳出循环
+            if (!isset($default[$field])) continue;
+            // 如果传参为空, 设置默认值
+            if (empty($value) && $value !== '0') {
+                $data[$field] = $default[$field];
+            }
+        }
+        return $data;
+    }
+
+    /**
+     * 设置基础查询条件(用于简化基础alias和field)
+     * @param string $alias
+     * @param array $join
+     * @return static
+     */
+    public function setBaseQuery($alias = '', $join = [])
+    {
+        // 设置别名
+        $aliasValue = $alias ?: $this->alias;
+        $query = $this->alias($aliasValue)->field("{$aliasValue}.*");
+        // join条件
+        if (!empty($join)) : foreach ($join as $item):
+            $query->join($item[0], "{$item[0]}.{$item[1]}={$aliasValue}."
+                . (isset($item[2]) ? $item[2] : $item[1]));
+        endforeach; endif;
+        return $query;
+    }
+
+    /**
+     * 批量更新多条数据(支持带where条件)
+     * @param iterable $dataSet [0 => ['data'=>[], 'where'=>[]]]
+     * @return array|false
+     */
+    public function updateAll(iterable $dataSet)
+    {
+        if (empty($dataSet)) {
+            return false;
+        }
+        return $this->transaction(function () use ($dataSet) {
+            $result = [];
+            foreach ($dataSet as $key => $item) {
+                $result[$key] = self::updateBase($item['data'], $item['where']);
+            }
+            return $result;
+        });
+    }
+
+    /**
+     * 批量新增数据
+     * @param iterable $dataSet [0 => ['id'=>10001, 'name'=>'wang']]
+     * @return array|false
+     */
+    public function addAll(iterable $dataSet)
+    {
+        if (empty($dataSet)) {
+            return false;
+        }
+        return $this->transaction(function () use ($dataSet) {
+            $result = [];
+            foreach ($dataSet as $key => $item) {
+                $result[$key] = self::create($item, $this->field);
+            }
+            return $result;
+        });
+    }
+
+    /**
+     * 删除记录
+     * @param array $where
+     *  方式1: ['goods_id' => $goodsId]
+     *  方式2: [
+     *           ['store_user_id', '=', $storeUserId],
+     *           ['role_id', 'in', $deleteRoleIds]
+     *        ]
+     * @return int
+     */
+    public static function deleteAll(array $where)
+    {
+        return (new static)->where($where)->delete();
+    }
+
+    /**
+     * 返回错误信息
+     * @return string
+     */
+    public function getError()
+    {
+        return empty($this->error) ? false : $this->error;
+    }
+
+    /**
+     * 字段值增长
+     * @param array|int|bool $where
+     * @param string $field
+     * @param float $step
+     * @return mixed
+     */
+    protected function setInc($where, string $field, float $step = 1)
+    {
+        if (is_numeric($where)) {
+            $where = [$this->getPk() => (int)$where];
+        }
+        return $this->where($where)->inc($field, $step)->update();
+    }
+
+    /**
+     * 字段值消减
+     * @param array|int|bool $where
+     * @param string $field
+     * @param float $step
+     * @return mixed
+     */
+    protected function setDec($where, string $field, float $step = 1)
+    {
+        return $this->where($where)->dec($field, $step)->update();
+    }
+
+    /**
+     * 实例化新查询对象
+     * @return \think\db\BaseQuery
+     */
+    protected function getNewQuery()
+    {
+        return $this->db();
+    }
+
+    /**
+     * 新增hidden属性
+     * @param array $hidden
+     * @return $this
+     */
+    protected function addHidden(array $hidden)
+    {
+        $this->hidden = array_merge($this->hidden, $hidden);
+        return $this;
+    }
+
+    /**
+     * 生成字段列表(字段加上$alias别名)
+     * @param string $alias 别名
+     * @param array $withoutFields 排除的字段
+     * @return array
+     */
+    protected function getAliasFields(string $alias, $withoutFields = [])
+    {
+        $fields = array_diff($this->getTableFields(), $withoutFields);
+        foreach ($fields as &$field) {
+            $field = "$alias.$field";
+        }
+        return $fields;
+    }
+
+    /**
+     * 更新数据[单条]
+     * @param array|int $where 更新条件默认arra, 也支持传参int, 但必须是主键id
+     * @param array $data 更新的数据内容
+     * @return bool
+     */
+    public static function updateOne($where, array $data): bool
+    {
+        $model = new static;
+        return self::$ModelExt->updateOne($model, $where, $data);
+    }
+
+    /**
+     * 更新数据[批量] 如果只更新单条记录请使用 updateOne方法
+     * @param array $data 更新的数据内容
+     * @param array $where 更新条件
+     * @param array $allowField 允许的字段
+     * @return bool
+     */
+    public static function updateBase(array $data, array $where, array $allowField = []): bool
+    {
+        $model = new static;
+        return self::$ModelExt->updateBase($model, $data, $where, $allowField);
+    }
+
+    /**
+     * 设置模型的更新条件
+     * @access protected
+     * @param mixed $where 更新条件
+     * @return static
+     */
+    public function mySetUpdateWhere($where)
+    {
+        parent::setUpdateWhere($where);
+        return $this;
+    }
+
+    /**
+     * 合并设置项
+     * @param array $confusion 系统默认配置
+     * @param array $variable 用户自定义
+     * @param string $_ 数据来源[后期加载附加数据]
+     * @param false $__ 是否只显示value
+     * @return array
+     */
+    protected static function reorganize(array $confusion, array $variable, string $_ = 'cache', $__ = false)
+    {
+        return self::$ModelExt->reorganize($confusion, $variable, $_, $__);
+    }
+
+    /**
+     * 仅返回values数据
+     * @param array $setting 全部设置
+     * @param bool $setKey 是否设置键值
+     * @return array
+     */
+    public final static function getValues(array $setting, bool $setKey = true)
+    {
+        return self::$ModelExt->getValues($setting, $setKey);
+    }
+
+    /**
+     * 加载关联数据 [列表数据类型]
+     * @param iterable $dataSet 数据集
+     * @param array $with 关联方法名 例如: ['user']; 支持嵌套['user.avatar'] ['user' => 'avatar']
+     * @param bool $isToArray 是否用数组格式输出
+     * @return Collection|Paginator|iterable
+     */
+    public static final function preload(iterable $dataSet, array $with, bool $isToArray = false)
+    {
+        return self::$ModelExt->preload($dataSet, $with, $isToArray);
+    }
+
+    /**
+     * 加载关联数据 [单条数据类型]
+     * @param mixed $model
+     * @param array $with 关联方法名 例如: ['user']; 不支持嵌套
+     * @return Model|static|false
+     */
+    public static final function related($model, array $with)
+    {
+        return self::$ModelExt->related($model, $with);
+    }
+
+}

+ 10 - 2
app/ExceptionHandle.php → cores/ExceptionHandle.php

@@ -1,6 +1,14 @@
 <?php
-
-namespace app;
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+namespace cores;
 
 use Throwable;
 use think\Response;

+ 19 - 0
cores/Request.php

@@ -0,0 +1,19 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+namespace cores;
+
+// 应用请求对象类
+class Request extends \think\Request
+{
+    // 全局过滤规则
+    protected $filter = ['my_trim', 'my_htmlspecialchars', 'filter_emoji'];
+
+}

+ 101 - 0
cores/middleware/AllowCrossDomain.php

@@ -0,0 +1,101 @@
+<?php
+// +----------------------------------------------------------------------
+// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
+// +----------------------------------------------------------------------
+// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
+// +----------------------------------------------------------------------
+// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
+// +----------------------------------------------------------------------
+// | Author: 萤火科技 <admin@yiovo.com>
+// +----------------------------------------------------------------------
+declare (strict_types=1);
+
+namespace cores\middleware;
+
+use Closure;
+use think\Config;
+use think\Request;
+use think\Response;
+
+/**
+ * 跨域请求支持
+ * Class AllowCrossDomain
+ * @package cores\middleware
+ */
+class AllowCrossDomain
+{
+    // cookie的所属域名
+    protected $cookieDomain;
+
+    /**
+     * 构造方法
+     * AllowCrossDomain constructor.
+     * @param Config $config
+     */
+    public function __construct(Config $config)
+    {
+        $this->cookieDomain = $config->get('cookie.domain', '');
+    }
+
+    /**
+     * 获取允许跨域的header参数 [自定义]
+     * @return array
+     */
+    private function getCustomHeader()
+    {
+        return [
+            'Access-Token',
+            'storeId',
+            'platform',
+        ];
+    }
+
+    /**
+     * 获取允许跨域的header参数
+     * @return array
+     */
+    private function getHeader()
+    {
+        $headers = array_merge([
+            'Authorization', 'Content-Type', 'X-CSRF-TOKEN', 'X-Requested-With',
+            'If-Match', 'If-Modified-Since', 'If-None-Match', 'If-Unmodified-Since'
+        ], $this->getCustomHeader());
+
+        return [
+            // 允许所有域名访问
+            'Access-Control-Allow-Origin' => '*',
+            // 允许cookie跨域访问
+            'Access-Control-Allow-Credentials' => 'true',
+            // 预检请求的有效期
+            'Access-Control-Max-Age' => 1800,
+            // 允许跨域的方法
+            'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
+            // 跨域请求header头
+            'Access-Control-Allow-Headers' => implode(',', $headers),
+        ];
+    }
+
+    /**
+     * 允许跨域请求
+     * @access public
+     * @param Request $request
+     * @param Closure $next
+     * @param array|null $header
+     * @return Response
+     */
+    public function handle(Request $request, Closure $next, ?array $header = [])
+    {
+        $header = !empty($header) ? array_merge($this->getHeader(), $header) : $this->getHeader();
+        if (!isset($header['Access-Control-Allow-Origin'])) {
+            $origin = $request->header('origin');
+
+            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
+                $header['Access-Control-Allow-Origin'] = $origin;
+            } else {
+                $header['Access-Control-Allow-Origin'] = '*';
+            }
+        }
+        return $next($request)->header($header);
+    }
+
+}