From 1cfb3704c64b57a2622ae8622959cf47090d1ff8 Mon Sep 17 00:00:00 2001 From: thinkphp Date: Sat, 3 Oct 2015 21:43:48 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=84=E8=8C=83=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convention.php | 109 +++++++++++++++++-------- library/org/image/driver/imagick.php | 2 +- library/think/app.php | 2 +- library/think/cache.php | 2 +- library/think/controller.php | 5 +- library/think/controller/rest.php | 3 +- library/think/create.php | 9 +- library/think/db.php | 2 +- library/think/db/driver.php | 44 +++++----- library/think/db/driver/mongo.php | 4 +- library/think/db/lite.php | 7 +- library/think/debug.php | 8 +- library/think/error.php | 7 +- library/think/input.php | 4 +- library/think/lang.php | 5 +- library/think/loader.php | 3 +- library/think/log.php | 4 +- library/think/model.php | 66 +++++++++------ library/think/model/mongo_model.php | 24 +++--- library/think/route.php | 19 +++-- library/think/template.php | 63 ++++++++------ library/think/template/driver/file.php | 2 +- library/think/template/taglib.php | 5 +- library/think/url.php | 8 +- mode/sae.php | 42 ++++++---- start.php | 9 +- traits/think/model/auto.php | 80 ++++++++++-------- traits/think/model/extend.php | 37 +++++---- traits/think/model/query.php | 14 ++-- traits/think/model/relation.php | 8 +- traits/think/model/view.php | 81 +++++++++--------- 31 files changed, 393 insertions(+), 285 deletions(-) diff --git a/convention.php b/convention.php index e81d454a..04994bba 100644 --- a/convention.php +++ b/convention.php @@ -1,27 +1,46 @@ 'debug',// 应用模式状态 - 'var_pathinfo' => 's', // PATHINFO变量名 用于兼容模式 + // 应用模式状态 + 'app_status' => 'debug', + // PATHINFO变量名 用于兼容模式 + 'var_pathinfo' => 's', 'extra_config_list' => [], 'pathinfo_fetch' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', - 'pathinfo_depr' => '/', // pathinfo分隔符 - 'require_module' => true, // 是否显示模块 - 'default_module' => 'index', // 默认模块名 - 'default_controller' => 'index', // 默认控制器名 - 'default_action' => 'index', // 默认操作名 - 'empty_controller' => 'error', // 默认的空控制器名 - 'action_suffix' => '', // 操作方法后缀 - 'url_model' => 1, // URL模式 - 'url_request_uri' => 'REQUEST_URI', // 获取当前页面地址的系统变量 默认为REQUEST_URI - 'base_url' => $_SERVER["SCRIPT_NAME"], // 基础URL路径 + // pathinfo分隔符 + 'pathinfo_depr' => '/', + // 是否显示模块 + 'require_module' => true, + // 默认模块名 + 'default_module' => 'index', + // 默认控制器名 + 'default_controller' => 'index', + // 默认操作名 + 'default_action' => 'index', + // 默认的空控制器名 + 'empty_controller' => 'error', + // 操作方法后缀 + 'action_suffix' => '', + // URL模式 + 'url_model' => 1, + // 获取当前页面地址的系统变量 默认为REQUEST_URI + 'url_request_uri' => 'REQUEST_URI', + // 基础URL路径 + 'base_url' => $_SERVER["SCRIPT_NAME"], + // URL伪静态后缀 'url_html_suffix' => '.html', - 'url_params_bind' => TRUE, // url变量绑定 - 'exception_tmpl' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件 - 'error_tmpl' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件 - 'success_tmpl' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件 - 'default_ajax_return' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ... - 'default_jsonp_handler' => 'jsonpReturn', // 默认JSONP格式返回的处理方法 + // url变量绑定 + 'url_params_bind' => TRUE, + // 异常页面的模板文件 + 'exception_tmpl' => THINK_PATH.'Tpl/think_exception.tpl', + // 默认错误跳转对应的模板文件 + 'error_tmpl' => THINK_PATH.'Tpl/dispatch_jump.tpl', + // 默认成功跳转对应的模板文件 + 'success_tmpl' => THINK_PATH.'Tpl/dispatch_jump.tpl', + // 默认AJAX 数据返回格式,可选JSON XML ... + 'default_ajax_return' => 'JSON', + // 默认JSONP格式返回的处理方法 + 'default_jsonp_handler' => 'jsonpReturn', 'var_jsonp_handler' => 'callback', 'template_engine' => 'think', 'common_module' => 'common', @@ -29,9 +48,12 @@ return [ 'url_module_map' => [], /* 错误设置 */ - 'error_message' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效 - 'error_page' => '', // 错误定向页面 - 'show_error_msg' => false, // 显示错误信息 + //错误显示信息,非调试模式有效 + 'error_message' => '页面错误!请稍后再试~', + // 错误定向页面 + 'error_page' => '', + // 显示错误信息 + 'show_error_msg' => false, 'log' => [ 'type' => 'File', @@ -53,20 +75,35 @@ return [ /* 数据库设置 */ 'database' => [ - 'type' => 'mysql', // 数据库类型 - 'dsn' => '', // - 'hostname' => 'localhost', // 服务器地址 - 'database' => '', // 数据库名 - 'username' => 'root', // 用户名 - 'password' => '', // 密码 - 'hostport' => '', // 端口 - 'params' => [], // 数据库连接参数 - 'charset' => 'utf8', // 数据库编码默认采用utf8 - 'prefix' => '', // 数据库表前缀 - 'debug' => false, // 数据库调试模式 - 'deploy' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) - 'rw_separate' => false, // 数据库读写是否分离 主从式有效 - 'master_num' => 1, // 读写分离后 主服务器数量 - 'slave_no' => '', // 指定从服务器序号 + // 数据库类型 + 'type' => 'mysql', + // 数据库连接DSN配置 + 'dsn' => '', + // 服务器地址 + 'hostname' => 'localhost', + // 数据库名 + 'database' => '', + // 数据库用户名 + 'username' => 'root', + // 数据库密码 + 'password' => '', + // 数据库连接端口 + 'hostport' => '', + // 数据库连接参数 + 'params' => [], + // 数据库编码默认采用utf8 + 'charset' => 'utf8', + // 数据库表前缀 + 'prefix' => '', + // 数据库调试模式 + 'debug' => false, + // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) + 'deploy' => 0, + // 数据库读写是否分离 主从式有效 + 'rw_separate' => false, + // 读写分离后 主服务器数量 + 'master_num' => 1, + // 指定从服务器序号 + 'slave_no' => '', ], ]; \ No newline at end of file diff --git a/library/org/image/driver/imagick.php b/library/org/image/driver/imagick.php index 09c03f1f..45ca5254 100644 --- a/library/org/image/driver/imagick.php +++ b/library/org/image/driver/imagick.php @@ -30,7 +30,7 @@ class Imagick{ */ public function __construct($imgname = null) { if ( !extension_loaded('Imagick') ) { - E(L('_NOT_SUPPERT_').':Imagick'); + throw new \Exception(Lang::get('_NOT_SUPPERT_').':Imagick'); } $imgname && $this->open($imgname); } diff --git a/library/think/app.php b/library/think/app.php index 992408ea..3ba4fc36 100644 --- a/library/think/app.php +++ b/library/think/app.php @@ -243,7 +243,7 @@ class App { $_SERVER['PATH_INFO'] = __INFO__; if(__INFO__ && !defined('BIND_MODULE')){ if($config['url_deny_suffix'] && preg_match('/\.('.$config['url_deny_suffix'].')$/i', __INFO__)){ - exit; + throw new Exception('URL_SUFFIX_DENY'); } $paths = explode($config['pathinfo_depr'], __INFO__,2); // 获取URL中的模块名 diff --git a/library/think/cache.php b/library/think/cache.php index d74dc16a..f74c61e6 100644 --- a/library/think/cache.php +++ b/library/think/cache.php @@ -33,6 +33,6 @@ class Cache { } static public function __callStatic($method, $params){ - return call_user_func_array(array(self::$handler, $method), $params); + return call_user_func_array([self::$handler, $method], $params); } } diff --git a/library/think/controller.php b/library/think/controller.php index 5917f859..bda0b98a 100644 --- a/library/think/controller.php +++ b/library/think/controller.php @@ -11,7 +11,6 @@ namespace think; use think\View; -use org\Transform; class Controller { // 视图类实例 @@ -182,8 +181,8 @@ class Controller { $data['jumpUrl'] = $jumpUrl; // 提示标题 - $data['msgTitle'] = $status ? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'); - $data['status'] = $status; // 状态 + $data['msgTitle'] = Lang::get( $status ? '_OPERATION_SUCCESS_' : '_OPERATION_FAIL_'); + $data['status'] = $status; // 状态 //保证输出不受静态缓存影响 Config::set('html_cache_on',false); diff --git a/library/think/controller/rest.php b/library/think/controller/rest.php index ce2da906..d5baa96a 100644 --- a/library/think/controller/rest.php +++ b/library/think/controller/rest.php @@ -10,6 +10,7 @@ // +---------------------------------------------------------------------- namespace think\controller; +use think\Response; abstract class rest { @@ -68,7 +69,7 @@ abstract class rest { $this->$fun(); }else{ // 抛出异常 - throw new \think\Exception(L('_ERROR_ACTION_:').ACTION_NAME); + throw new \think\Exception(\think\Lang::get('_ERROR_ACTION_:').ACTION_NAME); } } diff --git a/library/think/create.php b/library/think/create.php index 0d26c1bd..d814200a 100644 --- a/library/think/create.php +++ b/library/think/create.php @@ -14,13 +14,12 @@ namespace think; class Create { static public function build($build) { // 锁定 - $lockfile = APP_PATH.'create.lock'; + $lockfile = APP_PATH.'create.lock'; if(is_writable($lockfile)) { return ; } else { if(!touch($lockfile)){ - header('Content-Type:text/html; charset=utf-8'); - exit('目录 [ '.APP_PATH.' ] 不可写!'); + throw new Exception('目录 [ '.APP_PATH.' ] 不可写!'); } } foreach ($build as $module=>$list){ @@ -45,7 +44,7 @@ class Create { mkdir(APP_PATH.$module.'/'.$path); } foreach($file as $val){ - $filename = APP_PATH.$module.'/'.$path.'/'.strtolower($val).EXT; + $filename = APP_PATH.$module.'/'.$path.'/'.strtolower($val).EXT; switch($path) { case 'controller':// 控制器 if(!is_file($filename)) { @@ -75,7 +74,7 @@ class Create { // 创建欢迎页面 static public function buildHelloController($module) { - $filename = APP_PATH.$module.'/controller/index'.EXT; + $filename = APP_PATH.$module.'/controller/index'.EXT; if(!is_file($filename)) { $content = file_get_contents(THINK_PATH.'tpl/default_index.tpl'); $content = str_replace('{$module}',$module,$content); diff --git a/library/think/db.php b/library/think/db.php index 672c1fb0..126de1f6 100644 --- a/library/think/db.php +++ b/library/think/db.php @@ -92,6 +92,6 @@ class Db { // 调用驱动类的方法 static public function __callStatic($method, $params){ - return call_user_func_array(array(self::$_instance, $method), $params); + return call_user_func_array([self::$_instance, $method], $params); } } diff --git a/library/think/db/driver.php b/library/think/db/driver.php index d9aeef9f..f054e7c3 100644 --- a/library/think/db/driver.php +++ b/library/think/db/driver.php @@ -491,7 +491,7 @@ abstract class Driver { $whereStr = $where; }else{ // 使用数组表达式 $operate = isset($where['_logic'])?strtoupper($where['_logic']):''; - if(in_array($operate,array('AND','OR','XOR'))){ + if(in_array($operate,['AND','OR','XOR'])){ // 定义逻辑运算规则 例如 OR XOR AND NOT $operate = ' '.$operate.' '; unset($where['_logic']); @@ -512,7 +512,7 @@ abstract class Driver { $key = trim($key); if(strpos($key,'|')) { // 支持 name|title|nickname 方式定义查询字段 $array = explode('|',$key); - $str = array(); + $str = []; foreach ($array as $m=>$k){ $v = $multi?$val[$m]:$val; $str[] = $this->parseWhereItem($this->parseKey($k),$v); @@ -520,7 +520,7 @@ abstract class Driver { $whereStr .= '( '.implode(' OR ',$str).' )'; }elseif(strpos($key,'&')){ $array = explode('&',$key); - $str = array(); + $str = []; foreach ($array as $m=>$k){ $v = $multi?$val[$m]:$val; $str[] = '('.$this->parseWhereItem($this->parseKey($k),$v).')'; @@ -548,8 +548,8 @@ abstract class Driver { }elseif(preg_match('/^(notlike|like)$/',$exp)){// 模糊查找 if(is_array($val[1])) { $likeLogic = isset($val[2])?strtoupper($val[2]):'OR'; - if(in_array($likeLogic,array('AND','OR','XOR'))){ - $like = array(); + if(in_array($likeLogic,['AND','OR','XOR'])){ + $like = []; foreach ($val[1] as $item){ $like[] = $key.' '.$this->exp[$exp].' '.$this->parseValue($item); } @@ -576,12 +576,12 @@ abstract class Driver { $data = is_string($val[1])? explode(',',$val[1]):$val[1]; $whereStr .= $key.' '.$this->exp[$exp].' '.$this->parseValue($data[0]).' AND '.$this->parseValue($data[1]); }else{ - throw new Exception(L('_EXPRESS_ERROR_').':'.$val[0]); + throw new Exception(Lang::get('_EXPRESS_ERROR_').':'.$val[0]); } }else { $count = count($val); $rule = isset($val[$count-1]) ? (is_array($val[$count-1]) ? strtoupper($val[$count-1][0]) : strtoupper($val[$count-1]) ) : '' ; - if(in_array($rule,array('AND','OR','XOR'))) { + if(in_array($rule,['AND','OR','XOR'])) { $count = $count -1; }else{ $rule = 'AND'; @@ -792,7 +792,7 @@ abstract class Driver { public function insert($data,$options=[],$replace=false) { $values = $fields = []; $this->model = $options['model']; - $this->parseBind(!empty($options['bind'])?$options['bind']:array()); + $this->parseBind(!empty($options['bind'])?$options['bind']:[]); foreach ($data as $key=>$val){ if(is_array($val) && 'exp' == $val[0]){ $fields[] = $this->parseKey($key); @@ -826,14 +826,14 @@ abstract class Driver { * @param boolean $replace 是否replace * @return false | integer */ - public function insertAll($dataSet,$options=array(),$replace=false) { - $values = array(); + public function insertAll($dataSet,$options=[],$replace=false) { + $values = []; $this->model = $options['model']; if(!is_array($dataSet[0])) return false; - $this->parseBind(!empty($options['bind'])?$options['bind']:array()); - $fields = array_map(array($this,'parseKey'),array_keys($dataSet[0])); + $this->parseBind(!empty($options['bind'])?$options['bind']:[]); + $fields = array_map([$this,'parseKey'],array_keys($dataSet[0])); foreach ($dataSet as $data){ - $value = array(); + $value = []; foreach ($data as $key=>$val){ if(is_array($val) && 'exp' == $val[0]){ $value[] = $val[1]; @@ -866,9 +866,9 @@ abstract class Driver { */ public function selectInsert($fields,$table,$options=[]) { $this->model = $options['model']; - $this->parseBind(!empty($options['bind'])?$options['bind']:array()); + $this->parseBind(!empty($options['bind'])?$options['bind']:[]); if(is_string($fields)) $fields = explode(',',$fields); - array_walk($fields, array($this, 'parseKey')); + array_walk($fields, [$this, 'parseKey']); $sql = 'INSERT INTO '.$this->parseTable($table).' ('.implode(',', $fields).') '; $sql .= $this->buildSelectSql($options); return $this->execute($sql,!empty($options['fetch_sql']) ? true : false); @@ -883,7 +883,7 @@ abstract class Driver { */ public function update($data,$options) { $this->model = $options['model']; - $this->parseBind(!empty($options['bind'])?$options['bind']:array()); + $this->parseBind(!empty($options['bind'])?$options['bind']:[]); $table = $this->parseTable($options['table']); $sql = 'UPDATE ' . $table . $this->parseSet($data); if(strpos($table,',')){// 多表更新支持JOIN操作 @@ -907,7 +907,7 @@ abstract class Driver { */ public function delete($options=[]) { $this->model = $options['model']; - $this->parseBind(!empty($options['bind'])?$options['bind']:array()); + $this->parseBind(!empty($options['bind'])?$options['bind']:[]); $table = $this->parseTable($options['table']); $sql = 'DELETE FROM '.$table; if(strpos($table,',')){// 多表删除支持USING和JOIN操作 @@ -934,7 +934,7 @@ abstract class Driver { */ public function select($options=[]) { $this->model = $options['model']; - $this->parseBind(!empty($options['bind'])?$options['bind']:array()); + $this->parseBind(!empty($options['bind'])?$options['bind']:[]); $sql = $this->buildSelectSql($options); $result = $this->query($sql,!empty($options['fetch_sql']) ? true : false,!empty($options['read_master']) ? true : false); return $result; @@ -1105,7 +1105,7 @@ abstract class Driver { } if($m != $r ){ - $db_master = array( + $db_master = [ 'username' => isset($_config['username'][$m])?$_config['username'][$m]:$_config['username'][0], 'password' => isset($_config['password'][$m])?$_config['password'][$m]:$_config['password'][0], 'hostname' => isset($_config['hostname'][$m])?$_config['hostname'][$m]:$_config['hostname'][0], @@ -1113,9 +1113,9 @@ abstract class Driver { 'database' => isset($_config['database'][$m])?$_config['database'][$m]:$_config['database'][0], 'dsn' => isset($_config['dsn'][$m])?$_config['dsn'][$m]:$_config['dsn'][0], 'charset' => isset($_config['charset'][$m])?$_config['charset'][$m]:$_config['charset'][0], - ); + ]; } - $db_config = array( + $db_config = [ 'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0], 'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0], 'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0], @@ -1123,7 +1123,7 @@ abstract class Driver { 'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0], 'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0], 'charset' => isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0], - ); + ]; return $this->connect($db_config,$r,$r == $m ? false : $db_master); } diff --git a/library/think/db/driver/mongo.php b/library/think/db/driver/mongo.php index 59756bce..9910861e 100644 --- a/library/think/db/driver/mongo.php +++ b/library/think/db/driver/mongo.php @@ -31,7 +31,7 @@ class Mongo extends Driver { */ public function __construct($config=''){ if ( !class_exists('mongoClient') ) { - throw new Exception(L('_NOT_SUPPERT_').':Mongo'); + throw new Exception(Lang::get('_NOT_SUPPERT_').':Mongo'); } if(!empty($config)) { $this->config = array_merge($this->config,$config); @@ -631,7 +631,7 @@ class Mongo extends Driver { }else{ // 查询字段的安全过滤 if(!preg_match('/^[A-Z_\|\&\-.a-z0-9]+$/',trim($key))){ - throw new Exception(L('_ERROR_QUERY_').':'.$key); + throw new Exception(Lang::get('_ERROR_QUERY_').':'.$key); } $key = trim($key); if(strpos($key,'|')) { diff --git a/library/think/db/lite.php b/library/think/db/lite.php index d48082ad..b3f0d561 100644 --- a/library/think/db/lite.php +++ b/library/think/db/lite.php @@ -10,9 +10,10 @@ // +---------------------------------------------------------------------- namespace think\db; -use think\config; -use think\debug; -use think\log; +use think\Config; +use think\Debug; +use think\Log; +use think\Exception; use PDO; class Lite { diff --git a/library/think/debug.php b/library/think/debug.php index 8ff58746..3230dcb9 100644 --- a/library/think/debug.php +++ b/library/think/debug.php @@ -60,8 +60,8 @@ class Debug { $a = ['B', 'KB', 'MB', 'GB', 'TB']; $pos = 0; while ($size >= 1024) { - $size /= 1024; - $pos++; + $size /= 1024; + $pos++; } return round($size,$dec)." ".$a[$pos]; } @@ -81,8 +81,8 @@ class Debug { $a = ['B', 'KB', 'MB', 'GB', 'TB']; $pos = 0; while ($size >= 1024) { - $size /= 1024; - $pos++; + $size /= 1024; + $pos++; } return round($size,$dec)." ".$a[$pos]; } diff --git a/library/think/error.php b/library/think/error.php index bb57ca7e..4c997d18 100644 --- a/library/think/error.php +++ b/library/think/error.php @@ -94,7 +94,7 @@ class Error { $data['code'] = $code; $data['msg'] = $message; $data['time'] = NOW_TIME; - App::returnData($data); + Response::returnData($data); } $e = []; if (APP_DEBUG) { @@ -116,10 +116,11 @@ class Error { if (!empty($error_page)) { header('Location: ' . $error_page); } else { - if (Config::get('show_error_msg')) + if (Config::get('show_error_msg')){ $e['message'] = is_array($error) ? $error['message'] : $error; - else + }else{ $e['message'] = C('error_message'); + } } } // 包含异常页面模板 diff --git a/library/think/input.php b/library/think/input.php index 84fdf6d2..737717e6 100644 --- a/library/think/input.php +++ b/library/think/input.php @@ -150,7 +150,7 @@ class Input { * 获取系统变量 支持过滤和默认值 * @access public * @param string $method 输入数据类型 - * @param array $args 参数 array(key,filter,default) + * @param array $args 参数 [key,filter,default] * @return mixed */ static private function getData($name,$input,$filter,$default) { @@ -183,7 +183,7 @@ class Input { $filters = explode(',',$filters); } }elseif(is_int($filters)){ - $filters = array($filters); + $filters = [$filters]; } if(is_array($filters)){ diff --git a/library/think/lang.php b/library/think/lang.php index 749398ee..93914be0 100644 --- a/library/think/lang.php +++ b/library/think/lang.php @@ -28,7 +28,7 @@ class Lang { * @return mixed */ static public function set($name, $value=null,$range='') { - $range = $range?$range:self::$range; + $range = $range? $range : self::$range; // 批量定义 if (is_array($name)){ return self::$lang[$range] = array_merge(self::$lang[$range], array_change_key_case($name)); @@ -46,8 +46,9 @@ class Lang { static public function get($name=null, $range='') { $range = $range?$range:self::$range; // 空参数返回所有定义 - if (empty($name)) + if (empty($name)){ return self::$lang[$range]; + } $name = strtolower($name); return isset(self::$lang[$range][$name]) ? self::$lang[$range][$name] : $name; } diff --git a/library/think/loader.php b/library/think/loader.php index d84f4893..8e1c2d3f 100644 --- a/library/think/loader.php +++ b/library/think/loader.php @@ -89,8 +89,9 @@ class Loader { $baseUrl = APP_PATH . $class_strut[0] . '/'; } } - if (substr($baseUrl, -1) != '/') + if (substr($baseUrl, -1) != '/'){ $baseUrl .= '/'; + } // 如果类存在 则导入类库文件 $filename = $baseUrl . $class . $ext; if(is_file($filename)) { diff --git a/library/think/log.php b/library/think/log.php index c02f9245..ea2079b5 100644 --- a/library/think/log.php +++ b/library/think/log.php @@ -56,7 +56,9 @@ class Log { */ static public function save($destination='',$level='') { $log = self::getLog($level); - if(empty($log)) return ; + if(empty($log)) { + return ; + } $message = ''; if($level) { $message .= implode("\r\n",$log); diff --git a/library/think/model.php b/library/think/model.php index 70c5272a..484fcf87 100644 --- a/library/think/model.php +++ b/library/think/model.php @@ -13,9 +13,9 @@ namespace think; class Model { // 操作状态 - const MODEL_INSERT = 1; // 插入模型数据 - const MODEL_UPDATE = 2; // 更新模型数据 - const MODEL_BOTH = 3; // 包含上面两种方式 + const MODEL_INSERT = 1; // 新增 + const MODEL_UPDATE = 2; // 更新 + const MODEL_BOTH = 3; // 全部 // 当前数据库操作对象 protected $db = null; // 数据库对象池 @@ -43,9 +43,9 @@ class Model { // 查询表达式参数 protected $options = []; // 命名范围定义 - protected $scope = []; + protected $scope = []; // 字段映射定义 - protected $map = []; + protected $map = []; /** * 架构函数 @@ -110,7 +110,7 @@ class Model { * @return mixed */ public function __get($name) { - return isset($this->data[$name])?$this->data[$name]:null; + return isset($this->data[$name])? $this->data[$name] : null; } /** @@ -206,7 +206,9 @@ class Model { if(false !== $result && is_numeric($result)) { $pk = $this->getPk(); // 增加复合主键支持 - if (is_array($pk)) return $result; + if (is_array($pk)) { + return $result; + } $insertId = $this->getLastInsID(); if($insertId) { // 自增主键返回插入ID @@ -288,7 +290,7 @@ class Model { if(isset($data[$field])) { $where[$field] = $data[$field]; } else { - // 如果缺少复合主键数据则不执行 + // 如果缺少复合主键数据则不执行 $this->error = Lang::get('_OPERATION_WRONG_'); return false; } @@ -351,7 +353,9 @@ class Model { if (is_array($options) && (count($options) > 0) && is_array($pk)) { $count = 0; foreach (array_keys($options) as $key) { - if (is_int($key)) $count++; + if (is_int($key)) { + $count++; + } } if ($count == count($pk)) { $i = 0; @@ -376,7 +380,9 @@ class Model { $result = $this->db->delete($options); if(false !== $result && is_numeric($result)) { $data = []; - if(isset($pkValue)) $data[$pk] = $pkValue; + if(isset($pkValue)) { + $data[$pk] = $pkValue; + } $this->_after_delete($data,$options); } // 返回删除记录个数 @@ -406,7 +412,9 @@ class Model { // 根据复合主键查询 $count = 0; foreach (array_keys($options) as $key) { - if (is_int($key)) $count++; + if (is_int($key)) { + $count++; + } } if ($count == count($pk)) { $i = 0; @@ -427,7 +435,7 @@ class Model { // 判断查询缓存 if(isset($options['cache'])){ $cache = $options['cache']; - $key = is_string($cache['key'])?$cache['key']:md5(serialize($options)); + $key = is_string($cache['key'])? $cache['key'] : md5(serialize($options)); $data = Cache::get($key,'',$cache); if(false !== $data){ return $data; @@ -577,7 +585,9 @@ class Model { // 根据复合主键查询 $count = 0; foreach (array_keys($options) as $key) { - if (is_int($key)) $count++; + if (is_int($key)) { + $count++; + } } if ($count == count($pk)) { $i = 0; @@ -597,7 +607,7 @@ class Model { // 判断查询缓存 if(isset($options['cache'])){ $cache = $options['cache']; - $key = is_string($cache['key'])?$cache['key']:md5(serialize($options)); + $key = is_string($cache['key'])? $cache['key'] : md5(serialize($options)); $data = Cache::get($key,'',$cache); if(false !== $data){ $this->data = $data; @@ -620,7 +630,7 @@ class Model { $this->data = $data; if(isset($cache)){ Cache::set($key,$data,$cache); - } + } return $this->data; } @@ -667,7 +677,7 @@ class Model { } // 状态 - $type = $type?$type:(!empty($data[$this->getPk()])?self::MODEL_UPDATE:self::MODEL_INSERT); + $type = $type? $type : (!empty($data[$this->getPk()])? self::MODEL_UPDATE : self::MODEL_INSERT); // 检测提交字段的合法性 if(isset($this->options['field'])) { // $this->field('field1,field2...')->create() @@ -738,8 +748,9 @@ class Model { * @return string */ public function getModelName() { - if(empty($this->name)) + if(empty($this->name)){ $this->name = substr(get_class($this),0,-5); + } return $this->name; } @@ -828,7 +839,7 @@ class Model { // 增加复合主键支持 if (!empty($this->fields['_pk'])) { if (is_string($this->fields['_pk'])) { - $this->pk = array($this->fields['_pk']); + $this->pk = [$this->fields['_pk']]; $this->fields['_pk'] = $this->pk; } $this->pk[] = $key; @@ -896,10 +907,10 @@ class Model { $options = $this->_parseOptions(); $sql = $this->db->parseSql($sql,$options); }elseif(is_array($parse)){ // SQL预处理 - $parse = array_map(array($this->db,'escapeString'),$parse); + $parse = array_map([$this->db,'escapeString'],$parse); $sql = vsprintf($sql,$parse); }else{ - $sql = strtr($sql,array('__TABLE__'=>$this->getTableName(),'__PREFIX__'=>$this->tablePrefix)); + $sql = strtr($sql,['__TABLE__'=>$this->getTableName(),'__PREFIX__'=>$this->tablePrefix]); $prefix = $this->tablePrefix; $sql = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $sql); } @@ -999,8 +1010,9 @@ class Model { $expire = $key; $key = true; } - if(false !== $key) + if(false !== $key){ $this->options['cache'] = ['key'=>$key,'expire'=>$expire,'type'=>$type]; + } return $this; } @@ -1014,7 +1026,7 @@ class Model { public function field($field,$except=false){ if(true === $field) {// 获取全部字段 $fields = $this->getDbFields(); - $field = $fields?:'*'; + $field = $fields? : '*'; }elseif($except) {// 字段排除 if(is_string($field)) { $field = explode(',',$field); @@ -1074,8 +1086,8 @@ class Model { $parse = func_get_args(); array_shift($parse); } - $parse = array_map([$this->db,'escapeString'],$parse); - $where = vsprintf($where,$parse); + $parse = array_map([$this->db,'escapeString'],$parse); + $where = vsprintf($where,$parse); }elseif(is_object($where)){ $where = get_object_vars($where); } @@ -1118,7 +1130,7 @@ class Model { if(is_null($listRows) && strpos($page,',')){ list($page,$listRows) = explode(',',$page); } - $this->options['page'] = array(intval($page),intval($listRows)); + $this->options['page'] = [intval($page),intval($listRows)]; return $this; } @@ -1324,7 +1336,7 @@ class Model { * @return Model */ public function readMaster(){ - $this->options['read_master'] = true; - return $this; + $this->options['read_master'] = true; + return $this; } } \ No newline at end of file diff --git a/library/think/model/mongo_model.php b/library/think/model/mongo_model.php index cecebb60..56cfad73 100644 --- a/library/think/model/mongo_model.php +++ b/library/think/model/mongo_model.php @@ -49,7 +49,7 @@ class MongoModel extends \Think\Model{ $where[$name] =$args[0]; return $this->where($where)->getField($args[1]); }else{ - throw new \think\Exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); + throw new \think\Exception(__CLASS__.':'.$method.Lang::get('_METHOD_NOT_EXIST_')); return; } } @@ -104,7 +104,7 @@ class MongoModel extends \Think\Model{ // 查询成功后的回调方法 protected function _after_select(&$resultSet,$options) { - array_walk($resultSet,array($this,'checkMongoId')); + array_walk($resultSet,[$this,'checkMongoId']); } /** @@ -134,11 +134,11 @@ class MongoModel extends \Think\Model{ * @param mixed $options 表达式参数 * @return mixed */ - public function find($options=array()) { + public function find($options=[]) { if( is_numeric($options) || is_string($options)) { $id = $this->getPk(); $where[$id] = $options; - $options = array(); + $options = []; $options['where'] = $where; } // 分析表达式 @@ -165,7 +165,7 @@ class MongoModel extends \Think\Model{ * @return boolean */ public function setInc($field,$step=1) { - return $this->setField($field,array('inc',$step)); + return $this->setField($field,['inc',$step]); } /** @@ -176,7 +176,7 @@ class MongoModel extends \Think\Model{ * @return boolean */ public function setDec($field,$step=1) { - return $this->setField($field,array('inc','-'.$step)); + return $this->setField($field,['inc','-'.$step]); } /** @@ -196,11 +196,11 @@ class MongoModel extends \Think\Model{ } $resultSet = $this->db->select($options); if(!empty($resultSet)) { - $_field = explode(',', $field); - $field = array_keys($resultSet[0]); - $key = array_shift($field); - $key2 = array_shift($field); - $cols = array(); + $_field = explode(',', $field); + $field = array_keys($resultSet[0]); + $key = array_shift($field); + $key2 = array_shift($field); + $cols = []; $count = count($_field); foreach ($resultSet as $result){ $name = $result[$key]; @@ -246,7 +246,7 @@ class MongoModel extends \Think\Model{ * @param array $args 参数 * @return mixed */ - public function mongoCode($code,$args=array()) { + public function mongoCode($code,$args=[]) { return $this->db->execute($code,$args); } diff --git a/library/think/route.php b/library/think/route.php index 20ce3fcb..13e770d2 100644 --- a/library/think/route.php +++ b/library/think/route.php @@ -231,8 +231,9 @@ class Route { return true; }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) { return true; + }else{ + return false; } - return false; } // 执行正则匹配下的闭包方法 支持参数调用 @@ -354,13 +355,13 @@ class Route { // 解析规则路由 // '路由规则'=>'[控制器/操作]?额外参数1=值1&额外参数2=值2...' - // '路由规则'=>array('[控制器/操作]','额外参数1=值1&额外参数2=值2...') + // '路由规则'=> ['[控制器/操作]','额外参数1=值1&额外参数2=值2...'] // '路由规则'=>'外部地址' - // '路由规则'=>array('外部地址','重定向代码') + // '路由规则'=>['外部地址','重定向代码'] // 路由规则中 :开头 表示动态变量 // 外部地址中可以用动态变量 采用 :1 :2 的方式 - // 'news/:month/:day/:id'=>array('News/read?cate=1','status=1'), - // 'new/:id'=>array('/new.php?id=:1',301), 重定向 + // 'news/:month/:day/:id'=>['News/read?cate=1','status=1'], + // 'new/:id'=>['/new.php?id=:1',301], 重定向 static private function parseRule($rule, $route, $regx) { // 获取路由地址规则 $url = is_array($route) ? $route[0] : $route; @@ -418,12 +419,12 @@ class Route { // 解析正则路由 // '路由正则'=>'[控制器/操作]?参数1=值1&参数2=值2...' - // '路由正则'=>array('[控制器/操作]?参数1=值1&参数2=值2...','额外参数1=值1&额外参数2=值2...') + // '路由正则'=>['[控制器/操作]?参数1=值1&参数2=值2...','额外参数1=值1&额外参数2=值2...'] // '路由正则'=>'外部地址' - // '路由正则'=>array('外部地址','重定向代码') + // '路由正则'=>['外部地址','重定向代码'] // 参数值和外部地址中可以用动态变量 采用 :1 :2 的方式 - // '/new\/(\d+)\/(\d+)/'=>array('News/read?id=:1&page=:2&cate=1','status=1'), - // '/new\/(\d+)/'=>array('/new.php?id=:1&page=:2&status=1','301'), 重定向 + // '/new\/(\d+)\/(\d+)/'=>['News/read?id=:1&page=:2&cate=1','status=1'], + // '/new\/(\d+)/'=>['/new.php?id=:1&page=:2&status=1','301'], 重定向 static private function parseRegex($matches, $route, $regx) { // 获取路由地址规则 $url = is_array($route) ? $route[0] : $route; diff --git a/library/think/template.php b/library/think/template.php index 6b24f818..8375c3d0 100644 --- a/library/think/template.php +++ b/library/think/template.php @@ -171,8 +171,9 @@ class Template { * @return boolen */ private function checkCache($template,$cacheFile) { - if (!$this->config['tpl_cache']) // 优先对配置设定检测 + if (!$this->config['tpl_cache']) {// 优先对配置设定检测 return false; + } // 检查编译存储是否有效 return $this->storage->check($template,$cacheFile,$this->config['cache_time']); } @@ -226,7 +227,9 @@ class Template { */ public function parse($content) { // 内容为空不解析 - if(empty($content)) return ''; + if(empty($content)) { + return ''; + } $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; // 检查include语法 @@ -279,7 +282,7 @@ class Template { } // PHP语法检查 if($this->config['tpl_deny_php'] && false !== strpos($content,''; $xml = simplexml_load_string($xml); - if(!$xml) - exit('_XML_TAG_ERROR_'); + if(!$xml){ + throw new Exception('_XML_TAG_ERROR_'); + } $xml = (array)($xml->tag->attributes()); $array = array_change_key_case($xml['@attributes']); return $array; @@ -375,7 +379,9 @@ class Template { * @return string */ private function parseLiteral($content) { - if(trim($content)=='') return ''; + if(trim($content)=='') { + return ''; + } $content = stripslashes($content); $i = count($this->literal); $parseStr = ""; @@ -500,13 +506,14 @@ class Template { * @return string */ private function parseXmlTag($tLib,$tagLib,$tag,$attr,$content) { - $attr = stripslashes($attr); - $content= stripslashes($content); - if(ini_get('magic_quotes_sybase')) - $attr = str_replace('\"','\'',$attr); - $parse = '_'.$tag; - $content = trim($content); - $tags = $tLib->parseXmlAttr($attr,$tag); + $attr = stripslashes($attr); + $content = stripslashes($content); + if(ini_get('magic_quotes_sybase')){ + $attr = str_replace('\"','\'',$attr); + } + $parse = '_'.$tag; + $content = trim($content); + $tags = $tLib->parseXmlAttr($attr,$tag); return $tLib->$parse($tags,$content); } @@ -554,7 +561,9 @@ class Template { $varStr = trim($varStr); static $_varParseList = []; //如果已经解析过该变量字串,则直接返回变量值 - if(isset($_varParseList[$varStr])) return $_varParseList[$varStr]; + if(isset($_varParseList[$varStr])) { + return $_varParseList[$varStr]; + } $parseStr = ''; if(!empty($varStr)){ $varArray = explode('|',$varStr); @@ -582,8 +591,9 @@ class Template { $name = "$$var"; } //对变量使用函数 - if(count($varArray)>0) + if(count($varArray)>0){ $name = $this->parseVarFunction($name,$varArray); + } $parseStr = ''; } $_varParseList[$varStr] = $parseStr; @@ -645,13 +655,13 @@ class Template { switch($vars[1]){ case 'SERVER': $parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']'; - break; + break; case 'GET': $parseStr = '$_GET[\''.$vars[2].'\']'; - break; + break; case 'POST': $parseStr = '$_POST[\''.$vars[2].'\']'; - break; + break; case 'COOKIE': if(isset($vars[3])) { $parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']'; @@ -668,24 +678,24 @@ class Template { break; case 'ENV': $parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']'; - break; + break; case 'REQUEST': $parseStr = '$_REQUEST[\''.$vars[2].'\']'; - break; + break; case 'CONST': $parseStr = strtoupper($vars[2]); - break; + break; case 'LANG': $parseStr = '\\think\\lang::get("'.$vars[2].'")'; - break; + break; case 'CONFIG': if(isset($vars[3])) { $vars[2] .= '.'.$vars[3]; } $parseStr = '\\think\\config::get("'.$vars[2].'")'; - break; + break; default: - break; + break; } }else if(count($vars)==2){ switch($vars[1]){ @@ -704,7 +714,7 @@ class Template { default: if(defined($vars[1])){ $parseStr = $vars[1]; - } + } } } return $parseStr; @@ -737,9 +747,10 @@ class Template { * @return string */ private function parseTemplateName($templateName){ - if(substr($templateName,0,1)=='$') + if(substr($templateName,0,1)=='$'){ //支持加载变量文件名 $templateName = $this->get(substr($templateName,1)); + } $array = explode(',',$templateName); $parseStr = ''; foreach ($array as $templateName){ diff --git a/library/think/template/driver/file.php b/library/think/template/driver/file.php index b30aa811..6e52d091 100644 --- a/library/think/template/driver/file.php +++ b/library/think/template/driver/file.php @@ -10,7 +10,7 @@ // +---------------------------------------------------------------------- namespace think\template\driver; -use think\exception; +use think\Exception; class File { // 写入编译缓存 diff --git a/library/think/template/taglib.php b/library/think/template/taglib.php index 26d3f61f..28e23055 100644 --- a/library/think/template/taglib.php +++ b/library/think/template/taglib.php @@ -10,6 +10,7 @@ // +---------------------------------------------------------------------- namespace think\template; +use think\Exception; /** * ThinkPHP标签库TagLib解析基类 @@ -83,7 +84,7 @@ class TagLib { $xml = ''; $xml = simplexml_load_string($xml); if(!$xml) { - exit('_XML_TAG_ERROR_ : '.$attr); + throw new Exception('_XML_TAG_ERROR_ : '.$attr); } $xml = (array)($xml->tag->attributes()); $array = array_change_key_case($xml['@attributes']); @@ -100,7 +101,7 @@ class TagLib { if( isset($array[$name])) { $array[$name] = str_replace('___','&',$array[$name]); }elseif(false !== array_search($name,$must)){ - exit('_PARAM_ERROR_:'.$name); + throw new Exception('_PARAM_ERROR_:'.$name); } } } diff --git a/library/think/url.php b/library/think/url.php index 8c6af373..c25aef21 100644 --- a/library/think/url.php +++ b/library/think/url.php @@ -25,7 +25,7 @@ class Url { $config = Config::get(); // 解析URL $info = parse_url($url); - $url = !empty($info['path'])?$info['path']:ACTION_NAME; + $url = !empty($info['path'])? $info['path'] : ACTION_NAME; if(isset($info['fragment'])) { // 解析锚点 $anchor = $info['fragment']; if(false !== strpos($anchor,'?')) { // 解析参数 @@ -39,7 +39,7 @@ class Url { } // 解析子域名 if(isset($host)) { - $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.')); + $domain = $host.(strpos($host,'.')? '' : strstr($_SERVER['HTTP_HOST'],'.')); }elseif($domain===true){ $domain = $_SERVER['HTTP_HOST']; if($config['app_sub_domain_deplay'] ) { // 开启子域名部署 @@ -107,7 +107,9 @@ class Url { } if(!empty($vars)) { // 添加参数 foreach ($vars as $var => $val){ - if('' !== trim($val)) $url .= $depr . $var . $depr . urlencode($val); + if('' !== trim($val)) { + $url .= $depr . $var . $depr . urlencode($val); + } } } if($suffix) { diff --git a/mode/sae.php b/mode/sae.php index b5aa8925..5cdecd0d 100644 --- a/mode/sae.php +++ b/mode/sae.php @@ -18,21 +18,35 @@ return [ 'config' => [ /* 数据库设置 */ 'database' => [ - 'type' => 'mysql', // 数据库类型 + // 数据库类型 + 'type' => 'mysql', 'dsn' => '', // - 'hostname' => SAE_MYSQL_HOST_M.','.SAE_MYSQL_HOST_S, // 服务器地址 - 'database' => SAE_MYSQL_DB, // 数据库名 - 'username' => SAE_MYSQL_USER, // 用户名 - 'password' => SAE_MYSQL_PASS, // 密码 - 'hostport' => SAE_MYSQL_PORT, // 端口 - 'params' => [], // 数据库连接参数 - 'charset' => 'utf8', // 数据库编码默认采用utf8 - 'prefix' => '', // 数据库表前缀 - 'debug' => false, // 数据库调试模式 - 'deploy' => 1, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) - 'rw_separate' => true, // 数据库读写是否分离 主从式有效 - 'master_num' => 1, // 读写分离后 主服务器数量 - 'slave_no' => '', // 指定从服务器序号 + // 服务器地址 + 'hostname' => SAE_MYSQL_HOST_M.','.SAE_MYSQL_HOST_S, + // 数据库名 + 'database' => SAE_MYSQL_DB, + // 用户名 + 'username' => SAE_MYSQL_USER, + // 密码 + 'password' => SAE_MYSQL_PASS, + // 端口 + 'hostport' => SAE_MYSQL_PORT, + // 数据库连接参数 + 'params' => [], + // 数据库编码默认采用utf8 + 'charset' => 'utf8', + // 数据库表前缀 + 'prefix' => '', + // 数据库调试模式 + 'debug' => false, + // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) + 'deploy' => 1, + // 数据库读写是否分离 主从式有效 + 'rw_separate' => true, + // 读写分离后 主服务器数量 + 'master_num' => 1, + // 指定从服务器序号 + 'slave_no' => '', ], 'log_type' => 'Sae', 'data_cache_type' => 'Memcachesae', diff --git a/start.php b/start.php index 5245c31e..7456913f 100644 --- a/start.php +++ b/start.php @@ -11,10 +11,7 @@ namespace think; -//-------------------------- // ThinkPHP 引导文件 -//-------------------------- - // 加载基础文件 require __DIR__.'/base.php'; require CORE_PATH.'loader.php'; @@ -23,9 +20,9 @@ require CORE_PATH.'loader.php'; Loader::register(); // 注册错误和异常处理机制 -register_shutdown_function(['think\Error','appShutdown']); -set_error_handler(['think\Error','appError']); -set_exception_handler(['think\Error','appException']); +register_shutdown_function(['think\error','appShutdown']); +set_error_handler(['think\error','appError']); +set_exception_handler(['think\error','appException']); // 加载模式定义文件 $mode = require MODE_PATH.APP_MODE.EXT; diff --git a/traits/think/model/auto.php b/traits/think/model/auto.php index 92c6feb6..e01a0982 100644 --- a/traits/think/model/auto.php +++ b/traits/think/model/auto.php @@ -35,7 +35,7 @@ trait Auto { } // 验证数据 if(empty($data) || !is_array($data)) { - $this->error = L('_DATA_TYPE_INVALID_'); + $this->error = \think\Lang::get('_DATA_TYPE_INVALID_'); return false; } @@ -94,7 +94,7 @@ trait Auto { * @return boolean */ public function regex($value,$rule) { - $validate = array( + static $validate = [ 'require' => '/.+/', 'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/', 'url' => '/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/', @@ -104,10 +104,11 @@ trait Auto { 'integer' => '/^[-\+]?\d+$/', 'double' => '/^[-\+]?\d+(\.\d+)?$/', 'english' => '/^[A-Za-z]+$/', - ); + ]; // 检查是否有内置的正则表达式 - if(isset($validate[strtolower($rule)])) + if(isset($validate[strtolower($rule)])){ $rule = $validate[strtolower($rule)]; + } return preg_match($rule,$value)===1; } @@ -129,8 +130,10 @@ trait Auto { if(isset($_auto)) { foreach ($_auto as $auto){ // 填充因子定义格式 - // array('field','填充内容','填充条件','附加规则',[额外参数]) - if(empty($auto[2])) $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充 + // ['field','填充内容','填充条件','附加规则',[额外参数]] + if(empty($auto[2])) { + $auto[2] = self::MODEL_INSERT; // 默认为新增的时候自动填充 + } if( $type == $auto[2] || $auto[2] == self::MODEL_BOTH) { switch(trim($auto[3])) { case 'function': // 使用函数进行填充 字段的值作为参数 @@ -142,21 +145,24 @@ trait Auto { if('function'==$auto[3]) { $data[$auto[0]] = call_user_func_array($auto[1], $args); }else{ - $data[$auto[0]] = call_user_func_array(array(&$this,$auto[1]), $args); + $data[$auto[0]] = call_user_func_array([&$this,$auto[1]], $args); } break; case 'field': // 用其它字段的值进行填充 $data[$auto[0]] = $data[$auto[1]]; break; case 'ignore': // 为空忽略 - if(''===$data[$auto[0]]) + if(''===$data[$auto[0]]){ unset($data[$auto[0]]); + } break; case 'string': default: // 默认作为字符串填充 $data[$auto[0]] = $auto[1]; } - if(false === $data[$auto[0]] ) unset($data[$auto[0]]); + if(false === $data[$auto[0]] ) { + unset($data[$auto[0]]); + } } } } @@ -172,24 +178,25 @@ trait Auto { */ protected function autoValidation($data,$type) { if(!empty($this->options['validate'])) { - $validate = $this->options['validate']; + $_validate = $this->options['validate']; unset($this->options['validate']); }elseif(!empty($this->validate)){ - $validate = $this->validate; + $_validate = $this->validate; } // 属性验证 - if(isset($validate)) { // 如果设置了数据自动验证则进行数据验证 + if(isset($_validate)) { // 如果设置了数据自动验证则进行数据验证 if($this->patchValidate) { // 重置验证错误信息 $this->error = []; } - foreach($validate as $key=>$val) { + foreach($_validate as $key=>$val) { // 验证因子定义格式 - // array(field,rule,message,condition,type,when,params) + // [field,rule,message,condition,type,when,params] // 判断是否需要执行验证 if(empty($val[5]) || $val[5]== self::MODEL_BOTH || $val[5]== $type ) { - if(0==strpos($val[2],'{%') && strpos($val[2],'}')) + if(0==strpos($val[2],'{%') && strpos($val[2],'}')){ // 支持提示信息的多语言 使用 {%语言定义} 方式 $val[2] = L(substr($val[2],2,-1)); + } $val[3] = isset($val[3])?$val[3]:EXISTS_VALIDATE; $val[4] = isset($val[4])?$val[4]:'regex'; // 判断验证条件 @@ -204,14 +211,16 @@ trait Auto { return false; break; default: // 默认表单存在该字段就验证 - if(isset($data[$val[0]])) - if(false === $this->_validationField($data,$val)) - return false; + if(isset($data[$val[0]]) && false === $this->_validationField($data,$val)) { + return false; + } } } } // 批量验证的时候最后返回错误 - if(!empty($this->error)) return false; + if(!empty($this->error)) { + return false; + } } return true; } @@ -248,39 +257,38 @@ trait Auto { case 'function':// 使用函数进行验证 case 'callback':// 调用方法进行验证 $args = isset($val[6])?(array)$val[6]:[]; - if(is_string($val[0]) && strpos($val[0], ',')) + if(is_string($val[0]) && strpos($val[0], ',')){ $val[0] = explode(',', $val[0]); + } if(is_array($val[0])){ // 支持多个字段验证 - foreach($val[0] as $field) + foreach($val[0] as $field){ $_data[$field] = $data[$field]; + } array_unshift($args, $_data); }else{ array_unshift($args, $data[$val[0]]); } - if('function'==$val[4]) { - return call_user_func_array($val[1], $args); - }else{ - return call_user_func_array(array(&$this, $val[1]), $args); - } + 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]) && strpos($val[0],',')) + if(is_string($val[0]) && strpos($val[0],',')){ $val[0] = explode(',',$val[0]); + } $map = []; if(is_array($val[0])) { // 支持多个字段验证 - foreach ($val[0] as $field) + foreach ($val[0] as $field){ $map[$field] = $data[$field]; + } }else{ $map[$val[0]] = $data[$val[0]]; } if(!empty($data[$this->getPk()])) { // 完善编辑的时候验证唯一 - $map[$this->getPk()] = array('neq',$data[$this->getPk()]); + $map[$this->getPk()] = ['neq',$data[$this->getPk()]]; } - if($this->where($map)->find()) return false; - return true; + return $this->where($map)->find() ? false : true; default: // 检查附加规则 return $this->check($data[$val[0]],$val[1],$val[4]); } @@ -323,8 +331,12 @@ trait Auto { } case 'expire': list($start,$end) = explode(',',$rule); - if(!is_numeric($start)) $start = strtotime($start); - if(!is_numeric($end)) $end = strtotime($end); + 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(get_client_ip(),explode(',',$rule)); @@ -354,7 +366,7 @@ trait Auto { * @param array $validate 自动验证设置 * @return Model */ - public function validate($auto){ + public function validate($validate){ $this->options['validate'] = $validate; return $this; } diff --git a/traits/think/model/extend.php b/traits/think/model/extend.php index ddbe48e9..95e6357f 100644 --- a/traits/think/model/extend.php +++ b/traits/think/model/extend.php @@ -10,7 +10,7 @@ // +---------------------------------------------------------------------- namespace traits\think\model; -use think\Loader; +use think\loader; trait Extend { protected $partition = []; @@ -23,7 +23,7 @@ trait Extend { * @return mixed */ public function __call($method,$args) { - if(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){ + if(in_array(strtolower($method),['count','sum','min','max','avg'],true)){ // 统计查询的实现 $field = isset($args[0])?$args[0]:'*'; return $this->getField(strtoupper($method).'('.$field.') AS tp_'.$method); @@ -40,7 +40,7 @@ trait Extend { }elseif(isset($this->scope[$method])){// 命名范围的单独调用支持 return $this->scope($method,$args[0]); }else{ - throw new \think\Exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_')); + throw new \think\Exception(__CLASS__.':'.$method.\think\Lang::get('_METHOD_NOT_EXIST_')); return; } } @@ -102,12 +102,11 @@ trait Extend { } $resultSet = $this->db->select($options); if(!empty($resultSet)) { - $_field = explode(',', $field); $field = array_keys($resultSet[0]); $key = array_shift($field); $key2 = array_shift($field); $cols = []; - $count = count($_field); + $count = count(explode(',', $field)); foreach ($resultSet as $result){ $name = $result[$key]; if(2==$count) { @@ -125,7 +124,9 @@ trait Extend { } $result = $this->db->select($options); if(!empty($result)) { - if(true !== $sepa && 1==$options['limit']) return reset($result[0]); + if(true !== $sepa && 1==$options['limit']) { + return reset($result[0]); + } foreach ($result as $val){ $array[] = $val[$field]; } @@ -149,11 +150,14 @@ trait Extend { return false; } if($lazyTime>0) {// 延迟写入 - $guid = md5($this->name.'_'.$field.'_'.serialize($condition)); - $step = $this->lazyWrite($guid,$step,$lazyTime); - if(false === $step ) return true; // 等待下次写入 + $guid = md5($this->name.'_'.$field.'_'.serialize($condition)); + $step = $this->lazyWrite($guid,$step,$lazyTime); + if(false === $step ) { + // 等待下次写入 + return true; + } } - return $this->setField($field,array('exp',$field.'+'.$step)); + return $this->setField($field,['exp',$field.'+'.$step]); } /** @@ -172,9 +176,12 @@ trait Extend { if($lazyTime>0) {// 延迟写入 $guid = md5($this->name.'_'.$field.'_'.serialize($condition)); $step = $this->lazyWrite($guid,$step,$lazyTime); - if(false === $step ) return true; // 等待下次写入 + if(false === $step ) { + // 等待下次写入 + return true; + } } - return $this->setField($field,array('exp',$field.'-'.$step)); + return $this->setField($field,['exp',$field.'-'.$step]); } /** @@ -252,10 +259,10 @@ trait Extend { // 当设置的分表字段不在查询条件或者数据中 // 进行联合查询,必须设定 partition['num'] $tableName = []; - for($i=0;$i<$this->partition['num'];$i++) + for($i=0;$i<$this->partition['num'];$i++){ $tableName[] = 'SELECT * FROM '.$this->getTableName().'_'.($i+1); - $tableName = '( '.implode(" UNION ",$tableName).') AS '.$this->name; - return $tableName; + } + return '( '.implode(" UNION ",$tableName).') AS '.$this->name; } } } \ No newline at end of file diff --git a/traits/think/model/query.php b/traits/think/model/query.php index fb0a172f..9fab35f2 100644 --- a/traits/think/model/query.php +++ b/traits/think/model/query.php @@ -52,12 +52,12 @@ trait Query { public function parseSql($sql,$parse) { // 分析表达式 if(true === $parse) { - $options = $this->_parseOptions(); - $sql = $this->db->parseSql($sql,$options); + $options = $this->_parseOptions(); + $sql = $this->db->parseSql($sql,$options); }elseif(is_array($parse)){ // SQL预处理 - $sql = vsprintf($sql,$parse); + $sql = vsprintf($sql,$parse); }else{ - $sql = strtr($sql,['__TABLE__'=>$this->getTableName(),'__PREFIX__'=>$this->tablePrefix]); + $sql = strtr($sql,['__TABLE__' => $this->getTableName(),'__PREFIX__' => $this->tablePrefix]); } return $sql; } @@ -70,7 +70,9 @@ trait Query { * @return boolean */ public function patchQuery($sql=[]) { - if(!is_array($sql)) return false; + if(!is_array($sql)) { + return false; + } // 自动启动事务支持 $this->startTrans(); try{ @@ -84,7 +86,7 @@ trait Query { } // 提交事务 $this->commit(); - } catch (\Think\Exception $e) { + } catch (\think\exception $e) { $this->rollback(); } return true; diff --git a/traits/think/model/relation.php b/traits/think/model/relation.php index 74f08eb3..e0ed4fa9 100644 --- a/traits/think/model/relation.php +++ b/traits/think/model/relation.php @@ -18,7 +18,7 @@ define('MANY_TO_MANY',4); trait Relation { // 关联定义 - protected $link = array(); + protected $link = []; /** * 得到关联的数据表名 @@ -166,7 +166,7 @@ trait Relation { break; } if(!$return){ - if(isset($val['as_fields']) && in_array($mappingType,array(HAS_ONE,BELONGS_TO)) ) { + if(isset($val['as_fields']) && in_array($mappingType,[HAS_ONE,BELONGS_TO]) ) { // 支持直接把关联的字段值映射成数据对象中的某个字段 // 仅仅支持HAS_ONE BELONGS_TO $fields = explode(',',$val['as_fields']); @@ -228,7 +228,7 @@ trait Relation { if(!empty($val['condition'])) { $mappingCondition = $val['condition']; }else{ - $mappingCondition = array(); + $mappingCondition = []; $mappingCondition[$mappingFk] = $pk; } // 获取关联model对象 @@ -285,7 +285,7 @@ trait Relation { $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 = array(); + $ids = []; foreach ($mappingData as $vo) $ids[] = $vo[$mappingKey]; $relationId = implode(',',$ids); diff --git a/traits/think/model/view.php b/traits/think/model/view.php index 14818d30..8cc50b0b 100644 --- a/traits/think/model/view.php +++ b/traits/think/model/view.php @@ -32,23 +32,24 @@ trait View { $tableName = ''; foreach ($this->viewFields as $key=>$view){ // 获取数据表名称 - if(isset($view['_table'])) { // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图 - $tableName .= $view['_table']; + if(isset($view['_table'])) { + // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图 + $tableName .= $view['_table']; }else{ - $class = $key.'Model'; - $Model = class_exists($class)?new $class():M($key); - $tableName .= $Model->getTableName(); + $class = $key.'Model'; + $model = class_exists($class)? new $class() : M($key); + $tableName .= $model->getTableName(); } // 表别名定义 - $tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key; + $tableName .= !empty($view['_as'])? ' '.$view['_as'] :' '.$key; // 支持ON 条件定义 - $tableName .= !empty($view['_on'])?' ON '.$view['_on']:''; + $tableName .= !empty($view['_on'])? ' ON '.$view['_on'] : ''; // 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效 - $type = !empty($view['_type'])?$view['_type']:''; - $tableName .= ' '.strtoupper($type).' JOIN '; - $len = strlen($type.'_JOIN '); + $type = !empty($view['_type'])?$view['_type']:''; + $tableName .= ' '.strtoupper($type).' JOIN '; + $len = strlen($type.'_JOIN '); } - $tableName = substr($tableName,0,-$len); + $tableName = substr($tableName,0,-$len); $this->trueTableName = $tableName; } return $this->trueTableName; @@ -61,16 +62,20 @@ trait View { * @return void */ protected function _options_filter(&$options) { - if(isset($options['field'])) - $options['field'] = $this->checkFields($options['field']); - else - $options['field'] = $this->checkFields(); - if(isset($options['group'])) - $options['group'] = $this->checkGroup($options['group']); - if(isset($options['where'])) - $options['where'] = $this->checkCondition($options['where']); - if(isset($options['order'])) - $options['order'] = $this->checkOrder($options['order']); + if(isset($options['field'])){ + $options['field'] = $this->checkFields($options['field']); + }else{ + $options['field'] = $this->checkFields(); + } + if(isset($options['group'])){ + $options['group'] = $this->checkGroup($options['group']); + } + if(isset($options['where'])){ + $options['where'] = $this->checkCondition($options['where']); + } + if(isset($options['order'])){ + $options['order'] = $this->checkOrder($options['order']); + } } /** @@ -126,16 +131,16 @@ trait View { $orders = explode(',',$order); $_order = []; foreach ($orders as $order){ - $array = explode(' ',$order); - $field = $array[0]; - $sort = isset($array[1])?$array[1]:'ASC'; + $array = explode(' ',$order); + $field = $array[0]; + $sort = isset($array[1])? $array[1] : 'ASC'; // 解析成视图字段 foreach ($this->viewFields as $name=>$val){ - $k = isset($val['_as'])?$val['_as']:$name; - $val = $this->_checkFields($name,$val); + $k = isset($val['_as']) ? $val['_as'] : $name; + $val = $this->_checkFields($name,$val); if(false !== $_field = array_search($field,$val,true)) { // 存在视图字段 - $field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field; + $field = is_numeric($_field)? $k.'.'.$field : $k.'.'.$_field; break; } } @@ -159,11 +164,11 @@ trait View { foreach ($groups as $field){ // 解析成视图字段 foreach ($this->viewFields as $name=>$val){ - $k = isset($val['_as'])?$val['_as']:$name; - $val = $this->_checkFields($name,$val); + $k = isset($val['_as'])? $val['_as'] : $name; + $val = $this->_checkFields($name,$val); if(false !== $_field = array_search($field,$val,true)) { // 存在视图字段 - $field = is_numeric($_field)?$k.'.'.$field:$k.'.'.$_field; + $field = is_numeric($_field)? $k.'.'.$field : $k.'.'.$_field; break; } } @@ -185,8 +190,8 @@ trait View { // 获取全部视图字段 $fields = []; foreach ($this->viewFields as $name=>$val){ - $k = isset($val['_as'])?$val['_as']:$name; - $val = $this->_checkFields($name,$val); + $k = isset($val['_as'])? $val['_as'] : $name; + $val = $this->_checkFields($name,$val); foreach ($val as $key=>$field){ if(is_numeric($key)) { $fields[] = $k.'.'.$field.' AS '.$field; @@ -203,8 +208,9 @@ trait View { } $fields = implode(',',$fields); }else{ - if(!is_array($fields)) + if(!is_array($fields)){ $fields = explode(',',$fields); + } // 解析成视图字段 $array = []; foreach ($fields as $key=>$field){ @@ -215,19 +221,20 @@ trait View { } } foreach ($this->viewFields as $name=>$val){ - $k = isset($val['_as'])?$val['_as']:$name; - $val = $this->_checkFields($name,$val); + $k = isset($val['_as'])? $val['_as'] : $name; + $val = $this->_checkFields($name,$val); foreach ($fields as $key=>$field){ if(false !== $_field = array_search($field,$val,true)) { // 存在视图字段 if(is_numeric($_field)) { $array[] = $k.'.'.$field.' AS '.$field; }elseif('_' != substr($_field,0,1)){ - if( false !== strpos($_field,'*') || false !== strpos($_field,'(') || false !== strpos($_field,'.')) + if( false !== strpos($_field,'*') || false !== strpos($_field,'(') || false !== strpos($_field,'.')){ //如果包含* 或者 使用了sql方法 则不再添加前面的表名 $array[] = $_field.' AS '.$field; - else + }else{ $array[] = $k.'.'.$_field.' AS '.$field; + } } } }