规范调整

This commit is contained in:
thinkphp
2015-10-03 21:43:48 +08:00
parent 7c2bcbcff2
commit 1cfb3704c6
31 changed files with 393 additions and 285 deletions

View File

@@ -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;
}

View File

@@ -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;
}
}
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -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;
}
}
}
}