From 8bb8f0919bdd4d50e9c4691fb9447390957395b7 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Tue, 26 Apr 2016 19:12:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9BLang=E7=B1=BB=20=E5=8E=BB?= =?UTF-8?q?=E9=99=A4=E6=97=A0=E7=94=A8=E7=9A=84=20traits\model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/think/Input.php | 8 +- library/think/Lang.php | 66 +++- library/traits/model/Adv.php | 351 ------------------- library/traits/model/Auto.php | 492 --------------------------- library/traits/model/Bulk.php | 144 -------- library/traits/model/Relation.php | 446 ------------------------ library/traits/model/Transaction.php | 80 ----- library/traits/model/View.php | 305 ----------------- 8 files changed, 55 insertions(+), 1837 deletions(-) delete mode 100644 library/traits/model/Adv.php delete mode 100644 library/traits/model/Auto.php delete mode 100644 library/traits/model/Bulk.php delete mode 100644 library/traits/model/Relation.php delete mode 100644 library/traits/model/Transaction.php delete mode 100644 library/traits/model/View.php diff --git a/library/think/Input.php b/library/think/Input.php index 28a565d5..57a84d42 100644 --- a/library/think/Input.php +++ b/library/think/Input.php @@ -11,6 +11,8 @@ namespace think; +use think\Config; + class Input { // 全局过滤规则 @@ -58,7 +60,7 @@ class Input } return self::data($_PUT, $name, $default, $filter, $merge); } - + /** * 获取delete变量 * @param string $name 数据名称 @@ -192,7 +194,7 @@ class Input public static function path($name = '', $default = null, $filter = null, $merge = false) { if (!empty($_SERVER['PATH_INFO'])) { - $depr = \think\Config::get('pathinfo_depr'); + $depr = Config::get('pathinfo_depr'); $input = explode($depr, trim($_SERVER['PATH_INFO'], $depr)); return self::data($input, $name, $default, $filter, $merge); } else { @@ -393,7 +395,7 @@ class Input { if (is_null(static::$filters)) { // 从配置项中读取 - $filters = \think\Config::get('default_filter'); + $filters = Config::get('default_filter'); static::$filters = empty($filters) ? [] : (is_array($filters) ? $filters : explode(',', $filters)); } return static::$filters; diff --git a/library/think/Lang.php b/library/think/Lang.php index c71d36e4..2a60fcbf 100644 --- a/library/think/Lang.php +++ b/library/think/Lang.php @@ -11,17 +11,23 @@ namespace think; -use think\Config; use think\Cookie; +use think\Log; class Lang { - // 语言参数 + // 语言数据 private static $lang = []; // 语言作用域 private static $range = 'zh-cn'; + // 语言自动侦测的变量 + protected static $langDetectVar = 'lang'; + // 语言Cookie变量 + protected static $langCookieVar = 'think_var'; + // 允许语言列表 + protected static $allowLangList = []; - // 设定语言参数的作用域(语言) + // 设定当前的语言 public static function range($range = '') { if ('' == $range) { @@ -35,7 +41,7 @@ class Lang * 设置语言定义(不区分大小写) * @param string|array $name 语言变量 * @param string $value 语言值 - * @param string $range 作用域 + * @param string $range 语言作用域 * @return mixed */ public static function set($name, $value = null, $range = '') @@ -55,7 +61,7 @@ class Lang /** * 加载语言定义(不区分大小写) * @param string $file 语言文件 - * @param string $range 作用域 + * @param string $range 语言作用域 * @return mixed */ public static function load($file, $range = '') @@ -89,7 +95,7 @@ class Lang * 获取语言定义(不区分大小写) * @param string|null $name 语言变量 * @param array $vars 变量替换 - * @param string $range 作用域 + * @param string $range 语言作用域 * @return mixed */ public static function get($name = null, $vars = [], $range = '') @@ -133,25 +139,53 @@ class Lang public static function detect() { // 自动侦测设置获取语言选择 - $langCookieVar = Config::get('lang_cookie_var'); - $langDetectVar = Config::get('lang_detect_var'); - $langSet = ''; - if (isset($_GET[$langDetectVar])) { + $langSet = ''; + if (isset($_GET[self::$langDetectVar])) { // url中设置了语言变量 - $langSet = strtolower($_GET[$langDetectVar]); - Cookie::set($langCookieVar, $langSet, 3600); - } elseif (Cookie::get($langCookieVar)) { + $langSet = strtolower($_GET[self::$langDetectVar]); + Cookie::set(self::$langCookieVar, $langSet, 3600); + } elseif (Cookie::get(self::$langCookieVar)) { // 获取上次用户的选择 - $langSet = strtolower(Cookie::get($langCookieVar)); + $langSet = strtolower(Cookie::get(self::$langCookieVar)); } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // 自动侦测浏览器语言 preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches); $langSet = strtolower($matches[1]); - Cookie::set($langCookieVar, $langSet, 3600); + Cookie::set(self::$langCookieVar, $langSet, 3600); } - if (in_array($langSet, Config::get('lang_list'))) { + if (empty(self::$allowLangList) || in_array($langSet, self::$allowLangList)) { // 合法的语言 self::$range = $langSet; } } + + /** + * 设置语言自动侦测的变量 + * @param string $var 变量名称 + * @return void + */ + public static function setLangDetectVar($var) + { + self::$langDetectVar = $var; + } + + /** + * 设置语言的cookie保存变量 + * @param string $var 变量名称 + * @return void + */ + public static function setLangCookieVar($var) + { + self::$langCookieVar = $var; + } + + /** + * 设置允许的语言列表 + * @param array $list 语言列表 + * @return void + */ + public static function setAllowLangList($list) + { + self::$allowLangList = $list; + } } diff --git a/library/traits/model/Adv.php b/library/traits/model/Adv.php deleted file mode 100644 index 257c3dd8..00000000 --- a/library/traits/model/Adv.php +++ /dev/null @@ -1,351 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace traits\model; - -trait Adv -{ - protected $optimLock = 'lock_version'; - - /** - * 利用__call方法重载 实现一些特殊的Model方法 (魔术方法) - * @access public - * @param string $method 方法名称 - * @param mixed $args 调用参数 - * @return mixed - */ - public function __call($method, $args) - { - if (strtolower(substr($method, 0, 3)) == 'top') { - // 获取前N条记录 - $count = substr($method, 3); - array_unshift($args, $count); - return call_user_func_array([ & $this, 'topN'], $args); - } else { - return parent::__call($method, $args); - } - } - - // 查询成功后的回调方法 - protected function _after_find(&$result, $options = []) - { - // 检查序列化字段 - $this->checkSerializeField($result); - // 缓存乐观锁 - $this->cacheLockVersion($result); - } - - // 查询数据集成功后的回调方法 - protected function _after_select(&$resultSet, $options = []) - { - // 检查序列化字段 - $resultSet = $this->checkListSerializeField($resultSet); - } - - // 写入前的回调方法 - protected function _before_insert(&$data, $options = []) - { - // 记录乐观锁 - $data = $this->recordLockVersion($data); - } - - // 更新前的回调方法 - protected function _before_update(&$data, $options = []) - { - // 检查乐观锁 - $pk = $this->getPK(); - if (isset($options['where'][$pk])) { - $id = $options['where'][$pk]; - if (!$this->checkLockVersion($id, $data)) { - return false; - } - } - // 检查只读字段 - $data = $this->checkReadonlyField($data); - } - - /** - * 记录乐观锁 - * @access protected - * @param array $data 数据对象 - * @return array - */ - protected function recordLockVersion($data) - { - // 记录乐观锁 - if ($this->optimLock && !isset($data[$this->optimLock])) { - if (in_array($this->optimLock, $this->fields, true)) { - $data[$this->optimLock] = 0; - } - } - return $data; - } - - /** - * 缓存乐观锁 - * @access protected - * @param array $data 数据对象 - * @return void - */ - protected function cacheLockVersion($data) - { - if ($this->optimLock) { - if (isset($data[$this->optimLock]) && isset($data[$this->getPk()])) { - // 只有当存在乐观锁字段和主键有值的时候才记录乐观锁 - $_SESSION[$this->name . '_' . $data[$this->getPk()] . '_lock_version'] = $data[$this->optimLock]; - } - } - } - - /** - * 检查乐观锁 - * @access protected - * @param integer $id 当前主键 - * @param array $data 当前数据 - * @return mixed - */ - protected function checkLockVersion($id, &$data) - { - // 检查乐观锁 - $identify = $this->name . '_' . $id . '_lock_version'; - if ($this->optimLock && isset($_SESSION[$identify])) { - $lock_version = $_SESSION[$identify]; - $vo = $this->field($this->optimLock)->find($id); - $_SESSION[$identify] = $lock_version; - $curr_version = $vo[$this->optimLock]; - if (isset($curr_version)) { - if ($curr_version > 0 && $lock_version != $curr_version) { - // 记录已经更新 - $this->error = 'record has update'; - return false; - } else { - // 更新乐观锁 - $save_version = $data[$this->optimLock]; - if ($save_version != $lock_version + 1) { - $data[$this->optimLock] = $lock_version + 1; - } - $_SESSION[$identify] = $lock_version + 1; - } - } - } - return true; - } - - /** - * 查找前N个记录 - * @access public - * @param integer $count 记录个数 - * @param array $options 查询表达式 - * @return array - */ - public function topN($count, $options = []) - { - $options['limit'] = $count; - return $this->select($options); - } - - /** - * 查询符合条件的第N条记录 - * 0 表示第一条记录 -1 表示最后一条记录 - * @access public - * @param integer $position 记录位置 - * @param array $options 查询表达式 - * @return mixed - */ - public function getN($position = 0, $options = []) - { - if ($position >= 0) { - // 正向查找 - $options['limit'] = $position . ',1'; - $list = $this->select($options); - return $list ? $list[0] : false; - } else { - // 逆序查找 - $list = $this->select($options); - return $list ? $list[count($list) - abs($position)] : false; - } - } - - /** - * 获取满足条件的第一条记录 - * @access public - * @param array $options 查询表达式 - * @return mixed - */ - public function first($options = []) - { - return $this->getN(0, $options); - } - - /** - * 获取满足条件的最后一条记录 - * @access public - * @param array $options 查询表达式 - * @return mixed - */ - public function last($options = []) - { - return $this->getN(-1, $options); - } - - /** - * 返回数据 - * @access public - * @param array $data 数据 - * @param string $type 返回类型 默认为数组 - * @return mixed - * @throws \think\Exception - */ - public function returnResult($data, $type = 'array') - { - - switch ($type) { - case 'array': - return $data; - case 'object': - return (object) $data; - default: // 允许用户自定义返回类型 - if (class_exists($type)) { - return new $type($data); - } else { - throw new \think\Exception(' class not exist :' . $type); - } - } - } - - /** - * 返回数据列表 - * @access protected - * @param array $resultSet 数据 - * @param string $type 返回类型 默认为数组 - * @return array - */ - protected function returnResultSet(&$resultSet, $type = '') - { - foreach ($resultSet as $key => $data) { - $resultSet[$key] = $this->returnResult($data, $type); - } - return $resultSet; - } - - // 检查返回数据的序列化字段 - protected function checkSerializeField(&$result) - { - // 检查序列化字段 - if (!empty($this->serializeField)) { - foreach ($this->serializeField as $key => $val) { - if (isset($result[$key])) { - $serialize = unserialize($result[$key]); - foreach ($serialize as $name => $value) { - $result[$name] = $value; - } - - unset($serialize, $result[$key]); - } - } - } - return $result; - } - - // 检查数据集的序列化字段 - protected function checkListSerializeField(&$resultSet) - { - // 检查序列化字段 - if (!empty($this->serializeField)) { - foreach ($this->serializeField as $key => $val) { - foreach ($resultSet as $k => $result) { - if (isset($result[$key])) { - $serialize = unserialize($result[$key]); - foreach ($serialize as $name => $value) { - $result[$name] = $value; - } - - unset($serialize, $result[$key]); - $resultSet[$k] = $result; - } - } - } - } - return $resultSet; - } - - /** - * 检查只读字段 - * @access protected - * @param array $data 数据 - * @return array - */ - protected function checkReadonlyField(&$data) - { - if (!empty($this->readonlyField)) { - foreach ($this->readonlyField as $key => $field) { - if (isset($data[$field])) { - unset($data[$field]); - } - } - } - return $data; - } - - /** - * 得到分表的的数据表名 - * @access public - * @param array $data 操作的数据 - * @return string - */ - public function getPartitionTableName($data = []) - { - // 对数据表进行分区 - if (isset($data[$this->partition['field']])) { - $field = $data[$this->partition['field']]; - switch ($this->partition['type']) { - case 'id': - // 按照id范围分表 - $step = $this->partition['expr']; - $seq = floor($field / $step) + 1; - break; - case 'year': - // 按照年份分表 - if (!is_numeric($field)) { - $field = strtotime($field); - } - $seq = date('Y', $field) - $this->partition['expr'] + 1; - break; - case 'mod': - // 按照id的模数分表 - $seq = ($field % $this->partition['num']) + 1; - break; - case 'md5': - // 按照md5的序列分表 - $seq = (ord(substr(md5($field), 0, 1)) % $this->partition['num']) + 1; - break; - default: - if (function_exists($this->partition['type'])) { - // 支持指定函数哈希 - $fun = $this->partition['type']; - $seq = (ord(substr($fun($field), 0, 1)) % $this->partition['num']) + 1; - } else { - // 按照字段的首字母的值分表 - $seq = (ord($field{0}) % $this->partition['num']) + 1; - } - } - return $this->getTableName() . '_' . $seq; - } else { - // 当设置的分表字段不在查询条件或者数据中 - // 进行联合查询,必须设定 partition['num'] - $tableName = []; - for ($i = 0; $i < $this->partition['num']; $i++) { - $tableName[] = 'SELECT * FROM ' . $this->getTableName() . '_' . ($i + 1); - } - return '( ' . implode(" UNION ", $tableName) . ') AS ' . $this->name; - } - } -} diff --git a/library/traits/model/Auto.php b/library/traits/model/Auto.php deleted file mode 100644 index e14ac872..00000000 --- a/library/traits/model/Auto.php +++ /dev/null @@ -1,492 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace traits\model; - -use think\Config; -use think\Lang; - -trait Auto -{ - /** - * 创建数据对象 但不保存到数据库 - * @access public - * @param mixed $data 创建数据 - * @param string $type 状态 - * @return mixed - */ - public function create($data = '', $type = '') - { - // 如果没有传值默认取POST数据 - if (empty($data)) { - $data = \think\Input::post(); - } elseif (is_object($data)) { - $data = get_object_vars($data); - } - // 验证数据 - if (empty($data) || !is_array($data)) { - $this->error = Lang::get('_DATA_TYPE_INVALID_'); - return false; - } - $pk = $this->getPk(); - // 状态 - $type = $type ? $type : (is_string($pk) && !empty($data[$pk]) ? self::MODEL_UPDATE : self::MODEL_INSERT); - $type = 1 << ($type - 1); - // 字段列表 - $keys = array_keys($data); - - // 检测提交字段的合法性 - if (isset($this->options['field'])) { - // $this->field('field1,field2...')->create() - $fields = $this->options['field']; - unset($this->options['field']); - } elseif (self::MODEL_INSERT == $type && isset($this->insertFields)) { - $fields = $this->insertFields; - } elseif (self::MODEL_UPDATE == $type && isset($this->updateFields)) { - $fields = $this->updateFields; - } - if (isset($fields)) { - if (is_string($fields)) { - $fields = explode(',', $fields); - } - // 判断令牌验证字段 - if (Config::get('token_on')) { - $fields[] = Config::get('token_name'); - } - - foreach ($keys as $i => $key) { - if (!in_array($key, $fields)) { - unset($keys[$i]); - unset($data[$key]); - } - } - } - - // 数据自动验证 - if (!$this->_autoValidation($data, $type)) { - return false; - } - - // 验证完成生成数据对象 - if (empty($this->options['link'])) { - // 开启字段检测并且没有关联表 则过滤非法字段数据 - $fields = $this->getFields(); - foreach ($keys as $i => $key) { - if (!in_array($key, $fields)) { - unset($data[$key]); - } - } - } - - // 创建完成对数据进行自动处理 - $this->_autoOperation($data, $type); - // 验证后的回调方法 - $this->_after_create($data, $this->options); - // 赋值当前数据对象 - $this->data = $data; - // 返回创建的数据以供其他调用 - return $data; - } - - // 创建数据对象后的回调方法 - protected function _after_create(&$data, $options) - { - } - - /** - * 使用正则验证数据 - * @access public - * @param string $value 要验证的数据 - * @param string $rule 验证规则 - * @return boolean - */ - public function regex($value, $rule) - { - static $validate = [ - 'require' => '/.+/', - 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', - 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/', - 'currency' => '/^\d+(\.\d+)?$/', - 'number' => '/^\d+$/', - 'zip' => '/^\d{6}$/', - 'integer' => '/^[-\+]?\d+$/', - 'double' => '/^[-\+]?\d+(\.\d+)?$/', - 'english' => '/^[A-Za-z]+$/', - ]; - // 检查是否有内置的正则表达式 - if (isset($validate[strtolower($rule)])) { - $rule = $validate[strtolower($rule)]; - } - return preg_match($rule, $value) === 1; - } - - /** - * 自动表单处理 - * @access public - * @param array $data 创建数据 - * @param string $type 创建类型 - * @return mixed - */ - protected function _autoOperation(&$data, $type) - { - if (isset($this->options['auto'])) { - if (false === $this->options['auto']) { - // 关闭自动完成 - return; - } else { - $_auto = $this->options['auto']; - unset($this->options['auto']); - if (empty($_auto) && !empty($this->auto)) { - $_auto = $this->auto; - } - } - } elseif (!empty($this->auto)) { - $_auto = $this->auto; - } - // 自动填充 - if (!empty($_auto)) { - foreach ($_auto as $key => $val) { - if (!is_numeric($key) && is_array(current($val)) && isset($data[$key])) { - foreach ($val as $k => $v) { - $this->_operationField($data[$key], $v, $type); - } - } else { - $this->_operationField($data, $val, $type); - } - } - } - return; - } - - /** - * 填充表单字段 - * @access private - * @param array $data 创建数据 - * @param array $auto 填充因子 - * @param string $type 创建类型 - * @return boolean - */ - private function _operationField(&$data, &$auto, $type) - { - // 填充因子定义格式 - // array('field','填充内容','填充时间','附加规则',[额外参数]) - if (empty($auto[2])) { - $flags = 1 << (self::MODEL_INSERT - 1); - } elseif (is_array($auto[2])) { - $flags = 0; - foreach ($auto[2] as $v) { - $flags |= 1 << ($v - 1); - } - } else { - $flags = 3 == $auto[2] ? 3 : 1 << ($auto[2] - 1); - } - // 检查填充条件 - if ($flags & $type) { - if (empty($auto[3])) { - $auto[3] = 'string'; - } - switch (trim($auto[3])) { - case 'function': // 使用函数进行填充 字段的值作为参数 - case 'callback': // 使用回调方法 - $args = isset($auto[4]) ? (array) $auto[4] : []; - if (is_string($auto[0]) && strpos($auto[0], ',')) { - $auto[0] = explode(',', $auto[0]); - } - if (is_array($auto[0])) { - // 支持多个字段验证 - foreach ($auto[0] as $field) { - $_data[$field] = isset($data[$field]) ? $data[$field] : null; - } - array_unshift($args, $_data); - } else { - array_unshift($args, isset($data[$auto[0]]) ? $data[$auto[0]] : null); - } - if ('function' == $auto[3]) { - $data[$auto[0]] = call_user_func_array($auto[1], $args); - } else { - $data[$auto[0]] = call_user_func_array([ & $this, $auto[1]], $args); - } - break; - case 'field': // 用其它字段的值进行填充 - $data[$auto[0]] = $data[$auto[1]]; - break; - case 'ignore': // 为空忽略 - if ($auto[1] === $data[$auto[0]]) { - unset($data[$auto[0]]); - } - break; - case 'string': - default: // 默认作为字符串填充 - $data[$auto[0]] = $auto[1]; - } - if (isset($data[$auto[0]]) && false === $data[$auto[0]]) { - unset($data[$auto[0]]); - } - } - } - - /** - * 自动表单验证 - * @access protected - * @param array $data 创建数据 - * @param string $type 创建类型 - * @return boolean - */ - protected function _autoValidation(&$data, $type) - { - if (isset($this->options['validate'])) { - if (false === $this->options['validate']) { - // 关闭自动验证 - return true; - } else { - $_validate = $this->options['validate']; - unset($this->options['validate']); - if (empty($_validate) && !empty($this->validate)) { - $_validate = $this->validate; - } - } - } elseif (!empty($this->validate)) { - $_validate = $this->validate; - } - // 属性验证 - if (!empty($_validate)) { - // 如果设置了数据自动验证则进行数据验证 - if ($this->patchValidate) { - // 重置验证错误信息 - $this->error = []; - } - foreach ($_validate as $key => $val) { - if (!is_numeric($key) && is_array(current($val)) && isset($data[$key])) { - foreach ($val as $k => $v) { - if (false === $this->_validationField($data[$key], $v, $type)) { - return false; - } - } - } else { - if (false === $this->_validationField($data, $val, $type)) { - return false; - } - } - } - // 批量验证的时候最后返回错误 - if (!empty($this->error)) { - return false; - } - } - return true; - } - - /** - * 验证表单字段 支持批量验证 - * 如果批量验证返回错误的数组信息 - * @access protected - * @param array $data 创建数据 - * @param array $val 验证因子 - * @param string $type 创建类型 - * @return boolean - */ - protected function _validationField(&$data, &$val, $type) - { - // 如果是批量验证,并且当前字段已经有规则验证没有通过则跳过 - if ($this->patchValidate && isset($this->error[$val[0]])) { - return true; - } - // 验证因子定义格式 - // [field,rule,message,condition,type,when,params] - if (empty($val[5])) { - $flags = 1 << (self::MODEL_BOTH - 1); - } elseif (is_array($val[5])) { - $flags = 0; - foreach ($val[5] as $v) { - $flags |= 1 << ($v - 1); - } - } else { - $flags = 3 == $val[5] ? 3 : 1 << ($val[5] - 1); - } - // 判断是否需要执行验证 - if ($flags & $type) { - if (0 == strpos($val[2], '{%') && strpos($val[2], '}')) { - // 支持提示信息的多语言 使用 {%语言定义} 方式 - $val[2] = Lang::get(substr($val[2], 2, -1)); - } - $val[3] = isset($val[3]) ? $val[3] : self::EXISTS_VALIDATE; - $val[4] = isset($val[4]) ? $val[4] : 'regex'; - $status = true; - // 判断验证条件 - switch ($val[3]) { - case self::MUST_VALIDATE: // 必须验证 不管表单是否有设置该字段 - $status = $this->_validationFieldItem($data, $val); - break; - case self::VALUE_VALIDATE: // 值不为空的时候才验证 - if ('' != trim($data[$val[0]])) { - $status = $this->_validationFieldItem($data, $val); - } - break; - default: // 默认表单存在该字段就验证 - if (isset($data[$val[0]])) { - $status = $this->_validationFieldItem($data, $val); - } - } - if (false === $status) { - if ($this->patchValidate) { - $this->error[$val[0]] = $val[2]; - } else { - $this->error = $val[2]; - return false; - } - } - } - return true; - } - - /** - * 根据验证因子验证字段 - * @access protected - * @param array $data 创建数据 - * @param array $val 验证因子 - * @return boolean - */ - protected function _validationFieldItem($data, $val) - { - switch (strtolower(trim($val[4]))) { - case 'function': // 使用函数进行验证 - case 'callback': // 调用方法进行验证 - $args = isset($val[6]) ? (array) $val[6] : []; - if (is_string($val[0]) && strpos($val[0], ',')) { - $val[0] = explode(',', $val[0]); - } - if (is_array($val[0])) { - // 支持多个字段验证 - foreach ($val[0] as $field) { - $_data[$field] = isset($data[$field]) ? $data[$field] : null; - } - array_unshift($args, $_data); - } else { - array_unshift($args, isset($data[$val[0]]) ? $data[$val[0]] : null); - } - return call_user_func_array('function' == $val[4] ? $val[1] : [ & $this, $val[1]], $args); - case 'confirm': // 验证两个字段是否相同 - return $data[$val[0]] == $data[$val[1]]; - case 'unique': // 验证某个值是否唯一 - if (is_string($val[0])) { - $val[0] = explode(',', $val[0]); - } - $map = []; - if (is_array($val[0])) { - // 支持多个字段验证 - foreach ($val[0] as $field) { - if (!isset($data[$field])) { - return false; - } - $map[$field] = $data[$field]; - } - } - $pk = $this->getPk(); - if (!empty($data[$pk]) && is_string($pk)) { - // 完善编辑的时候验证唯一 - $map[$pk] = ['neq', $data[$pk]]; - } - $options = $this->options; - if ($this->where($map)->find()) { - return false; - } - $this->options = $options; - return true; - default: // 检查附加规则 - return $this->check($data[$val[0]], $val[1], $val[4]); - } - } - - /** - * 验证数据 支持 in between equal length regex expire ip_allow ip_deny - * @access public - * @param string $value 验证数据 - * @param mixed $rule 验证表达式 - * @param string $type 验证方式 默认为正则验证 - * @return boolean - */ - public function check($value, $rule, $type = 'regex') - { - $type = strtolower(trim($type)); - switch ($type) { - case 'in': // 验证是否在某个指定范围之内 逗号分隔字符串或者数组 - case 'notin': - $range = is_array($rule) ? $rule : explode(',', $rule); - return 'in' == $type ? in_array($value, $range) : !in_array($value, $range); - case 'between': // 验证是否在某个范围 - case 'notbetween': // 验证是否不在某个范围 - if (is_array($rule)) { - $min = $rule[0]; - $max = $rule[1]; - } else { - list($min, $max) = explode(',', $rule); - } - return 'between' == $type ? $value >= $min && $value <= $max : $value < $min || $value > $max; - case 'equal': // 验证是否等于某个值 - case 'notequal': // 验证是否等于某个值 - return 'equal' == $type ? $value == $rule : $value != $rule; - case 'length': // 验证长度 - $length = mb_strlen($value, 'utf-8'); // 当前数据长度 - if (strpos($rule, ',')) { - // 长度区间 - list($min, $max) = explode(',', $rule); - return $length >= $min && $length <= $max; - } else { - // 指定长度 - return $length == $rule; - } - case 'expire': - list($start, $end) = explode(',', $rule); - if (!is_numeric($start)) { - $start = strtotime($start); - } - if (!is_numeric($end)) { - $end = strtotime($end); - } - return NOW_TIME >= $start && NOW_TIME <= $end; - case 'ip_allow': // IP 操作许可验证 - return in_array($_SERVER['REMOTE_ADDR'], explode(',', $rule)); - case 'ip_deny': // IP 操作禁止验证 - return !in_array($_SERVER['REMOTE_ADDR'], explode(',', $rule)); - case 'filter': // 使用filter_var验证 - $result = filter_var($value, is_int($rule) ? $rule : filter_id($rule)); - return false === $result ? false : true; - case 'regex': - default: // 默认使用正则验证 可以使用验证类中定义的验证名称 - // 检查附加规则 - return $this->regex($value, $rule); - } - } - - /** - * 指定自动完成 - * @access public - * @param array $auto 自动完成设置 - * @return Auto - */ - public function auto($auto = [], $rule = null) - { - $this->options['auto'] = $auto; - return $this; - } - - /** - * 指定自动验证 - * @access public - * @param array $validate 自动验证设置 - * @return Auto - */ - public function validate($validate = [], $rule = null) - { - $this->options['validate'] = $validate; - return $this; - } -} diff --git a/library/traits/model/Bulk.php b/library/traits/model/Bulk.php deleted file mode 100644 index 6de9c99c..00000000 --- a/library/traits/model/Bulk.php +++ /dev/null @@ -1,144 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace traits\model; - -use think\Lang; - -trait Bulk -{ - //插入缓存 - private $bulkAddCache = []; - //插入缓存SQL语句预估长度 - private $bulkAddSize = 0; - //更新缓存 - private $bulkSaveCache = []; - private $bulkSaveSize = []; - /** - * 进行缓存插入操作 - * @access public - * @param mixed $data 创建数据,如果传入true则更新所有缓存 - * @param string $type 状态 - * @return mixed - */ - public function bulkAdd($data = '',$options=[]) - { - // 如果没有数据传入 - if (empty($data)) { - $this->error = Lang::get('_DATA_TYPE_INVALID_'); - } - if($data !== true){ - //如不是提交操作,则进行数据处理和缓存累加 - $data = $this->_write_data($data,'insert'); - $this->bulkAddCache[] = $data; - //统计所有字段内容长度 - foreach($data as $key=>$val) - { - $this->bulkAddSize += strlen($val); - } - } - //得到默认的提交SQL数据长度,此设定根据数据库配置不同得到的性能结果会有差异 - //这个数字是否应该写死还是定义一个公共配置名称,需要核心组讨论 - //发现使用insertAll因为bind生成出来的语句比正常的要长不少.字段名+时间戳+序号,还有优化的余地 - $bulkSize = isset($options['bulkSize']) ? $options['bulkSize'] : 10000; - //数据累计到一定量,则执行 - if($this->bulkAddSize < $bulkSize && ($data !== true || empty($this->bulkAddCache))){ - return true; - } - $options = $this->_parseOptions($options); - // 写入数据到数据库 - $result = $this->db->insertAll($this->bulkAddCache, $options,false); - //清空插入缓存 - $this->bulkAddCache = []; - //清空长度计数 - $this->bulkAddSize = 0; - //触发了一个实际插入操作,返回成功或失败 - return (false !== $result); - //插入数据到缓存未导致任何触发 - } - /** - * 批量更新操作 - * @access public - * @param mixed $data 创建数据,如果传入true则更新所有缓存 - * @param string $type 状态 - * @return mixed - */ - public function bulkSave($data = '',$options=[]) - { - // 如果没有数据传入 - if (empty($data)) { - $this->error = Lang::get('_DATA_TYPE_INVALID_'); - } - $options = $this->_parseOptions(); - $pk = $this->getPk(); - if($data !== true){ - //批量跟新必须是带有主键的数组 - if(!isset($data[$pk])){ - throw new Exception('no have pk field'); - } - //由于批量更新存在在原值累加的情况,所以会有 array('id'=>1,'val+'=>10);所以不能先做字段检查 - foreach($data as $field=>$val) - { - //主键不需要处理 - if($field==$pk){ - continue; - } - //对字段缓存初始化.每个字段的更新都会以独立的SQL进行. - if(!isset($this->bulkSaveCache[$field])){ - $this->bulkSaveCache[$field] = []; - $this->bulkSaveSize[$field] = 0; - } - //如果同一个记录的同一字段被多次更新 - if(!isset($this->bulkSaveCache[$field][$data[$pk]])){ - //计算新增修改增加的SQL长度 - $this->bulkSaveCache[$field][$data[$pk]] = $val; - $this->bulkSaveSize[$field] += strlen($val) + strlen($data[$pk]) * 2+14; - continue; - } - //如果是自增自减操作 - $operator = '='; - if(in_array(substr($field,-1,1),['+','-'])){ - $operator = substr($field,-1,1); - } - if($operator == '='){ - //如果是直接赋值,不能重复写入,因为不确定那个值是正确的 - throw new Exception('cannot repeat write in'); - } - else{ - //在原有修改基础上再进行自增或自减操作 - $this->bulkSaveCache[$field][$data[$pk]] += ( $operator =='+' ? $val : - $val ); - } - } - } - $bulkSize = isset($options['bulkSize']) ? $options['bulkSize'] : 10000; - //扫描字段长度.看是否有需要先执行的 - foreach($this->bulkSaveSize as $field=>$size) - { - if($size < $bulkSize && ($size== 0 || $data !== true)){ - continue; - } - //复制出插入数组 - $dataSet = $this->bulkSaveCache[$field]; - unset($this->bulkSaveCache[$field]); - unset($this->bulkSaveSize[$field]); - //默认运算符 - $operator='='; - //自增或者自减 - if(in_array(substr($field,-1,1),['+','-'])) - { - $operator = substr($field,-1,1); - $field = substr($field,0,-1); - } - //批量字段更新 - $this->db->updateFieldAll($field,$pk,$dataSet,$operator,$options); - } - } -} diff --git a/library/traits/model/Relation.php b/library/traits/model/Relation.php deleted file mode 100644 index 1372ab97..00000000 --- a/library/traits/model/Relation.php +++ /dev/null @@ -1,446 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace traits\model; - -define('HAS_ONE', 1); -define('BELONGS_TO', 2); -define('HAS_MANY', 3); -define('MANY_TO_MANY', 4); - -trait Relation -{ - // 关联定义 - //protected $link = []; - - /** - * 得到关联的数据表名 - * @access public - * @return string - */ - public function getRelationTableName($relation) - { - $relationTable = !empty($this->tablePrefix) ? $this->tablePrefix : ''; - $relationTable .= $this->tableName ? $this->tableName : $this->name; - $relationTable .= '_' . $relation->getModelName(); - return strtolower($relationTable); - } - - // 查询成功后的回调方法 - protected function _after_find(&$result, $options = []) - { - // 获取关联数据 并附加到结果中 - if (!empty($options['link'])) { - $this->getRelation($result, $options['link']); - } - - } - - // 查询数据集成功后的回调方法 - protected function _after_select(&$result, $options = []) - { - // 获取关联数据 并附加到结果中 - if (!empty($options['link'])) { - $this->getRelations($result, $options['link']); - } - - } - - // 写入成功后的回调方法 - protected function _after_insert($data, $options = []) - { - // 关联写入 - if (!empty($options['link'])) { - $this->opRelation('ADD', $data, $options['link']); - } - - } - - // 更新成功后的回调方法 - protected function _after_update($data, $options = []) - { - // 关联更新 - if (!empty($options['link'])) { - $this->opRelation('SAVE', $data, $options['link']); - } - - } - - // 删除成功后的回调方法 - protected function _after_delete($data, $options = []) - { - // 关联删除 - if (!empty($options['link'])) { - $this->opRelation('DEL', $data, $options['link']); - } - - } - - // 表单验证成功后的回调方法 - protected function _after_create(&$data, $options = []) - { - // 获取关联数据 并附加到结果中 - if (!empty($options['link'])) { - $this->crRelation($data, $options['link']); - } - } - - /** - * 对保存到数据库的数据进行处理 - * @access protected - * @param mixed $data 要操作的数据 - * @param string $type insert 或者 update - * @return array - */ - protected function _write_data($data, $type) - { - $this->_before_write($data); - return $data; - } - - /** - * 获取返回数据集的关联记录 - * @access protected - * @param array $resultSet 返回数据 - * @param string|array $name 关联名称 - * @return array - */ - protected function getRelations(&$resultSet, $name = '') - { - // 获取记录集的主键列表 - foreach ($resultSet as $key => $val) { - $val = $this->getRelation($val, $name); - $resultSet[$key] = $val; - } - return $resultSet; - } - - /** - * 获取返回数据的关联记录 - * @access protected - * @param mixed $result 返回数据 - * @param string|array $name 关联名称 - * @param boolean $return 是否返回关联数据本身 - * @return array - */ - protected function getRelation(&$result, $name = '', $return = false) - { - if (!empty($this->link)) { - foreach ($this->link as $key => $val) { - $mappingName = !empty($val['mapping_name']) ? $val['mapping_name'] : $key; // 映射名称 - if (empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName, $name))) { - $mappingType = !empty($val['mapping_type']) ? $val['mapping_type'] : $val; // 关联类型 - $mappingClass = !empty($val['class_name']) ? $val['class_name'] : $key; // 关联类名 - $mappingFields = !empty($val['mapping_fields']) ? $val['mapping_fields'] : '*'; // 映射字段 - $mappingCondition = !empty($val['condition']) ? $val['condition'] : '1=1'; // 关联条件 - $mappingKey = !empty($val['mapping_key']) ? $val['mapping_key'] : $this->getPk(); // 关联键名 - if (strtoupper($mappingClass) == strtoupper($this->name)) { - // 自引用关联 获取父键名 - $mappingFk = !empty($val['parent_key']) ? $val['parent_key'] : 'parent_id'; - } else { - $mappingFk = !empty($val['foreign_key']) ? $val['foreign_key'] : strtolower($this->name) . '_id'; // 关联外键 - } - // 获取关联模型对象 - $model = \think\Loader::model($mappingClass); - switch ($mappingType) { - case HAS_ONE: - $pk = $result[$mappingKey]; - $mappingCondition .= " AND {$mappingFk}='{$pk}'"; - $relationData = $model->where($mappingCondition)->field($mappingFields)->find(); - break; - case BELONGS_TO: - if (strtoupper($mappingClass) == strtoupper($this->name)) { - // 自引用关联 获取父键名 - $mappingFk = !empty($val['parent_key']) ? $val['parent_key'] : 'parent_id'; - } else { - $mappingFk = !empty($val['foreign_key']) ? $val['foreign_key'] : strtolower($model->getModelName()) . '_id'; // 关联外键 - } - $fk = $result[$mappingFk]; - $mappingCondition .= " AND {$model->getPk()}='{$fk}'"; - $relationData = $model->where($mappingCondition)->field($mappingFields)->find(); - break; - case HAS_MANY: - $pk = $result[$mappingKey]; - $mappingCondition .= " AND {$mappingFk}='{$pk}'"; - $mappingOrder = !empty($val['mapping_order']) ? $val['mapping_order'] : ''; - $mappingLimit = !empty($val['mapping_limit']) ? $val['mapping_limit'] : ''; - // 延时获取关联记录 - $relationData = $model->where($mappingCondition)->field($mappingFields)->order($mappingOrder)->limit($mappingLimit)->select(); - break; - case MANY_TO_MANY: - $pk = $result[$mappingKey]; - $mappingCondition = " {$mappingFk}='{$pk}'"; - $mappingOrder = $val['mapping_order']; - $mappingLimit = $val['mapping_limit']; - $mappingRelationFk = $val['relation_foreign_key'] ? $val['relation_foreign_key'] : $model->getModelName() . '_id'; - $mappingRelationTable = $val['relation_table'] ? $val['relation_table'] : $this->getRelationTableName($model); - $sql = "SELECT b.{$mappingFields} FROM {$mappingRelationTable} AS a, " . $model->getTableName() . " AS b WHERE a.{$mappingRelationFk} = b.{$model->getPk()} AND a.{$mappingCondition}"; - if (!empty($val['condition'])) { - $sql .= ' AND ' . $val['condition']; - } - if (!empty($mappingOrder)) { - $sql .= ' ORDER BY ' . $mappingOrder; - } - if (!empty($mappingLimit)) { - $sql .= ' LIMIT ' . $mappingLimit; - } - $relationData = $this->query($sql); - break; - } - if (!$return) { - if (isset($val['as_fields']) && in_array($mappingType, [HAS_ONE, BELONGS_TO])) { - // 支持直接把关联的字段值映射成数据对象中的某个字段 - // 仅仅支持HAS_ONE BELONGS_TO - $fields = explode(',', $val['as_fields']); - foreach ($fields as $field) { - if (strpos($field, ':')) { - list($relationName, $nick) = explode(':', $field); - $result[$nick] = $relationData[$relationName]; - } else { - $result[$field] = $relationData[$field]; - } - } - } else { - $result[$mappingName] = $relationData; - } - unset($relationData); - } else { - return $relationData; - } - } - } - } - return $result; - } - - /** - * 操作关联数据 - * @access protected - * @param string $opType 操作方式 ADD SAVE DEL - * @param mixed $data 数据对象 - * @param string $name 关联名称 - * @return mixed - */ - protected function opRelation($opType, $data = '', $name = '') - { - $result = false; - if (empty($data) && !empty($this->data)) { - $data = $this->data; - } elseif (!is_array($data)) { - // 数据无效返回 - return false; - } - if (!empty($this->link)) { - // 遍历关联定义 - foreach ($this->link as $key => $val) { - // 操作制定关联类型 - $mappingName = $val['mapping_name'] ? $val['mapping_name'] : $key; // 映射名称 - if (empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName, $name))) { - // 操作制定的关联 - $mappingType = !empty($val['mapping_type']) ? $val['mapping_type'] : $val; // 关联类型 - $mappingClass = !empty($val['class_name']) ? $val['class_name'] : $key; // 关联类名 - $mappingKey = !empty($val['mapping_key']) ? $val['mapping_key'] : $this->getPk(); // 关联键名 - // 当前数据对象主键值 - $pk = $data[$mappingKey]; - if (strtoupper($mappingClass) == strtoupper($this->name)) { - // 自引用关联 获取父键名 - $mappingFk = !empty($val['parent_key']) ? $val['parent_key'] : 'parent_id'; - } else { - $mappingFk = !empty($val['foreign_key']) ? $val['foreign_key'] : strtolower($this->name) . '_id'; // 关联外键 - } - if (!empty($val['condition'])) { - $mappingCondition = $val['condition']; - } else { - $mappingCondition = []; - $mappingCondition[$mappingFk] = $pk; - } - // 获取关联model对象 - $model = \think\Loader::model($mappingClass); - $mappingData = isset($data[$mappingName]) ? $data[$mappingName] : false; - if (!empty($mappingData) || 'DEL' == $opType) { - switch ($mappingType) { - case HAS_ONE: - switch (strtoupper($opType)) { - case 'ADD': // 增加关联数据 - $mappingData[$mappingFk] = $pk; - $result = $model->add($mappingData); - break; - case 'SAVE': // 更新关联数据 - $result = $model->where($mappingCondition)->save($mappingData); - break; - case 'DEL': // 根据外键删除关联数据 - $result = $model->where($mappingCondition)->delete(); - break; - } - break; - case BELONGS_TO: - break; - case HAS_MANY: - switch (strtoupper($opType)) { - case 'ADD': // 增加关联数据 - $model->startTrans(); - foreach ($mappingData as $val) { - $val[$mappingFk] = $pk; - $result = $model->add($val); - } - $model->commit(); - break; - case 'SAVE': // 更新关联数据 - $model->startTrans(); - $pk = $model->getPk(); - foreach ($mappingData as $vo) { - if (isset($vo[$pk])) { - // 更新数据 - $mappingCondition = "$pk ={$vo[$pk]}"; - $result = $model->where($mappingCondition)->save($vo); - } else { - // 新增数据 - $vo[$mappingFk] = $data[$mappingKey]; - $result = $model->add($vo); - } - } - $model->commit(); - break; - case 'DEL': // 删除关联数据 - $result = $model->where($mappingCondition)->delete(); - break; - } - break; - case MANY_TO_MANY: - $mappingRelationFk = $val['relation_foreign_key'] ? $val['relation_foreign_key'] : $model->getModelName() . '_id'; // 关联 - $mappingRelationTable = $val['relation_table'] ? $val['relation_table'] : $this->getRelationTableName($model); - if (is_array($mappingData)) { - $ids = []; - foreach ($mappingData as $vo) { - $ids[] = $vo[$mappingKey]; - } - - $relationId = implode(',', $ids); - } - switch (strtoupper($opType)) { - case 'ADD': // 增加关联数据 - case 'SAVE': // 更新关联数据 - if (isset($relationId)) { - $this->startTrans(); - // 删除关联表数据 - $this->table($mappingRelationTable)->where($mappingCondition)->delete(); - // 插入关联表数据 - $sql = 'INSERT INTO ' . $mappingRelationTable . ' (' . $mappingFk . ',' . $mappingRelationFk . ') SELECT a.' . $this->getPk() . ',b.' . $model->getPk() . ' FROM ' . $this->getTableName() . ' AS a ,' . $model->getTableName() . " AS b where a." . $this->getPk() . ' =' . $pk . ' AND b.' . $model->getPk() . ' IN (' . $relationId . ") "; - $result = $model->execute($sql); - if (false !== $result) - // 提交事务 - { - $this->commit(); - } else - // 事务回滚 - { - $this->rollback(); - } - - } - break; - case 'DEL': // 根据外键删除中间表关联数据 - $result = $this->table($mappingRelationTable)->where($mappingCondition)->delete(); - break; - } - break; - } - } - } - } - } - return $result; - } - - /** - * 关联数据验证 - * @access protected - * @param mixed $data 数据对象 - * @param string $name 关联名称 - * @return mixed - */ - protected function crRelation(&$data, $name = '') - { - if (empty($data) && !empty($this->data)) { - $data = $this->data; - } elseif (!is_array($data)) { - // 数据无效返回 - return false; - } - if (!empty($this->_link)) { - $fields = $this->getFields(); - // 遍历关联定义 - foreach ($this->_link as $key => $val) { - // 操作制定关联类型 - $mappingName = !empty($val['mapping_name']) ? $val['mapping_name'] : $key; // 映射名称 - if (empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName, $name))) { - // 操作制定的关联 - $mappingType = !empty($val['mapping_type']) ? $val['mapping_type'] : $val; // 关联类型 - $mappingClass = !empty($val['class_name']) ? $val['class_name'] : $key; // 关联类名 - $mappingKey = !empty($val['mapping_key']) ? $val['mapping_key'] : $this->getPk(); // 关联键名 - if (strtoupper($mappingClass) == strtoupper($this->name) || !isset($data[$mappingName])) { - continue; // 自引用关联或提交关联数据跳过 - } - // 获取关联model对象 - $model = \think\Loader::model($mappingClass); - $_data = $data[$mappingName]; - unset($data[$key]); - if ($_data = $model->token(false)->create($_data)) { - $data[$mappingName] = $_data; - $fields[] = $mappingName; - } else { - $error = $model->getError(); - if ($this->patchValidate) { - $this->error[$mappingName] = $error; - } else { - $this->error = $error; - return false; - } - } - } - } - - // 过滤非法字段数据 - $diff = array_diff(array_keys($data), $fields); - foreach ($diff as $key) { - unset($data[$key]); - } - } - } - - /** - * 进行关联查询 - * @access public - * @param mixed $name 关联名称 - * @return Model - */ - public function relation($name) - { - $this->options['link'] = $name; - $this->autoCheckFields = false; - return $this; - } - - /** - * 关联数据获取 仅用于查询后 - * @access public - * @param string $name 关联名称 - * @return array - */ - public function relationGet($name) - { - if (empty($this->data)) { - return false; - } - - return $this->getRelation($this->data, $name, true); - } -} diff --git a/library/traits/model/Transaction.php b/library/traits/model/Transaction.php deleted file mode 100644 index 8e9533bb..00000000 --- a/library/traits/model/Transaction.php +++ /dev/null @@ -1,80 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace traits\model; - -trait Transaction -{ - - /** - * 启动事务 - * @access public - * @return void - */ - public function startTrans() - { - $this->commit(); - $this->db->startTrans(); - return; - } - - /** - * 提交事务 - * @access public - * @return boolean - */ - public function commit() - { - return $this->db->commit(); - } - - /** - * 事务回滚 - * @access public - * @return boolean - */ - public function rollback() - { - return $this->db->rollback(); - } - - /** - * 批处理执行SQL语句 - * 批处理的指令都认为是execute操作 - * @access public - * @param array $sql SQL批处理指令 - * @return boolean - */ - public function patchQuery($sql = []) - { - if (!is_array($sql)) { - return false; - } - // 自动启动事务支持 - $this->startTrans(); - try { - foreach ($sql as $_sql) { - $result = $this->execute($_sql); - if (false === $result) { - // 发生错误自动回滚事务 - $this->rollback(); - return false; - } - } - // 提交事务 - $this->commit(); - } catch (\think\exception $e) { - $this->rollback(); - return false; - } - return true; - } -} diff --git a/library/traits/model/View.php b/library/traits/model/View.php deleted file mode 100644 index d4a7c3ec..00000000 --- a/library/traits/model/View.php +++ /dev/null @@ -1,305 +0,0 @@ - -// +---------------------------------------------------------------------- - -namespace traits\model; - -trait View -{ - - /** - * 自动检测数据表信息 - * @access protected - * @return void - */ - protected function _checkTableInfo() - {} - - /** - * 得到完整的数据表名 - * @access public - * @return string - */ - public function getTableName() - { - if (empty($this->trueTableName)) { - $tableName = ''; - $len = 0; - foreach ($this->viewFields as $name => $view) { - // 获取数据表名称 - if (isset($view['_table'])) { - // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图 - $tableName .= $view['_table']; - $prefix = $this->tablePrefix; - $tableName = preg_replace_callback("/__([A-Z_-]+)__/sU", function ($match) use ($prefix) {return $prefix . strtolower($match[1]);}, $tableName); - } else { - $tableName .= \think\Loader::table($name)->getTableName(); - } - // 表别名定义 - $tableName .= !empty($view['_as']) ? ' ' . $view['_as'] : ' ' . $name; - // 支持ON 条件定义 - $tableName .= !empty($view['_on']) ? ' ON ' . $view['_on'] : ''; - if (!empty($view['_type'])) { - // 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效 - $type = strtoupper($view['_type']); - $tableName .= ' ' . $type . ' JOIN '; - if ($view == end($this->viewFields)) { - $len = strlen($type) + 7; - } - } - } - $this->trueTableName = $len ? substr($tableName, 0, -$len) : $tableName; - } - - return $this->trueTableName; - } - - /** - * 表达式过滤方法 - * @access protected - * @param string $options 表达式 - * @return void - */ - protected function _options_filter(&$options) - { - $viewFields = []; - foreach ($this->viewFields as $name => $val) { - $k = isset($val['_as']) ? $val['_as'] : $name; - $val = $this->_checkFields($name, $val); - foreach ($val as $key => $field) { - if (is_numeric($key)) { - $viewFields[$field] = $k . '.' . $field; - } elseif ('_' != substr($key, 0, 1)) { - // 以_开头的为特殊定义 - if (false !== strpos($key, '*') || false !== strpos($key, '(') || false !== strpos($key, '.')) { - //如果包含* 或者 使用了sql方法 则不再添加前面的表名 - $viewFields[$field] = $key; - } else { - $viewFields[$field] = $k . '.' . $key; - } - } - } - } - if (empty($options['field'])) { - $options['field'] = '*'; - } - $options['field'] = $this->checkFields($options['field'], $viewFields); - if (isset($options['group'])) { - $options['group'] = $this->checkGroup($options['group'], $viewFields); - } - if (isset($options['where'])) { - $options['where'] = $this->checkCondition($options['where'], $viewFields); - } - if (isset($options['order'])) { - $options['order'] = $this->checkOrder($options['order'], $viewFields); - } - } - - /** - * 检查是否定义了所有字段 - * @access protected - * @param string $name 模型名称 - * @param array $fields 字段数组 - * @return array - */ - private function _checkFields($name, $fields) - { - if (false !== $pos = array_search('*', $fields)) { - // 定义所有字段 - $fields = array_merge($fields, \think\Loader::table($name)->getFields()); - unset($fields[$pos]); - } - - return $fields; - } - - /** - * 检查条件中的视图字段 - * @access protected - * @param mixed $data 条件表达式 - * @param array $fields 视图字段数组 - * @return array - */ - protected function checkCondition($where, $viewFields) - { - if (is_array($where)) { - $_where = []; - foreach ($where as $field => $value) { - if ('_complex' != $field) { - $value = [$field => $value]; - $parent = 1; - } else { - $parent = 0; - } - foreach ($value as $key => $val) { - if (0 !== strpos($key, '_')) { - if ($items = preg_split('/[\|\&]/', $key, -1, PREG_SPLIT_OFFSET_CAPTURE)) { - // 倒序找出的字段数组,以便从后向前替换 - $items = array_reverse($items); - foreach ($items as $item) { - if (isset($viewFields[$item[0]])) { // 存在视图字段 - $key = substr_replace($key, $viewFields[$item[0]], $item[1], strlen($item[0])); - } - } - } - if (isset($val[0]) && 'exp' == $val[0] && !empty($val[1])) { - if (preg_match_all('/(? $field) { - if (is_numeric($key)) { - if ($pos = strpos($field, ' ')) { - $sort = substr($field, $pos); - $field = substr($field, 0, $pos); - } else { - $sort = ''; - } - } else { - $sort = ' ' . $field; - $field = $key; - } - if (isset($viewFields[$field])) { - // 存在视图字段 - $field = $viewFields[$field] . $sort; - } - $_order[] = $field; - } - - return $_order; - } - - /** - * 检查Group表达式中的视图字段 - * @access protected - * @param string $group 字段 - * @param array $fields 视图字段数组 - * @return string - */ - protected function checkGroup($group = '', $viewFields) - { - if (empty($group)) { - return ''; - } elseif (is_string($group)) { - $group = explode(',', $group); - } - foreach ($group as &$field) { - if (isset($viewFields[$field])) { - // 存在视图字段 - $field = $viewFields[$field]; - } - } - - return implode(',', $group); - } - - /** - * 检查fields表达式中的视图字段 - * @access protected - * @param string $fields 字段 - * @param array $fields 视图字段数组 - * @return string - */ - protected function checkFields($fields = '*', $viewFields) - { - if (is_string($fields)) { - if ('*' == $fields) { - return $viewFields; - } else { - $fields = explode(',', $fields); - } - } - $_fields = []; - foreach ($fields as $key => $field) { - if (is_numeric($key)) { - if ($pos = strpos($field, ' ')) { - $alias = substr($field, $pos); - $field = substr($field, 0, $pos); - } else { - $alias = ' AS ' . $field; - } - } else { - $alias = ' AS ' . $field; - $field = $key; - } - if (strpos($field, '(')) { - if (preg_match_all('/(?