Files
eatvio-infra/app/Services/FeedService.php
2023-10-04 17:57:09 +03:00

75 lines
2.6 KiB
PHP

<?php
namespace App\Services;
use App\Models\BlogPost;
use App\Models\Diet;
use App\Models\User;
use App\Models\Recipe;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class FeedService
{
public static function showActualFeed()
{
$days = 5;
$dateMax = Recipe::max('created_at');
$dateMin = Carbon::parse($dateMax)->subDays(10);
$sql = <<<EOF
SELECT
p.id,
p.title,
(
(p.likes_count + p.comments_count) /
((UNIX_TIMESTAMP(GREATEST(p.created_at,
COALESCE((SELECT MAX(l.created_at) FROM blog_post_likes l WHERE l.blog_post_id = p.id), p.created_at),
COALESCE((SELECT MAX(c.created_at) FROM blog_post_comments c WHERE c.blog_post_id = p.id), p.created_at)
)) - UNIX_TIMESTAMP(p.created_at))/60 + 1
) ^ 1.8
) AS popularity
FROM
(SELECT
`blog_posts`.id,
blog_posts.title,
blog_posts.created_at,
COUNT(blog_post_comments.id) AS comments_count,
COUNT(blog_post_likes.id) AS likes_count
FROM
`blog_posts`
LEFT JOIN blog_post_comments ON blog_post_comments.blog_post_id = blog_posts.id
LEFT JOIN blog_post_likes ON blog_post_likes.blog_post_id = blog_posts.id
GROUP BY blog_posts.id) p
ORDER BY popularity DESC;
EOF;
$hotBlogPosts = collect(
DB::select(DB::raw($sql))
)->map(fn ($post) => BlogPost::find($post->id))
->take(16)->chunk(4);
$newbiesBlogPosts = User::orderBy('created_at', 'desc')
->withCount('author_of_blog_post')
->get()
->filter(fn ($u) => $u->author_of_blog_post_count > 0)->take(4)
->pluck('id')
->map(fn ($id) => User::find($id)->author_of_blog_post()->limit(2)->get())
->flatten()
->random();
$randomRecipe = Recipe::where('created_at', '>=', $dateMin)
->where('created_at', '<=', $dateMax)
->inRandomOrder()
->limit(2)
->get();
$firstCollection = $hotBlogPosts->first()->push($newbiesBlogPosts->first())->push($randomRecipe->first());
$secondCollection = $hotBlogPosts->skip(1)->first()->push($newbiesBlogPosts->skip(1)->first())->push($randomRecipe->skip(1)->first());
$result = $firstCollection->concat($secondCollection)->filter(fn ($el) => !is_null($el) && $el->id);
return $result;
}
}