Files
bsh_info/app/common/controller/PostFavoriteController.php
T
2025-12-01 18:11:19 +08:00

100 lines
3.1 KiB
PHP

<?php
namespace app\common\controller;
use app\common\controller\BaseController;
use app\common\model\Post;
use app\common\model\PostMedia;
use app\common\model\User;
use app\common\service\OssService;
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\PostFavoriteService;
use support\Request;
class PostFavoriteController extends BaseController
{
use CrudControllerTrait;
protected $service;
public function __construct()
{
$this->service = new PostFavoriteService();
}
/**
* 获取列表
*
* @param Request $request 请求对象
* @return mixed 返回分页数据及总数
*/
public function self(Request $request)
{
try {
$raw = $this->service->serviceSelfList($request);
$data = $this->transformData($raw, method_exists($this, 'indexFormat')
? [$this, 'indexFormat']
: null);
return $this->success($data);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
protected function indexFormat($data)
{
if (isset($data['created_at']))
$data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
if (isset($data['updated_at']))
$data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
if (isset($data['post_id'])){
$ossservice = new OssService();
$post = Post::where('id', $data['post_id'])->first()->toArray();
if (isset( $post['user_id'])){
$user = User::where('id', $post['user_id'])->first();
$postUser = [];
$postUser['name'] = $user['name'];
$postUser['nickname'] = $user['nickname'];
$postUser['avatar'] = $user['avatar'];
$postUser['avatar_pull'] = $user['avatar'];
if(!str_contains($postUser['avatar'], 'http') && !empty($postUser['avatar'])){
$postUser['avatar_pull'] = $ossservice->generatePrivateUrl($postUser['avatar']);
}
$post['user'] = $postUser;
}
$ossservice = new OssService();
if (isset($post['id'])){
$post['media'] = PostMedia::where('post_id', $post['id'])->get()->toArray();
foreach ($post['media'] as &$media) {
$media['url_pull'] = $ossservice->generatePrivateUrl($media['url']);
}
}
$data['post'] = $post;
}
return $data;
}
/**
* 删除
*
* @param Request $request 请求对象
* @return mixed 返回删除操作结果
*/
public function delete(Request $request)
{
try {
$count = $this->service->serviceDelete($request);
return $this->success([], "取消收藏成功");
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
}