aiblog/app/Services/StatisticsService.php
2024-11-17 11:30:01 +08:00

83 lines
No EOL
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Post;
use App\Models\User;
use App\Models\Category;
use Illuminate\Support\Facades\DB;
class StatisticsService
{
protected CacheService $cacheService;
public function __construct(CacheService $cacheService)
{
$this->cacheService = $cacheService;
}
public function getPostStatistics(): array
{
return $this->cacheService->remember('statistics:posts', function () {
return [
'total_posts' => Post::count(),
'posts_by_category' => $this->getPostsByCategory(),
'posts_by_author' => $this->getPostsByAuthor(),
'most_commented' => $this->getMostCommentedPosts(),
'recent_posts' => $this->getRecentPosts(),
];
});
}
protected function getPostsByCategory(): array
{
return Category::withCount('posts')
->orderByDesc('posts_count')
->get()
->map(fn($category) => [
'name' => $category->name,
'count' => $category->posts_count,
])
->toArray();
}
protected function getPostsByAuthor(): array
{
return User::withCount('posts')
->orderByDesc('posts_count')
->limit(10)
->get()
->map(fn($user) => [
'name' => $user->name,
'count' => $user->posts_count,
])
->toArray();
}
protected function getMostCommentedPosts(): array
{
return Post::withCount('comments')
->orderByDesc('comments_count')
->limit(5)
->get()
->map(fn($post) => [
'title' => $post->title,
'comments_count' => $post->comments_count,
])
->toArray();
}
protected function getRecentPosts(): array
{
return Post::latest()
->limit(5)
->get()
->map(fn($post) => [
'title' => $post->title,
'created_at' => $post->created_at,
])
->toArray();
}
}