sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function debugLogSql($type = 'Query', $tableName, $condition = [], $options = []) { if (Cml::$debug) { Debug::addSqlInfo(sprintf( "[MongoDB {$type}] Collection: %s, Condition: %s, Other: %s", $this->getDbName() . ".{$tableName}", json_encode($condition, JSON_UNESCAPED_UNICODE), json_encode($options, JSON_UNESCAPED_UNICODE) )); } }
Debug模式记录查询语句显示到控制台 @param string $type 查询的类型 @param string $tableName 查询的Collection @param array $condition 条件 @param array $options 额外参数
entailment
public function runMongoCommand($cmd = [], $runOnMaster = true, $returnCursor = false) { Cml::$debug && $this->debugLogSql('Command', '', $cmd); $this->reset(); $db = $runOnMaster ? $this->getMaster()->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY_PREFERRED)) : $this->getSlave()->selectServer(new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED)); $cursor = $db->executeCommand($this->getDbName(), new Command($cmd)); if ($returnCursor) { return $cursor; } else { $cursor->setTypeMap(['root' => 'array', 'document' => 'array']); $result = []; foreach ($cursor as $collection) { $result[] = $collection; } return $result; } }
执行命令 @param array $cmd 要执行的Command @param bool $runOnMaster 使用主库还是从库执行 默认使用主库执行 @param bool $returnCursor 返回数据还是cursor 默认返回结果数据 @return array|Cursor
entailment
public function set($table, $data, $tablePrefix = null) { if (is_array($data)) { is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; $bulk = new BulkWrite(); $insertId = $bulk->insert($data); $result = $this->runMongoBulkWrite($tablePrefix . $table, $bulk); Cml::$debug && $this->debugLogSql('BulkWrite INSERT', $tablePrefix . $table, [], $data); if ($result->getInsertedCount() > 0) { $this->lastInsertId = sprintf('%s', $insertId); } return $this->insertId(); } else { return false; } }
根据key 新增 一条数据 @param string $table 表名 @param array $data eg: ['username'=>'admin', 'email'=>'[email protected]'] @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @return bool|int
entailment
public function setMulti($table, $field, $data, $tablePrefix = null, $openTransAction = true) { $idArray = []; foreach ($data as $row) { $idArray[] = $this->set($table, $row, $tablePrefix); } return $idArray; }
新增多条数据 @param string $table 表名 @param array $field mongodb中本参数无效 @param array $data eg: 多条数据的值 [['标题1', '内容1', 1, '2017'], ['标题2', '内容2', 1, '2017']] @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @param bool $openTransAction 是否开启事务 mongodb中本参数无效 @throws \InvalidArgumentException @return bool|array
entailment
public function replaceInto($table, array $data, $tablePrefix = null) { return $this->upSet($table, $data, $data, $tablePrefix); }
插入或替换一条记录 若AUTO_INCREMENT存在则返回 AUTO_INCREMENT 的值. @param string $table 表名 @param array $data 插入/更新的值 eg: ['username'=>'admin', 'email'=>'[email protected]'] @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @return int
entailment
public function upSet($table, array $data = [], array $up = [], $tablePrefix = null) { is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; $tableName = $tablePrefix . $table; if (empty($tableName)) { throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_TABLE_', 'upSet')); } $condition = $this->sql['where']; if (empty($condition)) { throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_CONDITION_', 'upSet')); } $bulk = new BulkWrite(); $bulk->update($condition, ['$set' => array_merge($data, $up)], ['multi' => true, 'upsert' => true]); $result = $this->runMongoBulkWrite($tableName, $bulk); Cml::$debug && $this->debugLogSql('BulkWrite upSet', $tableName, $condition, $data); return $result->getModifiedCount(); }
插入或更新一条记录,当UNIQUE index or PRIMARY KEY存在的时候更新,不存在的时候插入 若AUTO_INCREMENT存在则返回 AUTO_INCREMENT 的值. @param string $table 表名 @param array $data 插入的值 eg: ['username'=>'admin', 'email'=>'[email protected]'] @param array $up mongodb中此项无效 @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @return int
entailment
public function update($key, $data = null, $and = true, $tablePrefix = null) { is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; $tableName = $condition = ''; if (is_array($data)) { list($tableName, $condition) = $this->parseKey($key, $and, true, true); } else { $data = $key; } $tableName = empty($tableName) ? $this->getRealTableName(key($this->table)) : $tablePrefix . $tableName; if (empty($tableName)) { throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_TABLE_', 'update')); } $condition += $this->sql['where']; if (empty($condition)) { throw new \InvalidArgumentException(Lang::get('_PARSE_SQL_ERROR_NO_CONDITION_', 'update')); } $bulk = new BulkWrite(); $bulk->update($condition, ['$set' => $data], ['multi' => true]); $result = $this->runMongoBulkWrite($tableName, $bulk); Cml::$debug && $this->debugLogSql('BulkWrite UPDATE', $tableName, $condition, $data); return $result->getModifiedCount(); }
根据key更新一条数据 @param string|array $key eg 'user-uid-$uid' 如果条件是通用whereXX()、表名是通过table()设定。这边可以直接传$data的数组 @param array | null $data eg: ['username'=>'admin', 'email'=>'[email protected]'] @param bool $and 多个条件之间是否为and true为and false为or @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @return boolean
entailment
public function conditionFactory($column, $value, $operator = '=') { $currentOrIndex = isset($this->sql['where']['$or']) ? count($this->sql['where']['$or']) - 1 : 0; if ($this->opIsAnd) { if (isset($this->sql['where'][$column][$operator])) { throw new \InvalidArgumentException('Mongodb Where Op key Is Exists[' . $column . $operator . ']'); } } else if ($this->bracketsIsOpen) { if (isset($this->sql['where']['$or'][$currentOrIndex][$column][$operator])) { throw new \InvalidArgumentException('Mongodb Where Op key Is Exists[' . $column . $operator . ']'); } } switch ($operator) { case 'IN': // no break case 'NOT IN': empty($value) && $value = [0]; //这边可直接跳过不组装sql,但是为了给用户提示无条件 便于调试还是加上where field in(0) if ($this->opIsAnd) { $this->sql['where'][$column][$operator == 'IN' ? '$in' : '$nin'] = $value; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column][$operator == 'IN' ? '$in' : '$nin'] = $value; } else { $this->sql['where']['$or'][][$column] = $operator == 'IN' ? ['$in' => $value] : ['$nin' => $value]; } break; case 'BETWEEN': if ($this->opIsAnd) { $this->sql['where'][$column]['$gt'] = $value[0]; $this->sql['where'][$column]['$lt'] = $value[1]; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$gt'] = $value[0]; $this->sql['where']['$or'][$currentOrIndex][$column]['$lt'] = $value[1]; } else { $this->sql['where']['$or'][][$column] = ['$gt' => $value[0], '$lt' => $value[1]]; } break; case 'NOT BETWEEN': if ($this->opIsAnd) { $this->sql['where'][$column]['$lt'] = $value[0]; $this->sql['where'][$column]['$gt'] = $value[1]; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$lt'] = $value[0]; $this->sql['where']['$or'][$currentOrIndex][$column]['$gt'] = $value[1]; } else { $this->sql['where']['$or'][][$column] = ['$lt' => $value[0], '$gt' => $value[1]]; } break; case 'IS NULL': if ($this->opIsAnd) { $this->sql['where'][$column]['$in'] = [null]; $this->sql['where'][$column]['$exists'] = true; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$in'] = [null]; $this->sql['where']['$or'][$currentOrIndex][$column]['$exists'] = true; } else { $this->sql['where']['$or'][][$column] = ['$in' => [null], '$exists' => true]; } break; case 'IS NOT NULL': if ($this->opIsAnd) { $this->sql['where'][$column]['$ne'] = null; $this->sql['where'][$column]['$exists'] = true; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$ne'] = null; $this->sql['where']['$or'][$currentOrIndex][$column]['$exists'] = true; } else { $this->sql['where']['$or'][][$column] = ['$ne' => null, '$exists' => true]; } break; case '>': //no break; case '<': if ($this->opIsAnd) { $this->sql['where'][$column][$operator == '>' ? '$gt' : '$lt'] = $value; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column][$operator == '>' ? '$gt' : '$lt'] = $value; } else { $this->sql['where']['$or'][][$column] = $operator == '>' ? ['$gt' => $value] : ['$lt' => $value]; } break; case '>=': //no break; case '<=': if ($this->opIsAnd) { $this->sql['where'][$column][$operator == '>=' ? '$gte' : '$lte'] = $value; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column][$operator == '>=' ? '$gte' : '$lte'] = $value; } else { $this->sql['where']['$or'][][$column] = $operator == '>=' ? ['$gte' => $value] : ['$lte' => $value]; } break; case 'NOT LIKE': if ($this->opIsAnd) { $this->sql['where'][$column]['$not'] = new Regex($value, 'i'); } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$not'] = new Regex($value, 'i'); } else { $this->sql['where']['$or'][][$column] = ['$not' => new Regex($value, 'i')]; } break; case 'LIKE': //no break; case 'REGEXP': if ($this->opIsAnd) { $this->sql['where'][$column]['$regex'] = $value; $this->sql['where'][$column]['$options'] = '$i'; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$regex'] = $value; $this->sql['where']['$or'][$currentOrIndex][$column]['$options'] = '$i'; } else { $this->sql['where']['$or'][][$column] = ['$regex' => $value, '$options' => '$i']; } break; case '!=': if ($this->opIsAnd) { $this->sql['where'][$column]['$ne'] = $value; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column]['$ne'] = $value; } else { $this->sql['where']['$or'][][$column] = ['$ne' => $value]; } break; case '=': if ($this->opIsAnd) { $this->sql['where'][$column] = $value; } else if ($this->bracketsIsOpen) { $this->sql['where']['$or'][$currentOrIndex][$column] = $value; } else { $this->sql['where']['$or'][][$column] = $value; } break; case 'column': $this->sql['where']['$where'] = "this.{$column} = this.{$value}"; break; case 'raw': $this->sql['where']['$where'] = $column; break; } return $this; }
where 语句组装工厂 @param string $column 如 id user.id (这边的user为表别名如表pre_user as user 这边用user而非带前缀的原表名) @param array|int|string $value 值 @param string $operator 操作符 @throws \Exception @return $this
entailment
public function whereNotLike($column, $leftBlur = false, $value, $rightBlur = false) { $this->conditionFactory( $column, ($leftBlur ? '' : '^') . preg_quote($this->filterLike($value)) . ($rightBlur ? '' : '$'), 'NOT LIKE' ); return $this; }
where条件组装 LIKE @param string $column 如 id user.id (这边的user为表别名如表pre_user as user 这边用user而非带前缀的原表名) @param bool $leftBlur 是否开始左模糊匹配 @param string |int $value @param bool $rightBlur 是否开始右模糊匹配 @return $this
entailment
public function columns($columns = '*') { if (false === is_array($columns) && $columns != '*') { $columns = func_get_args(); } foreach ($columns as $column) { $this->sql['columns'][$column] = 1; } return $this; }
选择列 @param string|array $columns 默认选取所有 ['id, 'name'] 选取id,name两列 @return $this
entailment
public function _and(callable $callable = null) { $history = $this->opIsAnd; $this->opIsAnd = true; if (is_callable($callable)) { $this->lBrackets(); $callable(); $this->rBrackets(); $this->opIsAnd = $history; } return $this; }
设置后面的where以and连接 @param callable $callable 如果传入函数则函数内执行的条件会被()包围 @return $this
entailment
public function _or(callable $callable = null) { $history = $this->opIsAnd; $this->opIsAnd = false; if (is_callable($callable)) { $this->lBrackets(); $callable(); $this->rBrackets(); $this->opIsAnd = $history; } return $this; }
设置后面的where以or连接 @param callable $callable mongodb中元首 @return $this
entailment
public function limit($offset = 0, $limit = 10) { $limit < 1 && $limit = 100; $this->sql['limit'] = [$offset, $limit]; return $this; }
LIMIT @param int $offset 偏移量 @param int $limit 返回的条数 @return $this
entailment
public function count($field = '*', $isMulti = false, $useMaster = false) { $cmd = [ 'count' => $this->getRealTableName(key($this->table)), 'query' => $this->sql['where'] ]; $count = $this->runMongoCommand($cmd, $useMaster); return intval($count[0]['n']); }
获取count(字段名或*)的结果 @param string $field Mongo中此选项无效 @param bool $isMulti Mongo中此选项无效 @param bool|string $useMaster 是否使用主库 默认读取从库 @return mixed
entailment
public function min($field = 'id', $isMulti = false, $useMaster = false) { return $this->aggregation($field, $isMulti, '$min', $useMaster); }
获取 $min 的结果 @param string $field 要统计的字段名 @param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时此参数为要$group的字段 @param bool|string $useMaster 是否使用主库 默认读取从库 @return mixed
entailment
public function sum($field = 'id', $isMulti = false, $useMaster = false) { return $this->aggregation($field, $isMulti, '$sum', $useMaster); }
获取 $sum的结果 @param string $field 要统计的字段名 @param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时此参数为要$group的字段 @param bool|string $useMaster 是否使用主库 默认读取从库 @return mixed
entailment
public function avg($field = 'id', $isMulti = false, $useMaster = false) { return $this->aggregation($field, $isMulti, '$avg', $useMaster); }
获取 $avg 的结果 @param string $field 要统计的字段名 @param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时此参数为要$group的字段 @param bool|string $useMaster 是否使用主库 默认读取从库 @return mixed
entailment
private function aggregation($field, $isMulti = false, $operation = '$max', $useMaster = false) { $pipe = []; empty($this->sql['where']) || $pipe[] = [ '$match' => $this->sql['where'] ]; $pipe[] = [ '$group' => [ '_id' => $isMulti ? '$' . $isMulti : '0', 'count' => [$operation => '$' . $field] ] ]; $res = $this->mongoDbAggregate($pipe, [], $useMaster); if ($isMulti === false) { return $res[0]['count']; } else { return $res; } }
获取聚合的结果 @param string $field 要统计的字段名 @param bool|string $isMulti 结果集是否为多条 默认只有一条。传字符串时此参数为要$group的字段 @param string $operation 聚合操作 @param bool|string $useMaster 是否使用主库 默认读取从库 @return mixed
entailment
public function mongoDbDistinct($field = '') { $cmd = [ 'distinct' => $this->getRealTableName(key($this->table)), 'key' => $field, 'query' => $this->sql['where'] ]; $data = $this->runMongoCommand($cmd, false); return $data[0]['values']; }
MongoDb的distinct封装 @param string $field 指定不重复的字段值 @return mixed
entailment
public function mongoDbAggregate($pipeline = [], $options = [], $useMaster = false) { $cmd = $options + [ 'aggregate' => $this->getRealTableName(key($this->table)), 'pipeline' => $pipeline ]; $data = $this->runMongoCommand($cmd, $useMaster); return $data[0]['result']; }
MongoDb的aggregate封装 @param array $pipeline List of pipeline operations @param array $options Command options @param bool|string $useMaster 是否使用主库 默认读取从库 @return mixed
entailment
public function getMongoDbAutoIncKey($collection = 'mongoinckeycol', $table = 'post') { $res = $this->runMongoCommand([ 'findandmodify' => $collection, 'update' => [ '$inc' => ['id' => 1] ], 'query' => [ 'table' => $table ], 'new' => true ]); return intval($res[0]['value']['id']); }
获取自增id-需要先初始化数据 如: db.mongoinckeycol.insert({id:0, 'table' : 'post'}) 即初始化帖子表(post)自增初始值为0 @param string $collection 存储自增的collection名 @param string $table 表的名称 @return int
entailment
public function buildSql($offset = null, $limit = null, $isSelect = false) { $this->logNotSupportMethod(__METHOD__); return $this; }
构建sql @param null $offset 偏移量 @param null $limit 返回的条数 @param bool $isSelect 是否为select调用, 是则不重置查询参数并返回cacheKey/否则直接返回sql并重置查询参数 @return string|array
entailment
public function select($offset = null, $limit = null, $useMaster = false) { is_null($offset) || $this->limit($offset, $limit); $filter = []; count($this->sql['orderBy']) > 0 && $filter['sort'] = $this->sql['orderBy']; count($this->sql['columns']) > 0 && $filter['projection'] = $this->sql['columns']; isset($this->sql['limit'][0]) && $filter['skip'] = $this->sql['limit'][0]; isset($this->sql['limit'][1]) && $filter['limit'] = $this->sql['limit'][1]; return $this->runMongoQuery( $this->getRealTableName(key($this->table)), $this->sql['where'], $filter, $useMaster ); }
获取多条数据 @param int $offset 偏移量 @param int $limit 返回的条数 @param bool $useMaster 是否使用主库 默认读取从库 @return array
entailment
public function affectedRows($handle, $type) { switch ($type) { case 1: return $handle->getInsertedCount(); break; case 2: return $handle->getModifiedCount(); break; case 3: return $handle->getDeletedCount(); break; default: return false; } }
返回INSERT,UPDATE 或 DELETE 查询所影响的记录行数 @param \MongoDB\Driver\WriteResult $handle @param int $type 执行的类型1:insert、2:update、3:delete @return int
entailment
protected function connectDb($db, $reConnect = false) { if ($db == 'rlink') { //如果没有指定从数据库,则使用 master if (!isset($this->conf['slaves']) || empty($this->conf['slaves'])) { $this->rlink = $this->wlink; return $this->rlink; } $n = mt_rand(0, count($this->conf['slaves']) - 1); $conf = $this->conf['slaves'][$n]; $this->rlink = $this->connect( $conf['host'], $conf['username'], $conf['password'], $conf['dbname'], isset($conf['replicaSet']) ? $conf['replicaSet'] : '' ); return $this->rlink; } elseif ($db == 'wlink') { $conf = $this->conf['master']; $this->wlink = $this->connect( $conf['host'], $conf['username'], $conf['password'], $conf['dbname'], isset($conf['replicaSet']) ? $conf['replicaSet'] : '' ); return $this->wlink; } return false; }
连接数据库 @param string $db rlink/wlink @param bool $reConnect 是否重连--用于某些db如mysql.长连接被服务端断开的情况 @return bool|false|mixed|resource
entailment
public function connect($host, $username, $password, $dbName, $replicaSet = '', $engine = '', $pConnect = false) { $authString = ""; if ($username && $password) { $authString = "{$username}:{$password}@"; } $replicaSet && $replicaSet = '?replicaSet=' . $replicaSet; $dsn = "mongodb://{$authString}{$host}/{$dbName}{$replicaSet}"; return new Manager($dsn); }
Db连接 @param string $host 数据库host @param string $username 数据库用户名 @param string $password 数据库密码 @param string $dbName 数据库名 @param string $replicaSet replicaSet名称 @param string $engine 无用 @param bool $pConnect 无用 @return mixed
entailment
public function increment($key, $val = 1, $field = null, $tablePrefix = null) { list($tableName, $condition) = $this->parseKey($key, true); if (is_null($field) || empty($tableName) || empty($condition)) { return false; } $val = abs(intval($val)); is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; $tableName = $tablePrefix . $tableName; $bulk = new BulkWrite(); $bulk->update($condition, ['$inc' => [$field => $val]], ['multi' => true]); $result = $this->runMongoBulkWrite($tableName, $bulk); Cml::$debug && $this->debugLogSql('BulkWrite INC', $tableName, $condition, ['$inc' => [$field => $val]]); return $result->getModifiedCount(); }
指定字段的值+1 @param string $key 操作的key user-id-1 @param int $val @param string $field 要改变的字段 @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @return bool
entailment
public function version($link = null) { $cursor = $this->getMaster()->executeCommand( $this->getDbName(), new Command(['buildInfo' => 1]) ); $cursor->setTypeMap(['root' => 'array', 'document' => 'array']); $info = current($cursor->toArray()); return $info['version']; }
获取mysql 版本 @param \PDO $link @return string
entailment
public function serverSupportFeature($version = 3) { $info = $this->getSlave()->selectServer(new ReadPreference(ReadPreference::RP_PRIMARY))->getInfo(); $maxWireVersion = isset($info['maxWireVersion']) ? (integer)$info['maxWireVersion'] : 0; $minWireVersion = isset($info['minWireVersion']) ? (integer)$info['minWireVersion'] : 0; return ($minWireVersion <= $version && $maxWireVersion >= $version); }
判断当前mongod服务是否支持某个版本的特性 @param int $version 要判断的版本 @return bool
entailment
public function atomAt($index) { $atom = $this->atomAtDefault($index); if (null === $atom) { throw new Exception\UndefinedAtomException($index); } return $atom; }
Get a single path atom by index. @param integer $index The index to search for. @return string The path atom. @throws Exception\UndefinedAtomException If the index does not exist in this path's atoms.
entailment
public function atomAtDefault($index, $default = null) { $atoms = $this->atoms(); if ($index < 0) { $index = count($atoms) + $index; } if (array_key_exists($index, $atoms)) { return $atoms[$index]; } return $default; }
Get a single path atom by index, falling back to a default if the index is undefined. @param integer $index The index to search for. @param mixed $default The default value to return if no atom is defined for the supplied index. @return mixed The path atom, or $default if no atom is defined for the supplied index.
entailment
public function sliceAtoms($index, $length = null) { $atoms = $this->atoms(); if (null === $length) { $length = count($atoms); } return array_slice($atoms, $index, $length); }
Get a subset of the atoms of this path. @param integer $index The index of the first atom. @param integer|null $length The maximum number of atoms. @return array<integer,string> An array of strings representing the subset of path atoms.
entailment
public function name() { $atoms = $this->atoms(); $numAtoms = count($atoms); if ($numAtoms > 0) { return $atoms[$numAtoms - 1]; } return ''; }
Get this path's name. @return string The last path atom if one exists, otherwise an empty string.
entailment
public function nameAtomAt($index) { $atom = $this->nameAtomAtDefault($index); if (null === $atom) { throw new Exception\UndefinedAtomException($index); } return $atom; }
Get a single path name atom by index. @param integer $index The index to search for. @return string The path name atom. @throws Exception\UndefinedAtomException If the index does not exist in this path's name atoms.
entailment
public function nameAtomAtDefault($index, $default = null) { $atoms = $this->nameAtoms(); if ($index < 0) { $index = count($atoms) + $index; } if (array_key_exists($index, $atoms)) { return $atoms[$index]; } return $default; }
Get a single path name atom by index, falling back to a default if the index is undefined. @param integer $index The index to search for. @param mixed $default The default value to return if no atom is defined for the supplied index. @return mixed The path name atom, or $default if no atom is defined for the supplied index.
entailment
public function sliceNameAtoms($index, $length = null) { $atoms = $this->nameAtoms(); if (null === $length) { $length = count($atoms); } return array_slice($atoms, $index, $length); }
Get a subset of this path's name atoms. @param integer $index The index of the first atom. @param integer|null $length The maximum number of atoms. @return array<integer,string> An array of strings representing the subset of path name atoms.
entailment
public function nameWithoutExtension() { $atoms = $this->nameAtoms(); if (count($atoms) > 1) { array_pop($atoms); return implode(static::EXTENSION_SEPARATOR, $atoms); } return $atoms[0]; }
Get this path's name, excluding the last extension. @return string The last atom of this path, excluding the last extension. If this path has no atoms, an empty string is returned.
entailment
public function nameSuffix() { $atoms = $this->nameAtoms(); if (count($atoms) > 1) { array_shift($atoms); return implode(static::EXTENSION_SEPARATOR, $atoms); } return null; }
Get all of this path's extensions. @return string|null The extensions of this path's last atom. If the last atom has no extensions, or this path has no atoms, this method will return null.
entailment
public function extension() { $atoms = $this->nameAtoms(); $numParts = count($atoms); if ($numParts > 1) { return $atoms[$numParts - 1]; } return null; }
Get this path's last extension. @return string|null The last extension of this path's last atom. If the last atom has no extensions, or this path has no atoms, this method will return null.
entailment
public function contains($needle, $caseSensitive = null) { if ('' === $needle) { return true; } if (null === $caseSensitive) { $caseSensitive = false; } if ($caseSensitive) { return false !== mb_strpos($this->string(), $needle); } return false !== mb_stripos($this->string(), $needle); }
Determine if this path contains a substring. @param string $needle The substring to search for. @param boolean|null $caseSensitive True if case sensitive. @return boolean True if this path contains the substring.
entailment
public function endsWith($needle, $caseSensitive = null) { if ('' === $needle) { return true; } if (null === $caseSensitive) { $caseSensitive = false; } $end = mb_substr($this->string(), -mb_strlen($needle)); if ($caseSensitive) { return $end === $needle; } return mb_strtolower($end) === mb_strtolower($needle); }
Determine if this path ends with a substring. @param string $needle The substring to search for. @param boolean|null $caseSensitive True if case sensitive. @return boolean True if this path ends with the substring.
entailment
public function matches($pattern, $caseSensitive = null, $flags = null) { if (null === $caseSensitive) { $caseSensitive = false; } if (null === $flags) { $flags = 0; } if (!$caseSensitive) { $flags = $flags | FNM_CASEFOLD; } return fnmatch($pattern, $this->string(), $flags); }
Determine if this path matches a wildcard pattern. @param string $pattern The pattern to check against. @param boolean|null $caseSensitive True if case sensitive. @param integer|null $flags Additional flags. @return boolean True if this path matches the pattern.
entailment
public function matchesRegex( $pattern, array &$matches = null, $flags = null, $offset = null ) { if (null === $flags) { $flags = 0; } if (null === $offset) { $offset = 0; } return 1 === preg_match( $pattern, $this->string(), $matches, $flags, $offset ); }
Determine if this path matches a regular expression. @param string $pattern The pattern to check against. @param array|null &$matches Populated with the pattern matches. @param integer|null $flags Additional flags. @param integer|null $offset Start searching from this byte offset. @return boolean True if this path matches the pattern.
entailment
public function nameContains($needle, $caseSensitive = null) { if ('' === $needle) { return true; } if (null === $caseSensitive) { $caseSensitive = false; } if ($caseSensitive) { return false !== mb_strpos($this->name(), $needle); } return false !== mb_stripos($this->name(), $needle); }
Determine if this path's name contains a substring. @param string $needle The substring to search for. @param boolean|null $caseSensitive True if case sensitive. @return boolean True if this path's name contains the substring.
entailment
public function nameMatches($pattern, $caseSensitive = null, $flags = null) { if (null === $caseSensitive) { $caseSensitive = false; } if (null === $flags) { $flags = 0; } if (!$caseSensitive) { $flags = $flags | FNM_CASEFOLD; } return fnmatch($pattern, $this->name(), $flags); }
Determine if this path's name matches a wildcard pattern. @param string $pattern The pattern to check against. @param boolean|null $caseSensitive True if case sensitive. @param integer|null $flags Additional flags. @return boolean True if this path's name matches the pattern.
entailment
public function nameMatchesRegex( $pattern, array &$matches = null, $flags = null, $offset = null ) { if (null === $flags) { $flags = 0; } if (null === $offset) { $offset = 0; } return 1 === preg_match( $pattern, $this->name(), $matches, $flags, $offset ); }
Determine if this path's name matches a regular expression. @param string $pattern The pattern to check against. @param array|null &$matches Populated with the pattern matches. @param integer|null $flags Additional flags. @param integer|null $offset Start searching from this byte offset. @return boolean True if this path's name matches the pattern.
entailment
public function parent($numLevels = null) { if (null === $numLevels) { $numLevels = 1; } return $this->createPath( array_merge( $this->atoms(), array_fill(0, $numLevels, static::PARENT_ATOM) ), $this instanceof AbsolutePathInterface, false ); }
Get the parent of this path a specified number of levels up. @param integer|null $numLevels The number of levels up. Defaults to 1. @return PathInterface The parent of this path $numLevels up.
entailment
public function stripTrailingSlash() { if (!$this->hasTrailingSeparator()) { return $this; } return $this->createPath( $this->atoms(), $this instanceof AbsolutePathInterface, false ); }
Strips the trailing slash from this path. @return PathInterface A new path instance with the trailing slash removed from this path. If this path has no trailing slash, the path is returned unmodified.
entailment
public function joinAtomSequence($atoms) { if (!is_array($atoms)) { $atoms = iterator_to_array($atoms); } return $this->createPath( array_merge($this->atoms(), $atoms), $this instanceof AbsolutePathInterface, false ); }
Joins a sequence of atoms to this path. @param mixed<string> $atoms The path atoms to append. @return PathInterface A new path with the supplied sequence of atoms suffixed to this path. @throws Exception\InvalidPathAtomExceptionInterface If any joined atoms are invalid.
entailment
public function joinTrailingSlash() { if ($this->hasTrailingSeparator()) { return $this; } return $this->createPath( $this->atoms(), $this instanceof AbsolutePathInterface, true ); }
Adds a trailing slash to this path. @return PathInterface A new path instance with a trailing slash suffixed to this path.
entailment
public function joinExtensionSequence($extensions) { if (!is_array($extensions)) { $extensions = iterator_to_array($extensions); } $atoms = $this->nameAtoms(); if (array('', '') === $atoms) { array_pop($atoms); } return $this->replaceName( implode( static::EXTENSION_SEPARATOR, array_merge($atoms, $extensions) ) ); }
Joins a sequence of extensions to this path. @param mixed<string> $extensions The extensions to append. @return PathInterface A new path instance with the supplied extensions suffixed to this path. @throws Exception\InvalidPathAtomExceptionInterface If the suffixed extensions cause the atom to be invalid.
entailment
public function suffixName($suffix) { $name = $this->name(); if (static::SELF_ATOM === $name) { return $this->replaceName($suffix); } return $this->replaceName($name . $suffix); }
Suffixes this path's name with a supplied string. @param string $suffix The string to suffix to the path name. @return PathInterface A new path instance with the supplied string suffixed to the last path atom. @throws Exception\InvalidPathAtomExceptionInterface If the suffix causes the atom to be invalid.
entailment
public function prefixName($prefix) { $name = $this->name(); if (static::SELF_ATOM === $name) { return $this->replaceName($prefix); } return $this->replaceName($prefix . $name); }
Prefixes this path's name with a supplied string. @param string $prefix The string to prefix to the path name. @return PathInterface A new path instance with the supplied string prefixed to the last path atom. @throws Exception\InvalidPathAtomExceptionInterface If the prefix causes the atom to be invalid.
entailment
public function replace($index, $replacement, $length = null) { $atoms = $this->atoms(); if (!is_array($replacement)) { $replacement = iterator_to_array($replacement); } if (null === $length) { $length = count($atoms); } array_splice($atoms, $index, $length, $replacement); return $this->createPath( $atoms, $this instanceof AbsolutePathInterface, false ); }
Replace a section of this path with the supplied atom sequence. @param integer $index The start index of the replacement. @param mixed<string> $replacement The replacement atom sequence. @param integer|null $length The number of atoms to replace. If $length is null, the entire remainder of the path will be replaced. @return PathInterface A new path instance that has a portion of this path's atoms replaced with a different sequence of atoms.
entailment
public function replaceName($name) { $atoms = $this->atoms(); $numAtoms = count($atoms); if ($numAtoms > 0) { if ('' === $name) { array_pop($atoms); } else { $atoms[$numAtoms - 1] = $name; } } elseif ('' !== $name) { $atoms[] = $name; } return $this->createPath( $atoms, $this instanceof AbsolutePathInterface, false ); }
Replace this path's name. @param string $name The new path name. @return PathInterface A new path instance with the supplied name replacing the existing one.
entailment
public function replaceNameWithoutExtension($nameWithoutExtension) { $atoms = $this->nameAtoms(); if (count($atoms) < 2) { return $this->replaceName($nameWithoutExtension); } array_splice($atoms, 0, -1, array($nameWithoutExtension)); return $this->replaceName(implode(self::EXTENSION_SEPARATOR, $atoms)); }
Replace this path's name, but keep the last extension. @param string $nameWithoutExtension The replacement string. @return PathInterface A new path instance with the supplied name replacing the portion of the existing name preceding the last extension.
entailment
public function replaceNameSuffix($nameSuffix) { $atoms = $this->nameAtoms(); if (array('', '') === $atoms) { if (null === $nameSuffix) { return $this; } return $this->replaceName( static::EXTENSION_SEPARATOR . $nameSuffix ); } $numAtoms = count($atoms); if (null === $nameSuffix) { $replacement = array(); } else { $replacement = array($nameSuffix); } array_splice($atoms, 1, count($atoms), $replacement); return $this->replaceName(implode(self::EXTENSION_SEPARATOR, $atoms)); }
Replace all of this path's extensions. @param string|null $nameSuffix The replacement string, or null to remove all extensions. @return PathInterface A new path instance with the supplied name suffix replacing the existing one.
entailment
public function replaceExtension($extension) { $atoms = $this->nameAtoms(); if (array('', '') === $atoms) { if (null === $extension) { return $this; } return $this->replaceName( static::EXTENSION_SEPARATOR . $extension ); } $numAtoms = count($atoms); if ($numAtoms > 1) { if (null === $extension) { $replacement = array(); } else { $replacement = array($extension); } array_splice($atoms, -1, $numAtoms, $replacement); } elseif (null !== $extension) { $atoms[] = $extension; } return $this->replaceName(implode(self::EXTENSION_SEPARATOR, $atoms)); }
Replace this path's last extension. @param string|null $extension The replacement string, or null to remove the last extension. @return PathInterface A new path instance with the supplied extension replacing the existing one.
entailment
public function replaceNameAtoms($index, $replacement, $length = null) { $atoms = $this->nameAtoms(); if (!is_array($replacement)) { $replacement = iterator_to_array($replacement); } if (null === $length) { $length = count($atoms); } array_splice($atoms, $index, $length, $replacement); return $this->replaceName(implode(self::EXTENSION_SEPARATOR, $atoms)); }
Replace a section of this path's name with the supplied name atom sequence. @param integer $index The start index of the replacement. @param mixed<string> $replacement The replacement name atom sequence. @param integer|null $length The number of atoms to replace. If $length is null, the entire remainder of the path name will be replaced. @return PathInterface A new path instance that has a portion of this name's atoms replaced with a different sequence of atoms.
entailment
protected function normalizeAtoms($atoms) { $normalizedAtoms = array(); foreach ($atoms as $atom) { $this->validateAtom($atom); $normalizedAtoms[] = $atom; } return $normalizedAtoms; }
Normalizes and validates a sequence of path atoms. This method is called internally by the constructor upon instantiation. It can be overridden in child classes to change how path atoms are normalized and/or validated. @param mixed<string> $atoms The path atoms to normalize. @return array<string> The normalized path atoms. @throws Exception\EmptyPathAtomException If any path atom is empty. @throws Exception\PathAtomContainsSeparatorException If any path atom contains a separator.
entailment
protected function validateAtom($atom) { if ('' === $atom) { throw new Exception\EmptyPathAtomException; } elseif (false !== strpos($atom, static::ATOM_SEPARATOR)) { throw new Exception\PathAtomContainsSeparatorException($atom); } }
Validates a single path atom. This method is called internally by the constructor upon instantiation. It can be overridden in child classes to change how path atoms are validated. @param string $atom The atom to validate. @throws Exception\InvalidPathAtomExceptionInterface If an invalid path atom is encountered.
entailment
protected function createPath( $atoms, $isAbsolute, $hasTrailingSeparator = null ) { return static::factory()->createFromAtoms( $atoms, $isAbsolute, $hasTrailingSeparator ); }
Creates a new path instance of the most appropriate type. This method is called internally every time a new path instance is created as part of another method call. It can be overridden in child classes to change which classes are used when creating new path instances. @param mixed<string> $atoms The path atoms. @param boolean $isAbsolute True if the new path should be absolute. @param boolean|null $hasTrailingSeparator True if the new path should have a trailing separator. @return PathInterface The newly created path instance.
entailment
public function pathFactory() { if (null === $this->pathFactory) { $this->pathFactory = $this->createDefaultPathFactory(); } return $this->pathFactory; }
Get the path factory. @return PathFactoryInterface The path factory.
entailment
public static function fromAtoms( $atoms, $isAbsolute = null, $hasTrailingSeparator = null ) { return static::factory()->createFromAtoms( $atoms, $isAbsolute, $hasTrailingSeparator ); }
Creates a new path instance from a set of path atoms. @param mixed<string> $atoms The path atoms. @param boolean|null $isAbsolute True if the path is absolute. @param boolean|null $hasTrailingSeparator True if the path has a trailing separator. @return PathInterface The newly created path instance. @throws Exception\InvalidPathAtomExceptionInterface If any of the supplied atoms are invalid.
entailment
public function createFromAtoms( $atoms, $isAbsolute = null, $hasTrailingSeparator = null ) { if (null === $isAbsolute) { $isAbsolute = false; } if ($isAbsolute) { return new AbsoluteUnixPath($atoms, $hasTrailingSeparator); } return new RelativeUnixPath($atoms, $hasTrailingSeparator); }
Creates a new path instance from a set of path atoms. @param mixed<string> $atoms The path atoms. @param boolean|null $isAbsolute True if the path is absolute. @param boolean|null $hasTrailingSeparator True if the path has a trailing separator. @return PathInterface The newly created path instance. @throws InvalidPathAtomExceptionInterface If any of the supplied atoms are invalid. @throws InvalidPathStateException If the supplied arguments would produce an invalid path.
entailment
public static function setConfig($config = []) { if (!is_array($config)) { return false; } self::$config = array_merge(self::$config, $config); return true; }
修改配置 @param array $config ['pid'=>'', 'id' => '', 'name' =>'name'] @return mixed
entailment
public static function getTree( $list, $pid = 0, $selectedId = 0, $str = "<option value='\$id' \$selected>\$tempPrefix\$name</option>", $prefix = '|--', $selectedString = 'selected', $returnType = 1 ) { $string = $returnType === 1 ? '' : []; if (!is_array($list)) { //遍历结束 self::$times = 0; return $string; } $tempPrefix = ''; self::$times += 1; for ($i = 0; $i < self::$times; $i++) { $tempPrefix .= is_array($prefix) ? ($i + 1 == self::$times ? $prefix[1] : $prefix[0]) : $prefix; } foreach ($list as $v) { if ($v[self::$config['pid']] == $pid) { //获取pid下的子集 $id = $v[self::$config['id']]; //主键id $name = $v[self::$config['name']]; //显示的名称 $selected = ($id == $selectedId) ? $selectedString : ''; //被选中的id $tempCode = ''; eval("\$tempCode = \"{$str}\";");//转化 if ($returnType === 1) { $string .= $tempCode; $string .= self::getTree($list, $id, $selectedId, $str, $prefix, $selectedString, $returnType); } else { $string[$id] = $tempCode; $sub = self::getTree($list, $id, $selectedId, $str, $prefix, $selectedString, $returnType); $sub && $string = $string + $sub; } } } self::$times--; return $string; }
获取树--返回格式化后的数据 @param array $list 数据列表数组 @param int $pid 初始化树时候,代表获取pid下的所有子集 @param int $selectedId 选中的ID值 @param string $str 组装后的字串 @param string|array $prefix 前缀 如:|--表示每一层都会以|--分隔、[' ', '|--']表示只有最后一层是用|--其余层级用空格缩进 @param string $selectedString 选中时的字串 如selected checked @param int $returnType 1为返回字符串 2为返回数组 @return string|array
entailment
public static function getTreeNoFormat(&$list, $pid = 0, $sonNodeName = 'sonNode') { $res = []; if (!is_array($list)) { //遍历结束 return $res; } foreach ($list as $v) { if (isset($v[self::$config['pid']]) && $v[self::$config['pid']] == $pid) { //获取pid下的子集 $v[$sonNodeName] = self::getTreeNoFormat($list, $v[self::$config['id']], $sonNodeName); $res[$v[self::$config['id']]] = $v; } } return $res; }
获取树--返回数组 @param array $list 数据列表数组 @param int $pid 初始化树时候,代表获取pid下的所有子集 @param string $sonNodeName 子级的key @return string|array
entailment
public static function getChild($list, $id) { if (!is_array($list)) return []; $temp = []; foreach ($list as $v) { if ($v[self::$config['pid']] == $id) { $temp[] = $v; } } return $temp; }
获取子集 @param array $list 树的数组 @param int $id 父类ID @return string|array
entailment
public static function getParent($list, $id) { if (!is_array($list)) return []; $temp = []; foreach ($list as $v) { $temp[$v[self::$config['id']]] = $v; } $parentid = $temp[$id][self::$config['pid']]; return $temp[$parentid]; }
获取父集 @param array $list 树的数组 @param int $id 子集ID @return string|array
entailment
public function getlocation($ip = '') { $obj = new Ip2Region(); $res = $obj->btreeSearch($ip); $res = explode('|', $res['region']); return [ 'ip' => $ip, 'country' => $res[2].$res[3], 'area' => $res[4] ]; }
根据所给 IP 地址或域名返回所在地区信息 @param string $ip @return array
entailment
public static function get_client_ip($type = 0) { $ip = Request::ip(); // IP地址合法验证 $long = sprintf("%u", ip2long($ip)); $ip = $long ? [$ip, $long] : ['0.0.0.0', 0]; return $ip[$type]; }
获取客户端IP地址 @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 @return mixed
entailment
public function table($table = '', $tablePrefix = null) { $hasAlias = is_array($table) ? true : false; is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; $tableName = $tablePrefix . ($hasAlias ? key($table) : $table); $this->table[count($this->table) . '_' . $tableName] = $hasAlias ? current($table) : null; return $this; }
定义操作的表 @param string|array $table 表名 要取别名时使用 [不带前缀表名 => 别名] @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀 @return $this
entailment
protected function connectDb($db, $reConnect = false) { if ($db == 'rlink') { //如果没有指定从数据库,则使用 master if (empty($this->conf['slaves'])) { self::$dbInst[$db] = $this->rlink = $reConnect ? $this->connectDb('wlink', true) : $this->wlink; return $this->rlink; } $n = mt_rand(0, count($this->conf['slaves']) - 1); $conf = $this->conf['slaves'][$n]; empty($conf['engine']) && $conf['engine'] = ''; self::$dbInst[$db] = $this->rlink = $this->connect( $conf['host'], $conf['username'], $conf['password'], $conf['dbname'], $conf['charset'], $conf['engine'], $conf['pconnect'] ); return $this->rlink; } elseif ($db == 'wlink') { $conf = $this->conf['master']; empty($conf['engine']) && $conf['engine'] = ''; self::$dbInst[$db] = $this->wlink = $this->connect( $conf['host'], $conf['username'], $conf['password'], $conf['dbname'], $conf['charset'], $conf['engine'], $conf['pconnect'] ); return $this->wlink; } return false; }
连接数据库 @param string $db rlink/wlink @param bool $reConnect 是否重连--用于某些db如mysql.长连接被服务端断开的情况 @return bool|false|mixed|resource
entailment
public function paginate($limit, $useMaster = false, $page = null) { is_int($page) || $page = Input::requestInt(Config::get('var_page'), 1); $page < 1 && $page = 1; return call_user_func_array([$this, 'select'], [($page - 1) * $limit, $limit, $useMaster]); }
分页获取数据 @param int $limit 每页返回的条数 @param bool $useMaster 是否使用主库 默认读取从库 @param null|int $page 当前页数-不传则获取配置中var_page配置的request值 @return array
entailment
public function getPk($table, $tablePrefix = null) { $rows = $this->getDbFields($table, $tablePrefix); foreach ($rows as $val) { if ($val['primary']) { return $val['name']; } } return false; }
获取表主键 @param string $table 要获取主键的表名 @param string $tablePrefix 表前缀,不传则获取配置中配置的前缀 @return string || false
entailment
public function getOne($useMaster = false) { $result = $this->select(0, 1, $useMaster); if (isset($result[0])) { return $result[0]; } else { return false; } }
获取一条数据 @param bool $useMaster 是否使用主库 默认读取从库 @return array | bool
entailment
public function getOneValue($column, $useMaster = false) { $this->sql['columns'] == '' && $this->columns($column); $data = $this->getOne($useMaster); return isset($data[$column]) ? $data[$column] : false; }
获取一列 @param string $column 列名 @param bool $useMaster 是否使用主库 默认读取从库 @return bool|mixed
entailment
public function plunk($column, $key = null, $limit = null, $useMaster = false) { $this->sql['columns'] == '' && $this->columns(is_null($key) ? $column : [$key, $column]); $result = $this->select(0, $limit, $useMaster); $return = []; foreach ($result as $row) { is_null($key) ? $return[] = $row[$column] : $return[$row[$key]] = $row[$column]; } return $return; }
获取数据列值列表 @param string $column 列名 @param null $key 返回数组中为列值指定自定义键(该自定义键必须是该表的其它字段列名) @param int $limit 返回的条数 @param bool $useMaster 是否使用主库 默认读取从库 @return array
entailment
public function chunk($num = 100, callable $func) { $this->paramsAutoReset(); $start = 0; $backComdition = $this->sql;//sql组装 $backTable = $this->table;//操作的表 $backJoin = $this->join;//是否内联 $backleftJoin = $this->leftJoin;//是否左联结 $backrightJoin = $this->rightJoin;//是否右联 $backBindParams = $this->bindParams; while ($result = $this->select($start, $num)) { if ($func($result) === false) { break; } $start += count($result); $this->sql = $backComdition;//sql组装 $this->table = $backTable;//操作的表 $this->join = $backJoin;//是否内联 $this->leftJoin = $backleftJoin;//是否左联结 $this->rightJoin = $backrightJoin;//是否右联 $this->bindParams = $backBindParams; } $this->paramsAutoReset(); $this->reset(); $this->clearBindParams(); }
组块结果集-此方法前调用paramsAutoReset无效 @param int $num 每次获取的条数 @param callable $func 结果集处理函数。本回调函数内调用paramsAutoReset无效
entailment
public function where($column, $value = '') { if (is_array($column)) { foreach ($column as $key => $val) { $this->whereNeedAddAndOrOr > 0 && ($value === false ? $this->_or() : $this->_and()); $this->conditionFactory($key, $val, '='); } } else { $this->conditionFactory($column, $value, '='); } return $this; }
where条件组装 相等 @param string|array $column 如 id user.id (这边的user为表别名如表pre_user as user 这边用user而非带前缀的原表名) 当$column为数组时 批量设置 @param string |int $value 当$column为数组时 此时$value为false时条件为or 否则为and @return $this
entailment
public function whereNotBetween($column, $value, $value2 = null) { if (is_null($value2)) { if (!is_array($value)) { throw new \InvalidArgumentException(Lang::get('_DB_PARAM_ERROR_WHERE_BETWEEN_')); } $val = $value; } else { $val = [$value, $value2]; } $this->conditionFactory($column, $val, 'NOT BETWEEN'); return $this; }
where条件组装 NOT BETWEEN @param string $column 如 id user.id (这边的user为表别名如表pre_user as user 这边用user而非带前缀的原表名) @param string |int | array $value @param string |int | null $value2 @return $this
entailment
public function conditionFactory($column, $value, $operator = '=') { if ($this->sql['where'] == '') $this->sql['where'] = 'WHERE '; if ($this->whereNeedAddAndOrOr === 1) { $this->sql['where'] .= ' AND '; } else if ($this->whereNeedAddAndOrOr === 2) { $this->sql['where'] .= ' OR '; } //下一次where操作默认加上AND $this->whereNeedAddAndOrOr = 1; if ($operator == 'IN' || $operator == 'NOT IN') { empty($value) && $value = [0]; //这边可直接跳过不组装sql,但是为了给用户提示无条件 便于调试还是加上where field in(0) $inValue = '('; foreach ($value as $val) { $inValue .= '%s ,'; $this->bindParams[] = $val; } $this->sql['where'] .= "{$column} {$operator} " . rtrim($inValue, ',') . ') '; } elseif ($operator == 'BETWEEN' || $operator == 'NOT BETWEEN') { $betweenValue = '%s AND %s '; $this->bindParams[] = $value[0]; $this->bindParams[] = $value[1]; $this->sql['where'] .= "{$column} {$operator} {$betweenValue} "; } else if ($operator == 'IS NULL' || $operator == 'IS NOT NULL') { $this->sql['where'] .= "{$column} {$operator} "; } else if ($operator == 'column') { substr(trim($column), 0, 1) != '`' && $column = "`{$column}` "; substr(trim($value), 0, 1) != '`' && $value = "`{$value}` "; $this->sql['where'] .= "{$column} = {$value} "; } else if ($operator == 'raw') { $this->sql['where'] .= str_replace('?', '%s', $column) . ' '; $value && $this->bindParams = array_merge($this->bindParams, $value); } else { $this->sql['where'] .= "{$column} {$operator} "; if ($operator) {//兼容类式find_in_set()这类的函数查询 $this->sql['where'] .= "%s "; $this->bindParams[] = $value; } } return $this; }
where 语句组装工厂 @param string $column 如 id user.id (这边的user为表别名如表pre_user as user 这边用user而非带前缀的原表名) @param array|int|string $value 值 @param string $operator 操作符 @return $this
entailment
public function _and(callable $callable = null) { $history = $this->whereNeedAddAndOrOr; $this->whereNeedAddAndOrOr = 1; if (is_callable($callable)) { $history === 0 && $this->whereNeedAddAndOrOr = 0; $this->lBrackets(); call_user_func($callable, $this); $this->rBrackets(); } return $this; }
增加 and条件操作符 @param callable $callable 如果传入函数则函数内执行的条件会被()包围 @return $this
entailment
public function lBrackets() { if ($this->sql['where'] == '') { $this->sql['where'] = 'WHERE '; } else { if ($this->whereNeedAddAndOrOr === 1) { $this->sql['where'] .= ' AND '; } else if ($this->whereNeedAddAndOrOr === 2) { $this->sql['where'] .= ' OR '; } } $this->sql['where'] .= ' ('; //移除下一次where操作默认加上AND $this->whereNeedAddAndOrOr = 0; return $this; }
where条件增加左括号 @return $this
entailment
public function columns($columns = '*') { $result = ''; if (is_array($columns)) { foreach ($columns as $key => $val) { $result .= ($result == '' ? '' : ', ') . (is_int($key) ? $val : ($key . " AS `{$val}`")); } } else { $result = implode(', ', func_get_args()); } $this->sql['columns'] == '' || ($this->sql['columns'] .= ' ,'); $this->sql['columns'] .= $result; return $this; }
选择列 @param string|array $columns 默认选取所有 ['id, 'name'] 选取id,name两列,['article.id' => 'aid', 'article.title' => 'article_title'] 别名 @return $this
entailment
public function limit($offset = 0, $limit = 10) { $offset = intval($offset); $limit = intval($limit); $offset < 0 && $offset = 0; $limit < 1 && $limit = 100; $this->sql['limit'] = "LIMIT {$offset}, {$limit}"; return $this; }
LIMIT @param int $offset 偏移量 @param int $limit 返回的条数 @return $this
entailment
public function orderBy($column, $order = 'ASC') { if ($this->sql['orderBy'] == '') { $this->sql['orderBy'] = "ORDER BY {$column} {$order} "; } else { $this->sql['orderBy'] .= ", {$column} {$order} "; } return $this; }
排序 @param string $column 要排序的字段 @param string $order 方向,默认为正序 @return $this
entailment
public function having($column, $operator = '=', $value, $logic = 'AND') { $having = $this->sql['having'] == '' ? 'HAVING' : " {$logic} "; $this->sql['having'] .= "{$having} {$column} {$operator} "; if ($value) { if (is_array($value)) {//手动传%s $this->bindParams = array_merge($this->bindParams, $value); } else { $this->sql['having'] .= ' %s '; $this->bindParams[] = $value; } } return $this; }
having语句 @param string $column 字段名 @param string $operator 操作符 @param string|array $value 值 @param string $logic 逻辑AND OR @return $this
entailment
public function join($table, $on, $tablePrefix = null) { is_null($tablePrefix) && $tablePrefix = $this->tablePrefix; $this->table($table, $tablePrefix); $hasAlias = is_array($table) ? true : false; $tableName = $tablePrefix . ($hasAlias ? key($table) : $table); $this->join[count($this->table) - 1 . '_' . $tableName] = is_array($on) ? $this->parseOn($table, $on) : addslashes($on); return $this; }
join内联结 @param string|array $table 表名 要取别名时使用 [不带前缀表名 => 别名] @param string $on 联结的条件 如:'c.cid = a.cid' @param mixed $tablePrefix 表前缀 @return $this
entailment
public function union($sql, $all = false) { if (is_array($sql)) { foreach ($sql as $s) { $this->union .= $all ? ' UNION ALL ' : ' UNION '; $this->union .= $this->filterUnionSql($s); } } else { $this->union .= $all ? ' UNION ALL ' : ' UNION '; $this->union .= $this->filterUnionSql($sql) . ' '; } return $this; }
union联结 @param string|array $sql 要union的sql @param bool $all 是否为union all @return $this
entailment
protected function parseOn(&$table, $on) { if (empty($on)) { throw new \InvalidArgumentException(Lang::get('_DB_PARAM_ERROR_PARSE_ON_', $table)); } $result = ''; foreach ($on as $key => $val) { if (is_numeric($key)) { $result == '' || $result .= ' AND '; $result .= $val; } else { $result == '' || $result .= ($val === true ? ' AND ' : ' OR '); $result .= $key; } } return addslashes($result); //on条件是程序员自己写死的表字段名不存在注入以防万一还是过滤一下 }
解析联结的on参数 @param string $table 要联结的表名 @param array $on ['on条件1', 'on条件2' => true] on条件为数字索引时多条件默认为and为非数字引时 条件=>true为and 条件=>false为or @return string
entailment
public function paramsAutoReset($autoReset = true, $alwaysClearTable = false, $alwaysClearColumns = true) { $this->paramsAutoReset = $autoReset; $this->alwaysClearTable = $alwaysClearTable; $this->alwaysClearColumns = $alwaysClearColumns; return $this; }
orm参数是否自动重置, 默认在执行语句后会重置orm参数,包含查询的表、字段信息、条件等信息 @param bool $autoReset 是否自动重置 查询的表、字段信息、条件等信息 @param bool $alwaysClearTable 用来控制在$paramsAutoReset = false 的时候是否清除查询的table信息.避免快捷方法重复调用table(); @param bool $alwaysClearColumns 用来控制在$paramsAutoReset = false 的时候是否清除查询的字段信息.主要用于按批获取数据不用多次调用columns(); @return $this
entailment
protected function arrToCondition($arr) { $s = $p = ''; $params = []; foreach ($arr as $k => $v) { if (is_array($v)) { //自增或自减 switch (key($v)) { case '+': case 'inc': $p = "`{$k}`= `{$k}`+" . abs(intval(current($v))); break; case '-': case 'dec': $p = "`{$k}`= `{$k}`-" . abs(intval(current($v))); break; case 'func': $func = strtoupper(key(current($v))); $funcParams = current(current($v)); foreach ($funcParams as $key => $val) { if (substr($val, 0, 1) !== '`') { $funcParams[$key] = '%s'; $params[] = $val; } } $p = "`{$k}`= {$func}(" . implode($funcParams, ',') . ')'; break; case 'column': $p = "`{$k}`= `" . current($v) . "`"; break; case 'raw': $p = "`{$k}`= " . addslashes(current($v));//flags = (flags | 2) ^ 3 break; default ://计算类型 $conKey = key($v); if (!in_array(key(current($v)), ['+', '-', '*', '/', '%', '^', '&', '|', '<<', '>>', '~'])) { throw new \InvalidArgumentException(Lang::get('_PARSE_UPDATE_SQL_PARAMS_ERROR_')); } $p = "`{$k}`= `{$conKey}`" . key(current($v)) . abs(intval(current(current($v)))); break; } } else { $p = "`{$k}`= %s"; $params[] = $v; } $s .= (empty($s) ? '' : ',') . $p; } $this->bindParams = array_merge($params, $this->bindParams); return $s; }
SQL语句条件组装 @param array $arr 要组装的数组 @return string
entailment
protected function parseKey($key, $and = true, $noCondition = false, $noTable = false) { $condition = ''; $arr = explode('-', $key); $len = count($arr); for ($i = 1; $i < $len; $i += 2) { isset($arr[$i + 1]) && $condition .= ($condition ? ($and ? ' AND ' : ' OR ') : '') . "`{$arr[$i]}` = %s"; $this->bindParams[] = $arr[$i + 1]; } $table = strtolower($arr[0]); if (empty($table) && !$noTable) { throw new \InvalidArgumentException(Lang::get('_DB_PARAM_ERROR_PARSE_KEY_', $key, 'table')); } if (empty($condition) && !$noCondition) { throw new \InvalidArgumentException(Lang::get('_DB_PARAM_ERROR_PARSE_KEY_', $key, 'condition')); } empty($condition) || $condition = "($condition)"; return [$table, $condition]; }
SQL语句条件组装 @param string $key eg: 'forum-fid-1-uid-2' @param bool $and 多个条件之间是否为and true为and false为or @param bool $noCondition 是否为无条件操作 set/delete/update操作的时候 condition为空是正常的不报异常 @param bool $noTable 是否可以没有数据表 当delete/update等操作的时候已经执行了table() table为空是正常的 @return array eg: ['forum', "`fid` = '1' AND `uid` = '2'"]
entailment
public function getCacheVer($table) { if (!$this->openCache) { return ''; } $version = Model::getInstance()->cache()->get($this->conf['mark'] . '_db_cache_version_' . $table); if (!$version) { $version = microtime(true); Model::getInstance()->cache()->set($this->conf['mark'] . '_db_cache_version_' . $table, $version, $this->conf['cache_expire']); } return $version; }
根据表名获取cache版本号 @param string $table @return mixed
entailment
public function setCacheVer($table) { if (!$this->openCache) { return; } $isOpenEmergencyMode = Config::get('emergency_mode_not_real_time_refresh_mysql_query_cache'); if ($isOpenEmergencyMode !== false && $isOpenEmergencyMode > 0) {//开启了紧急模式 $expireTime = Model::getInstance()->cache()->get("emergency_mode_not_real_time_refresh_mysql_query_cache_{$table}"); if ($expireTime && $isOpenEmergencyMode + $expireTime > time()) { return; } Model::getInstance()->cache()->set("emergency_mode_not_real_time_refresh_mysql_query_cache_{$table}", time(), 3600); } Model::getInstance()->cache()->set($this->conf['mark'] . '_db_cache_version_' . $table, microtime(true), $this->conf['cache_expire']); }
设置cache版本号 @param string $table
entailment
public function assign($key, $val = null) { if (is_array($key)) { $this->args = array_merge($this->args, $key); } else { $this->args[$key] = $val; } return $this; }
变量赋值 @param string | array $key 赋值到模板的key,数组或字符串为数组时批量赋值 @param mixed $val 赋值到模板的值 @return $this
entailment
public function assignByRef($key, &$val = null) { if (is_array($key)) { foreach ($key as $k => &$v) { $this->args[$k] = $v; } } else { $this->args[$key] = $val; } return $this; }
引用赋值 @param string | array $key 赋值到模板的key,数组或字符串为数组时批量赋值 @param mixed $val @return $this
entailment
public function getValue($key = null) { if (is_null($key)) {//返回所有 return $this->args; } elseif (isset($this->args[$key])) { return $this->args[$key]; } else { return null; } }
获取赋到模板的值 @param string $key 要获取的值的key,数组或字符串为数组时批量赋值 @return mixed
entailment