优化代码

pull/446/head
Karson 2023-07-04 10:05:40 +08:00
parent 80ad9e307a
commit e4094e24e2
16 changed files with 50 additions and 58 deletions

View File

@ -123,10 +123,10 @@ class Backend extends Controller
$path = str_replace('.', '/', $controllername) . '/' . $actionname; $path = str_replace('.', '/', $controllername) . '/' . $actionname;
// 定义是否Addtabs请求 // 定义是否Addtabs请求
!defined('IS_ADDTABS') && define('IS_ADDTABS', input("addtabs") ? true : false); !defined('IS_ADDTABS') && define('IS_ADDTABS', (bool)input("addtabs"));
// 定义是否Dialog请求 // 定义是否Dialog请求
!defined('IS_DIALOG') && define('IS_DIALOG', input("dialog") ? true : false); !defined('IS_DIALOG') && define('IS_DIALOG', (bool)input("dialog"));
// 定义是否AJAX请求 // 定义是否AJAX请求
!defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax()); !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
@ -312,12 +312,12 @@ class Backend extends Controller
if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) { if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
continue; continue;
} }
$sym = isset($op[$k]) ? $op[$k] : '='; $sym = $op[$k] ?? '=';
if (stripos($k, ".") === false) { if (stripos($k, ".") === false) {
$k = $aliasName . $k; $k = $aliasName . $k;
} }
$v = !is_array($v) ? trim($v) : $v; $v = !is_array($v) ? trim($v) : $v;
$sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym); $sym = strtoupper($op[$k] ?? $sym);
//null和空字符串特殊处理 //null和空字符串特殊处理
if (!is_array($v)) { if (!is_array($v)) {
if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) { if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
@ -367,8 +367,8 @@ class Backend extends Controller
case 'NOT BETWEEN': case 'NOT BETWEEN':
$arr = array_slice(explode(',', $v), 0, 2); $arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr, function ($v) { if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
return $v != '' && $v !== false && $v !== null; return $v != '' && $v !== false && $v !== null;
})) { })) {
continue 2; continue 2;
} }
//当出现一边为空时改变操作符 //当出现一边为空时改变操作符
@ -397,7 +397,7 @@ class Backend extends Controller
$arr = $arr[0]; $arr = $arr[0];
} }
$tableArr = explode('.', $k); $tableArr = explode('.', $k);
if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
&& !empty($this->model) && $this->relationSearch) { && !empty($this->model) && $this->relationSearch) {
//修复关联模型下时间无法搜索的BUG //修复关联模型下时间无法搜索的BUG
$relation = Loader::parseName($tableArr[0], 1, false); $relation = Loader::parseName($tableArr[0], 1, false);
@ -569,8 +569,8 @@ class Backend extends Controller
unset($item['password'], $item['salt']); unset($item['password'], $item['salt']);
if ($this->selectpageFields == '*') { if ($this->selectpageFields == '*') {
$result = [ $result = [
$primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '', $primarykey => $item[$primarykey] ?? '',
$field => isset($item[$field]) ? $item[$field] : '', $field => $item[$field] ?? '',
]; ];
} else { } else {
$result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields)); $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));

View File

@ -164,7 +164,7 @@ class Auth
'avatar' => '', 'avatar' => '',
]; ];
$params = array_merge($data, [ $params = array_merge($data, [
'nickname' => preg_match("/^1[3-9]{1}\d{9}$/",$username) ? substr_replace($username,'****',3,4) : $username, 'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
'salt' => Random::alnum(), 'salt' => Random::alnum(),
'jointime' => $time, 'jointime' => $time,
'joinip' => $ip, 'joinip' => $ip,
@ -356,7 +356,7 @@ class Auth
} }
$url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path); $url = ($module ? $module : request()->module()) . '/' . (is_null($path) ? $this->getRequestUri() : $path);
$url = strtolower(str_replace('.', '/', $url)); $url = strtolower(str_replace('.', '/', $url));
return in_array($url, $rules) ? true : false; return in_array($url, $rules);
} }
/** /**
@ -394,7 +394,7 @@ class Auth
/** /**
* 获取会员组别规则列表 * 获取会员组别规则列表
* @return array * @return array|bool|\PDOStatement|string|\think\Collection
*/ */
public function getRuleList() public function getRuleList()
{ {
@ -547,7 +547,7 @@ class Auth
} }
} }
foreach ($datalist as $k => &$v) { foreach ($datalist as $k => &$v) {
$v[$renderkey] = isset($list[$v[$fieldkey]]) ? $list[$v[$fieldkey]] : null; $v[$renderkey] = $list[$v[$fieldkey]] ?? null;
} }
unset($v); unset($v);
return $datalist; return $datalist;

View File

@ -60,7 +60,7 @@ class Email
} }
$this->options = array_merge($this->options, $options); $this->options = array_merge($this->options, $options);
$secureArr = [0 => '', 1 => 'tls', 2 => 'ssl']; $secureArr = [0 => '', 1 => 'tls', 2 => 'ssl'];
$secure = isset($secureArr[$this->options['mail_verify_type']]) ? $secureArr[$this->options['mail_verify_type']] : ''; $secure = $secureArr[$this->options['mail_verify_type']] ?? '';
$logger = isset($this->options['debug']) && $this->options['debug'] ? new Log : null; $logger = isset($this->options['debug']) && $this->options['debug'] ? new Log : null;
$this->mail = new Mailer($logger); $this->mail = new Mailer($logger);
@ -217,8 +217,8 @@ class Email
$this->setError($e->getCode() . $e->getMessage()); $this->setError($e->getCode() . $e->getMessage());
} catch (CodeException $e) { } catch (CodeException $e) {
preg_match_all("/Expected: (\d+)\, Got: (\d+)( \| (.*))?\$/i", $e->getMessage(), $matches); preg_match_all("/Expected: (\d+)\, Got: (\d+)( \| (.*))?\$/i", $e->getMessage(), $matches);
$code = isset($matches[2][3]) ? $matches[2][3] : 0; $code = $matches[2][0] ?? 0;
$message = isset($matches[2][0]) ? $matches[4][0] : $e->getMessage(); $message = isset($matches[2][0]) && isset($matches[4][0]) ? $matches[4][0] : $e->getMessage();
$message = mb_convert_encoding($message, 'UTF-8', 'GBK,GB2312,BIG5'); $message = mb_convert_encoding($message, 'UTF-8', 'GBK,GB2312,BIG5');
$this->setError($message); $this->setError($message);
} catch (\Exception $e) { } catch (\Exception $e) {

View File

@ -32,8 +32,7 @@ class Ems
*/ */
public static function get($email, $event = 'default') public static function get($email, $event = 'default')
{ {
$ems = \app\common\model\Ems:: $ems = \app\common\model\Ems::where(['email' => $email, 'event' => $event])
where(['email' => $email, 'event' => $event])
->order('id', 'DESC') ->order('id', 'DESC')
->find(); ->find();
Hook::listen('ems_get', $ems, null, true); Hook::listen('ems_get', $ems, null, true);
@ -103,7 +102,7 @@ class Ems
}); });
} }
$result = Hook::listen('ems_notice', $params, null, true); $result = Hook::listen('ems_notice', $params, null, true);
return $result ? true : false; return (bool)$result;
} }
/** /**
@ -150,8 +149,7 @@ class Ems
*/ */
public static function flush($email, $event = 'default') public static function flush($email, $event = 'default')
{ {
\app\common\model\Ems:: \app\common\model\Ems::where(['email' => $email, 'event' => $event])
where(['email' => $email, 'event' => $event])
->delete(); ->delete();
Hook::listen('ems_flush'); Hook::listen('ems_flush');
return true; return true;

View File

@ -14,9 +14,9 @@ class Log extends AbstractLogger
/** /**
* Logs with an arbitrary level. * Logs with an arbitrary level.
* *
* @param mixed $level * @param mixed $level
* @param string $message * @param string $message
* @param mixed[] $context * @param array $context
* *
* @return void * @return void
* *

View File

@ -100,7 +100,7 @@ class Menu
if ($ids) { if ($ids) {
//旧版本的菜单需要做删除处理 //旧版本的菜单需要做删除处理
$config = Service::config($name); $config = Service::config($name);
$menus = isset($config['menus']) ? $config['menus'] : []; $menus = $config['menus'] ?? [];
$where = ['id' => ['in', $ids]]; $where = ['id' => ['in', $ids]];
if ($menus) { if ($menus) {
//必须是旧版本中的菜单,可排除用户自主创建的菜单 //必须是旧版本中的菜单,可排除用户自主创建的菜单
@ -184,10 +184,10 @@ class Menu
} }
$allow = array_flip(['file', 'name', 'title', 'url', 'icon', 'condition', 'remark', 'ismenu', 'menutype', 'extend', 'weigh']); $allow = array_flip(['file', 'name', 'title', 'url', 'icon', 'condition', 'remark', 'ismenu', 'menutype', 'extend', 'weigh']);
foreach ($newMenu as $k => $v) { foreach ($newMenu as $k => $v) {
$hasChild = isset($v['sublist']) && $v['sublist'] ? true : false; $hasChild = isset($v['sublist']) && $v['sublist'];
$data = array_intersect_key($v, $allow); $data = array_intersect_key($v, $allow);
$data['ismenu'] = isset($data['ismenu']) ? $data['ismenu'] : ($hasChild ? 1 : 0); $data['ismenu'] = $data['ismenu'] ?? ($hasChild ? 1 : 0);
$data['icon'] = isset($data['icon']) ? $data['icon'] : ($hasChild ? 'fa fa-list' : 'fa fa-circle-o'); $data['icon'] = $data['icon'] ?? ($hasChild ? 'fa fa-list' : 'fa fa-circle-o');
$data['pid'] = $pid; $data['pid'] = $pid;
$data['status'] = 'normal'; $data['status'] = 'normal';
if (!isset($oldMenu[$data['name']])) { if (!isset($oldMenu[$data['name']])) {

View File

@ -16,7 +16,6 @@ use Exception;
*/ */
class Security class Security
{ {
protected static $instance = null; protected static $instance = null;
/** /**
@ -420,7 +419,7 @@ class Security
*/ */
public function get_random_bytes($length) public function get_random_bytes($length)
{ {
if (empty($length) OR !ctype_digit((string)$length)) { if (empty($length) or !ctype_digit((string)$length)) {
return false; return false;
} }
@ -485,8 +484,8 @@ class Security
static $_entities; static $_entities;
isset($charset) OR $charset = $this->charset; isset($charset) or $charset = $this->charset;
isset($_entities) OR $_entities = array_map('strtolower', get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML5, $charset)); isset($_entities) or $_entities = array_map('strtolower', get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML5, $charset));
do { do {
$str_compare = $str; $str_compare = $str;
@ -698,7 +697,7 @@ class Security
// Is it indeed an "evil" attribute? // Is it indeed an "evil" attribute?
preg_match($is_evil_pattern, $attribute['name'][0]) preg_match($is_evil_pattern, $attribute['name'][0])
// Or does it have an equals sign, but no value and not quoted? Strip that too! // Or does it have an equals sign, but no value and not quoted? Strip that too!
OR (trim($attribute['value'][0]) === '') or (trim($attribute['value'][0]) === '')
) { ) {
$attributes[] = 'xss=removed'; $attributes[] = 'xss=removed';
} else { } else {
@ -870,5 +869,4 @@ class Security
return $str; return $str;
} }
} }

View File

@ -32,8 +32,7 @@ class Sms
*/ */
public static function get($mobile, $event = 'default') public static function get($mobile, $event = 'default')
{ {
$sms = \app\common\model\Sms:: $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
where(['mobile' => $mobile, 'event' => $event])
->order('id', 'DESC') ->order('id', 'DESC')
->find(); ->find();
Hook::listen('sms_get', $sms, null, true); Hook::listen('sms_get', $sms, null, true);
@ -78,7 +77,7 @@ class Sms
'template' => $template 'template' => $template
]; ];
$result = Hook::listen('sms_notice', $params, null, true); $result = Hook::listen('sms_notice', $params, null, true);
return $result ? true : false; return (bool)$result;
} }
/** /**
@ -125,8 +124,7 @@ class Sms
*/ */
public static function flush($mobile, $event = 'default') public static function flush($mobile, $event = 'default')
{ {
\app\common\model\Sms:: \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
where(['mobile' => $mobile, 'event' => $event])
->delete(); ->delete();
Hook::listen('sms_flush'); Hook::listen('sms_flush');
return true; return true;

View File

@ -15,7 +15,6 @@ use think\Hook;
*/ */
class Upload class Upload
{ {
protected $merging = false; protected $merging = false;
protected $chunkDir = null; protected $chunkDir = null;
@ -130,8 +129,8 @@ class Upload
if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) { if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
throw new UploadException(__('Uploaded file is not a valid image')); throw new UploadException(__('Uploaded file is not a valid image'));
} }
$this->fileInfo['imagewidth'] = isset($imgInfo[0]) ? $imgInfo[0] : 0; $this->fileInfo['imagewidth'] = $imgInfo[0] ?? 0;
$this->fileInfo['imageheight'] = isset($imgInfo[1]) ? $imgInfo[1] : 0; $this->fileInfo['imageheight'] = $imgInfo[1] ?? 0;
return true; return true;
} else { } else {
return !$force; return !$force;
@ -148,11 +147,13 @@ class Upload
$size = $matches ? $matches[1] : $this->config['maxsize']; $size = $matches ? $matches[1] : $this->config['maxsize'];
$type = $matches ? strtolower($matches[2]) : 'b'; $type = $matches ? strtolower($matches[2]) : 'b';
$typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3]; $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
$size = (int)($size * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0)); $size = (int)($size * pow(1024, $typeDict[$type] ?? 0));
if ($this->fileInfo['size'] > $size) { if ($this->fileInfo['size'] > $size) {
throw new UploadException(__('File is too big (%sMiB), Max filesize: %sMiB.', throw new UploadException(__(
'File is too big (%sMiB), Max filesize: %sMiB.',
round($this->fileInfo['size'] / pow(1024, 2), 2), round($this->fileInfo['size'] / pow(1024, 2), 2),
round($size / pow(1024, 2), 2))); round($size / pow(1024, 2), 2)
));
} }
} }
@ -316,7 +317,6 @@ class Upload
*/ */
public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false) public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false)
{ {
if ($this->fileInfo['type'] != 'application/octet-stream') { if ($this->fileInfo['type'] != 'application/octet-stream') {
throw new UploadException(__('Uploaded file format is limited')); throw new UploadException(__('Uploaded file format is limited'));
} }

View File

@ -22,8 +22,8 @@ class Area extends Model
{ {
$namearr = [1 => 'geo:province', 2 => 'geo:city', 3 => 'geo:district']; $namearr = [1 => 'geo:province', 2 => 'geo:city', 3 => 'geo:district'];
$rangearr = [1 => 15000, 2 => 1000, 3 => 200]; $rangearr = [1 => 15000, 2 => 1000, 3 => 200];
$geoname = isset($namearr[$level]) ? $namearr[$level] : $namearr[3]; $geoname = $namearr[$level] ?? $namearr[3];
$georange = isset($rangearr[$level]) ? $rangearr[$level] : $rangearr[3]; $georange = $rangearr[$level] ?? $rangearr[3];
// 读取范围内的ID // 读取范围内的ID
$redis = Cache::store('redis')->handler(); $redis = Cache::store('redis')->handler();
$georadiuslist = []; $georadiuslist = [];

View File

@ -50,7 +50,7 @@ class Category extends Model
{ {
$value = $value ? $value : $data['type']; $value = $value ? $value : $data['type'];
$list = $this->getTypeList(); $list = $this->getTypeList();
return isset($list[$value]) ? $list[$value] : ''; return $list[$value] ?? '';
} }
public function getFlagList() public function getFlagList()

View File

@ -115,8 +115,8 @@ class Config extends Model
$data = $result; $data = $result;
} }
$fieldarr = $valuearr = []; $fieldarr = $valuearr = [];
$field = isset($data['field']) ? $data['field'] : (isset($data['key']) ? $data['key'] : []); $field = $data['field'] ?? ($data['key'] ?? []);
$value = isset($data['value']) ? $data['value'] : []; $value = $data['value'] ?? [];
foreach ($field as $m => $n) { foreach ($field as $m => $n) {
if ($n != '') { if ($n != '') {
$fieldarr[] = $field[$m]; $fieldarr[] = $field[$m];
@ -175,7 +175,7 @@ class Config extends Model
if (!preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $uploadurl) && substr($uploadurl, 0, 1) !== '/') { if (!preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $uploadurl) && substr($uploadurl, 0, 1) !== '/') {
$uploadurl = url($uploadurl, '', false); $uploadurl = url($uploadurl, '', false);
} }
$uploadcfg['fullmode'] = isset($uploadcfg['fullmode']) && $uploadcfg['fullmode'] ? true : false; $uploadcfg['fullmode'] = isset($uploadcfg['fullmode']) && $uploadcfg['fullmode'];
$uploadcfg['thumbstyle'] = $uploadcfg['thumbstyle'] ?? ''; $uploadcfg['thumbstyle'] = $uploadcfg['thumbstyle'] ?? '';
$upload = [ $upload = [

View File

@ -7,7 +7,7 @@ use think\Model;
/** /**
* 邮箱验证码 * 邮箱验证码
*/ */
class Ems Extends Model class Ems extends Model
{ {
// 开启自动写入时间戳字段 // 开启自动写入时间戳字段
@ -18,5 +18,4 @@ class Ems Extends Model
// 追加属性 // 追加属性
protected $append = [ protected $append = [
]; ];
} }

View File

@ -7,7 +7,7 @@ use think\Model;
/** /**
* 会员余额日志模型 * 会员余额日志模型
*/ */
class MoneyLog Extends Model class MoneyLog extends Model
{ {
// 表名 // 表名

View File

@ -7,7 +7,7 @@ use think\Model;
/** /**
* 会员积分日志模型 * 会员积分日志模型
*/ */
class ScoreLog Extends Model class ScoreLog extends Model
{ {
// 表名 // 表名

View File

@ -7,7 +7,7 @@ use think\Model;
/** /**
* 短信验证码 * 短信验证码
*/ */
class Sms Extends Model class Sms extends Model
{ {
// 开启自动写入时间戳字段 // 开启自动写入时间戳字段
@ -18,5 +18,4 @@ class Sms Extends Model
// 追加属性 // 追加属性
protected $append = [ protected $append = [
]; ];
} }