luck-draw/app/repository/CommonRepository.php

112 lines
3.1 KiB
PHP

<?php
namespace app\repository;
use app\model\SmsLog;
use app\service\Repository;
use app\service\Sms;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;
use think\Model;
/**
* 通用域 相关操作
*
* Class CommonRepository
* @package app\repository
* @method self getInstance(Model $model = null) static
*/
class CommonRepository extends Repository
{
public const SMS_TYPE_REGISTER = 'register';//注册
public const SMS_TYPE_LOGIN = 'login';//登录
public const SMS_TYPE_BINDING = 'binding';//绑定
public const SMS_TYPE_EDIT_PASSWORD = 'edit_password';//修改密码
public const SMS_STATUS_OK = 1;//短信验证通过
public const SMS_STATUS_WAITING = 0;//验证码待检测
/**
* 发送短信
*
* @param string $phone
* @param string $type
* @return bool
*/
public function sendSms(string $phone, string $type): bool
{
try {
$now = time();
$res = SmsLog::create([
'phone' => $phone,
'type' => $type,
'code' => rand(100000, 999999),
'created_at' => date('Y-m-d H:i:s', $now),
'expired_at' => date('Y-m-d H:i:s', $now + 5 * 60),
]);
$res = Sms::send($phone, $res['code']);
if (is_bool($res)) {
return $res;
}
Log::error(json_encode($res, JSON_FORCE_OBJECT));
return false;
} catch (Exception $e) {
Log::error(sprintf("[发送短信验证码失败]%s:%d %s", $e->getFile(), $e->getLine(), $e->getMessage()));
return false;
}
}
/**
* 检查短信验证码
*
* @param string $phone
* @param string $code
* @param string $type
* @return bool
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function checkSms(string $phone, string $code, string $type): bool
{
$item = (new SmsLog())->where('phone', $phone)
->where('type', $type)
->where('code', $code)
->order('created_at', 'desc')
->order('id', 'desc')
->find();
if (!$item) {
return false;
}
if ($item['expired_at'] < date('Y-m-d H:i:s')) {
return false;
}
return $item->save(['status' => self::SMS_STATUS_OK]);
}
/**
* 日志记录
*
* @param string $msg
* @param Exception|null $e
* @param string $level
* @param string $channel
*/
public static function log(string $msg, Exception $e = null, string $level = 'error', string $channel = 'file')
{
if ($e != null) {
$msg = sprintf("[%s]%s:%s %s", $msg, $e->getFile(), $e->getLine(), $e->getMessage());
} else {
$msg = sprintf("%s", $msg);
}
Log::channel($channel)->$level($msg);
}
}