信息发布
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace app\common\service;
|
||||
|
||||
use app\common\model\PostMedia;
|
||||
use app\common\validate\PostValidate;
|
||||
use app\common\traits\crud\CrudServiceTrait;
|
||||
use app\common\model\Post;
|
||||
use support\Redis;
|
||||
use support\Request;
|
||||
|
||||
class PostService
|
||||
{
|
||||
|
||||
use CrudServiceTrait;
|
||||
|
||||
/**
|
||||
* 指定当前要操作的模型
|
||||
*/
|
||||
protected string $modelClass = Post::class;
|
||||
|
||||
/**
|
||||
* 验证器
|
||||
*/
|
||||
protected $validator = PostValidate::class;
|
||||
|
||||
/**
|
||||
* 获取验证器
|
||||
*/
|
||||
public function getValidator()
|
||||
{
|
||||
return new $this->validator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加前置处理
|
||||
*/
|
||||
public function beforeServiceStore($data, Request $request)
|
||||
{
|
||||
$data['user_id'] = $request->user->uid;;
|
||||
$media = serialize($data['media']);
|
||||
redis::set('PostMedia_'.$data['user_id'],$media,30);
|
||||
unset($data['media']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加后置处理
|
||||
*/
|
||||
public function afterServiceStore($res)
|
||||
{
|
||||
$media = redis::get('PostMedia_'.$res['user_id']);
|
||||
$media = unserialize($media);
|
||||
foreach ($media as $v) {
|
||||
PostMedia::create([
|
||||
'post_id' => $res->id,
|
||||
'media_type' => $this->getMediaTypeByUrl($v['url']),
|
||||
'url' => $v['url'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加前置处理
|
||||
*/
|
||||
public function beforeServiceUpdate($data, Request $request)
|
||||
{
|
||||
$data['user_id'] = $request->user->uid;;
|
||||
$media = serialize($data['media']);
|
||||
redis::set('PostMedia_'.$data['user_id'],$media,30);
|
||||
unset($data['media']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加后置处理
|
||||
*/
|
||||
public function afterServiceUpdate($res)
|
||||
{
|
||||
PostMedia::where('post_id', $res->id)->delete();
|
||||
$media = redis::get('PostMedia_'.$res['user_id']);
|
||||
$media = unserialize($media);
|
||||
foreach ($media as $v) {
|
||||
PostMedia::create([
|
||||
'post_id' => $res->id,
|
||||
'media_type' => $this->getMediaTypeByUrl($v['url']),
|
||||
'url' => $v['url'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
function getMediaTypeByUrl(string $url): int
|
||||
{
|
||||
// 提取后缀
|
||||
$ext = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION));
|
||||
|
||||
// 图片类型
|
||||
$imageExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
|
||||
// 视频类型
|
||||
$videoExt = ['mp4', 'mov', 'avi', 'wmv', 'flv', 'mkv'];
|
||||
|
||||
if (in_array($ext, $imageExt)) {
|
||||
return 1; // 图片
|
||||
}
|
||||
if (in_array($ext, $videoExt)) {
|
||||
return 2; // 视频
|
||||
}
|
||||
|
||||
return 0; // 未知类型
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user