DemoController.php 2.04 KB
<?php

namespace App\Http\Container\AppSection\Controllers\Activity;

use App\Enums\ActivitySongTypeEnum;
use App\Enums\ActivityStatusEnum;
use App\Helpers\JsonResource;
use App\Models\Activity;
use App\Models\UserShare;
use App\Support\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DemoController extends Controller
{
    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function __invoke(Request $request): JsonResponse
    {
        $pageSize = $request->integer('size', 20);
        $filter   = $request->mergeIfMissing(['setSort' => '-id'])->except('page', 'size');

        $data = Activity::filter($filter)
            ->with(['user:id,nick_name,avatar', 'project:id,name', 'tags:id,name'])
            ->select(['id', 'cover', 'song_name', 'user_id', 'project_id', 'status', 'created_at', 'created_form'])
            ->addSelect(['share_count' => $this->getShareCountQuery()])
            ->where('song_type', ActivitySongTypeEnum::DEMO)
            ->whereIn('status', [ActivityStatusEnum::UP->value, ActivityStatusEnum::DOWN->value])
            ->when($request->integer('demo_type'), fn(Builder $query, $type) => $type === 1 ? $query->whereIn('created_form', [0, 1]) : $query->where('created_form', 2))
            ->paginate($pageSize);

        return JsonResource::success(JsonResource::SUCCESS, [
            'data'  => $data->each(fn($item) => $item->setAttribute('demo_type', $item->getAttribute('created_form') !== 2 ? 1 : 2)->setHidden(['user_id', 'project_id', 'created_form']))->toArray(),
            'count' => $data->total()
        ]);
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    protected function getShareCountQuery(): \Illuminate\Database\Query\Builder
    {
        return UserShare::selectRaw('count(distinct to_id)')
            ->where('subject_type', Activity::class)
            ->whereColumn('subject_id', 'activitys.id')
            ->whereHas('toUser')->getQuery();
    }
}