优化代码

main
gzydong 2021-05-24 11:31:36 +08:00
parent 69245aef69
commit 29a1b2de60
12 changed files with 208 additions and 107 deletions

View File

@ -29,7 +29,8 @@ SIMPLE_JWT_PREFIX=jwt
WEB_URL=http://im.gzydong.club WEB_URL=http://im.gzydong.club
IMG_URL=http://im-img0.gzydong.club IMG_URL=http://im-img0.gzydong.club
UPLOAD_PATH=/www/data/lumenim UPLOAD_PATH=/www/data/lumenim
IP_ADDRESS=0.0.0.0 ## 管理员邮箱
ADMIN_EMAIL=
# ---- 邮件配置 ---- # ---- 邮件配置 ----
MAIL_DRIVER=smtp MAIL_DRIVER=smtp

View File

@ -204,4 +204,15 @@ class AuthController extends CController
return $this->response->success($data, '验证码发送成功...'); return $this->response->success($data, '验证码发送成功...');
} }
/**
* 发送验证码
* @RequestMapping(path="test", methods="get")
*/
public function test()
{
//$user = User::first();
//$name = $user->yuanodng;
var_dump($name);
}
} }

View File

@ -4,7 +4,9 @@ declare(strict_types=1);
namespace App\Exception\Handler; namespace App\Exception\Handler;
use App\Cache\Repository\LockRedis;
use App\Constants\ResponseCode; use App\Constants\ResponseCode;
use App\Support\MailerTemplate;
use Hyperf\Contract\StdoutLoggerInterface; use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler; use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream; use Hyperf\HttpMessage\Stream\SwooleStream;
@ -30,9 +32,12 @@ class AppExceptionHandler extends ExceptionHandler
$data = json_encode([ $data = json_encode([
'code' => ResponseCode::SERVER_ERROR, 'code' => ResponseCode::SERVER_ERROR,
'message' => 'Internal Server Error.' 'message' => 'Internal Server Error.',
'errors' => config('app_env') == 'dev' ? $throwable->getTrace() : [],
], JSON_UNESCAPED_UNICODE); ], JSON_UNESCAPED_UNICODE);
$this->sendAdminEmail($throwable);
return $response->withHeader('Server', 'Lumen IM')->withStatus(500)->withBody(new SwooleStream($data)); return $response->withHeader('Server', 'Lumen IM')->withStatus(500)->withBody(new SwooleStream($data));
} }
@ -44,4 +49,31 @@ class AppExceptionHandler extends ExceptionHandler
{ {
return true; return true;
} }
/**
* 发送系统报错通知邮件
*
* @param Throwable $throwable
*/
public function sendAdminEmail(Throwable $throwable)
{
$error = implode(':', [
'error',
time(),
md5($throwable->getFile() . $throwable->getCode() . $throwable->getLine()),
]);
$adminEmail = config('admin_email');
if ($adminEmail && LockRedis::getInstance()->lock($error, 60 * 30)) {
try {
email()->send(
$adminEmail,
'系统报错通知',
container()->get(MailerTemplate::class)->errorNotice($throwable)
);
} catch (\Exception $exception) {
}
}
}
} }

View File

@ -17,8 +17,6 @@ class JwtAuthExceptionHandler extends ExceptionHandler
{ {
public function handle(Throwable $throwable, ResponseInterface $response) public function handle(Throwable $throwable, ResponseInterface $response)
{ {
// 判断被捕获到的异常是希望被捕获的异常
if ($throwable instanceof AuthException) {
// 格式化输出 // 格式化输出
$data = json_encode([ $data = json_encode([
'code' => $throwable->getCode(), 'code' => $throwable->getCode(),
@ -32,9 +30,6 @@ class JwtAuthExceptionHandler extends ExceptionHandler
return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(401)->withBody(new SwooleStream($data)); return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(401)->withBody(new SwooleStream($data));
} }
return $response;
}
/** /**
* 判断该异常处理器是否要对该异常进行处理 * 判断该异常处理器是否要对该异常进行处理
* *
@ -43,6 +38,6 @@ class JwtAuthExceptionHandler extends ExceptionHandler
*/ */
public function isValid(Throwable $throwable): bool public function isValid(Throwable $throwable): bool
{ {
return true; return $throwable instanceof AuthException;
} }
} }

View File

@ -23,8 +23,6 @@ class ValidateExceptionHandler extends ExceptionHandler
*/ */
public function handle(Throwable $throwable, ResponseInterface $response) public function handle(Throwable $throwable, ResponseInterface $response)
{ {
// 判断被捕获到的异常是希望被捕获的异常
if ($throwable instanceof ValidateException) {
// 格式化输出 // 格式化输出
$data = json_encode([ $data = json_encode([
'code' => $throwable->getCode(), 'code' => $throwable->getCode(),
@ -38,9 +36,6 @@ class ValidateExceptionHandler extends ExceptionHandler
return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(200)->withBody(new SwooleStream($data)); return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withStatus(200)->withBody(new SwooleStream($data));
} }
return $response;
}
/** /**
* 判断该异常处理器是否要对该异常进行处理 * 判断该异常处理器是否要对该异常进行处理
* *
@ -49,6 +44,6 @@ class ValidateExceptionHandler extends ExceptionHandler
*/ */
public function isValid(Throwable $throwable): bool public function isValid(Throwable $throwable): bool
{ {
return true; return $throwable instanceof ValidateException;
} }
} }

View File

@ -12,38 +12,15 @@ use PHPMailer\PHPMailer\Exception;
*/ */
class Mail class Mail
{ {
/**
* 发送邮件验证码
*
* @param string $email 邮箱地址
* @param string $sms_code 验证码
* @param string $title 邮件标题
* @return bool
*/
public function sendEmailCode(string $email, string $sms_code, string $title)
{
$view = $this->view(config('view.engine'), 'emails.verify-code', [
'service_name' => "邮箱绑定",
'sms_code' => $sms_code,
'domain' => config('domain.web_url')
]);
try {
return $this->mail($email, $title, $view);
} catch (\Exception $e) {
return false;
}
}
/** /**
* @param string $address * @param string $address
* @param string $subject * @param string $subject
* @param string $view * @param string $view
* @return bool * @return bool
* @throws \PHPMailer\PHPMailer\Exception
*/ */
private function mail(string $address, string $subject, string $view): bool public function send(string $address, string $subject, string $view): bool
{ {
try {
$config = config('mail'); $config = config('mail');
$mail = new PHPMailer(); // PHPMailer对象 $mail = new PHPMailer(); // PHPMailer对象
$mail->CharSet = 'UTF-8'; // 设定邮件编码默认ISO-8859-1如果发中文此项必须设置否则乱码 $mail->CharSet = 'UTF-8'; // 设定邮件编码默认ISO-8859-1如果发中文此项必须设置否则乱码
@ -60,17 +37,9 @@ class Mail
$mail->MsgHTML($view); $mail->MsgHTML($view);
$mail->AddAddress($address); // 收件人 $mail->AddAddress($address); // 收件人
return $mail->Send(); return $mail->Send();
} } catch (\Exception $e) {
logger()->error($e->getTraceAsString());
/** return false;
* @param string $engine }
* @param string $template
* @param array $params
* @return string
*/
private function view(string $engine, string $template, array $params = []): string
{
$config = config('view.config', []);
return container()->get($engine)->render($template, $params, $config);
} }
} }

View File

@ -2,6 +2,8 @@
namespace App\Support; namespace App\Support;
use Throwable;
/** /**
* 邮件视图模板 * 邮件视图模板
* *
@ -17,13 +19,13 @@ class MailerTemplate
* @param array $params 模板参数 * @param array $params 模板参数
* @return string * @return string
*/ */
public function view(string $engine, string $template, $params = []): string private function view(string $engine, string $template, $params = []): string
{ {
return container()->get($engine)->render($template, $params, config('view.config', [])); return container()->get($engine)->render($template, $params, config('view.config', []));
} }
/** /**
* 邮件验证码模板 * 验证码通知 - 邮件模板
* *
* @param string $sms_code 验证码 * @param string $sms_code 验证码
* @param array $params 模板参数 * @param array $params 模板参数
@ -39,10 +41,15 @@ class MailerTemplate
} }
/** /**
* 注册成功通知 * 系统错误通知 - 邮件模板
*
* @param Throwable $throwable
* @return string
*/ */
public function register() public function errorNotice(Throwable $throwable)
{ {
return $this->view(config('view.engine'), 'emails.error-notice', [
'throwable' => $throwable->getTraceAsString()
]);
} }
} }

View File

@ -57,7 +57,10 @@ class SendEmailCode
$this->setCode($key, $sms_code);; $this->setCode($key, $sms_code);;
// ...执行发送(后期使用队列) // ...执行发送(后期使用队列)
container()->get(Mail::class)->sendEmailCode($email, $sms_code, 'Lumen IM(绑定邮箱验证码)'); email()->send(
$email, 'Lumen IM(绑定邮箱验证码)',
container()->get(MailerTemplate::class)->emailCode($sms_code)
);
return true; return true;
} }

View File

@ -119,13 +119,20 @@ function response()
return container()->get(ResponseInterface::class); return container()->get(ResponseInterface::class);
} }
function email()
{
return container()->get(\App\Support\Mail::class);
}
/** /**
* 从HTML文本中提取所有图片 * 从HTML文本中提取所有图片
* *
* @param string $content HTML文本 * @param string $content HTML文本
* @return array * @return array
*/ */
function get_html_images($content) function get_html_images(string $content)
{ {
$pattern = "/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/"; $pattern = "/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
preg_match_all($pattern, htmlspecialchars_decode($content), $match); preg_match_all($pattern, htmlspecialchars_decode($content), $match);
@ -147,7 +154,7 @@ function get_html_images($content)
* @param string $day2 日期2 * @param string $day2 日期2
* @return float|int * @return float|int
*/ */
function diff_date($day1, $day2) function diff_date(string $day1, string $day2)
{ {
$second1 = strtotime($day1); $second1 = strtotime($day1);
$second2 = strtotime($day2); $second2 = strtotime($day2);
@ -180,7 +187,7 @@ function get_media_url(string $path)
*/ */
function create_image_name(string $ext, int $width, int $height) function create_image_name(string $ext, int $width, int $height)
{ {
return uniqid() . Str::random(16) . uniqid() . '_' . $width . 'x' . $height . '.' . $ext; return uniqid() . Str::random() . '_' . $width . 'x' . $height . '.' . $ext;
} }
/** /**
@ -205,7 +212,7 @@ function replace_url_link(string $str)
* @param int $sort 排序方式 * @param int $sort 排序方式
* @return array * @return array
*/ */
function arraysSort(array $array, $field, $sort = SORT_DESC) function arraysSort(array $array, string $field, $sort = SORT_DESC)
{ {
array_multisort(array_column($array, $field), $sort, $array); array_multisort(array_column($array, $field), $sort, $array);
return $array; return $array;
@ -214,20 +221,20 @@ function arraysSort(array $array, $field, $sort = SORT_DESC)
/** /**
* 判断0或正整数 * 判断0或正整数
* *
* @param string $int 验证字符串 * @param string|int $value 验证字符串
* @param bool $isZero 判断是否可为0 * @param bool $isZero 判断是否可为0
* @return bool * @return bool
*/ */
function check_int($int, $isZero = false) function check_int($value, $isZero = false)
{ {
$reg = $isZero ? '/^[+]{0,1}(\d+)$/' : '/^[1-9]\d*$/'; $reg = $isZero ? '/^[+]{0,1}(\d+)$/' : '/^[1-9]\d*$/';
return is_numeric($int) && preg_match($reg, $int); return is_numeric($value) && preg_match($reg, $value);
} }
/** /**
* 解析英文逗号',' 拼接的 ID 字符串 * 解析英文逗号',' 拼接的 ID 字符串
* *
* @param string $ids 字符串(例如; "1,2,3,4,5,6") * @param string|int $ids 字符串(例如; "1,2,3,4,5,6")
* @return array * @return array
*/ */
function parse_ids($ids) function parse_ids($ids)
@ -247,3 +254,5 @@ function push_amqp(ProducerMessage $message, bool $confirm = false, int $timeout
{ {
return container()->get(Producer::class)->produce($message, $confirm, $timeout); return container()->get(Producer::class)->produce($message, $confirm, $timeout);
} }

View File

@ -10,4 +10,5 @@ declare(strict_types=1);
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/ */
return [ return [
\Hyperf\ExceptionHandler\Listener\ErrorExceptionHandler::class
]; ];

View File

@ -19,11 +19,6 @@ return [
'app_env' => env('APP_ENV', 'dev'), 'app_env' => env('APP_ENV', 'dev'),
'scan_cacheable' => env('SCAN_CACHEABLE', false), 'scan_cacheable' => env('SCAN_CACHEABLE', false),
'ip_address' => env('IP_ADDRESS', ''),
// 运行模式(预留)
'run_mode' => 'cluster',
// 域名相关配置 // 域名相关配置
'domain' => [ 'domain' => [
'web_url' => env('WEB_URL', ''),//Web 端首页地址 'web_url' => env('WEB_URL', ''),//Web 端首页地址
@ -32,6 +27,9 @@ return [
'upload_dir' => env('UPLOAD_PATH', ''), 'upload_dir' => env('UPLOAD_PATH', ''),
// 管理员邮箱
'admin_email' => env('ADMIN_EMAIL', ''),
StdoutLoggerInterface::class => [ StdoutLoggerInterface::class => [
'log_level' => [ 'log_level' => [
LogLevel::ALERT, LogLevel::ALERT,

View File

@ -0,0 +1,80 @@
<head>
<base target="_blank"/>
<style type="text/css">
body {
font-size: 14px;
font-family: arial, verdana, sans-serif;
line-height: 1.666;
padding: 0;
margin: 0;
overflow: auto;
white-space: normal;
word-wrap: break-word;
min-height: 100px
}
td, input, button, select, body {
font-family: Helvetica, 'Microsoft Yahei', verdana
}
pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
width: 95%
}
th, td {
font-family: arial, verdana, sans-serif;
line-height: 1.666
}
img {
border: 0
}
header, footer, section, aside, article, nav, hgroup, figure, figcaption {
display: block
}
blockquote {
margin-right: 0px
}
::-webkit-scrollbar {
display: none;
}
</style>
</head>
<body tabindex="0" role="listitem">
<table width="700" border="0" align="center" cellspacing="0" style="width:700px;">
<tbody>
<tr>
<td>
<div style="width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;">
<table border="0" cellpadding="0" cellspacing="0" width="700" height="39"
style="font:12px Tahoma, Arial, 宋体;">
<tbody>
<tr>
<td width="210"></td>
</tr>
</tbody>
</table>
</div>
<div style="width:680px;padding:0 10px;margin:0 auto;">
<div style="line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;">
<strong style="display:block;margin-bottom:15px;font-size: 16px;">
系统报错通知:{{date('Y-m-d H:i:s')}}
</strong>
</div>
<div style="margin-bottom:30px;">
<pre>{{$throwable}}</pre>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</body>