Files
eatvio-infra/app/Services/BlogPost/ListViewService.php

99 lines
2.8 KiB
PHP

<?php
namespace App\Services\BlogPost;
use App\Livewire\BlogPost\ListView;
use App\Models\BlogPost;
use App\Models\Tag;
use App\Models\User;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
class ListViewService
{
private ListView $parentState;
public function __construct(ListView $parent)
{
$this->parentState = $parent;
}
public function buildBlogPosts(): BlogPost
{
$recipes = $this->getPrimaryCriteriedBlogPosts();
return $this->getSecondaryCriteriedBlogPosts($recipes);
}
private function getPrimaryCriteriedBlogPosts(): Builder|BlogPost|MorphToMany|array
{
if ($this->parentState->author) {
$posts = $this->getAuthorBlogPosts();
} elseif ($this->parentState->tag) {
$posts = $this->getTagBlogPosts();
} elseif ($this->parentState->search && mb_strlen($this->parentState->search) > 2) {
$posts = $this->getSearchBlogPosts();
} else {
$posts = (new BlogPost());
}
return $posts;
}
private function getSecondaryCriteriedBlogPosts(Builder|BlogPost|MorphToMany|array $posts): BlogPost
{
if ($this->parentState->typeFilter === 'user') {
$posts = $posts->whereRelation('author', 'is_consultant', false);
}
if ($this->parentState->typeFilter === 'consultant') {
$posts = $posts->whereRelation('author', 'is_consultant', true);
}
return $posts;
}
private function getAuthorBlogPosts(): array
{
$author = $this->parentState->author;
$user = User::find($author);
return $user ? $user->author_of_blog_post()->distinct() : [];
}
private function getTagBlogPosts(): MorphToMany
{
$tagId = Str::of($this->parentState->tag)->split('/-/')->first();
return Tag::find($tagId)->blogPosts();
}
private function getSearchBlogPosts(): Builder
{
return BlogPost::where('title', 'rlike', $this->parentState->search);
}
// private function getTagsCollection(): array
// {
// return Recipe::all()->map(
// fn($r) => [
// $r->type,
// $r->tags->map(fn($t) => $t->id . '-' . $t->name)->all(),
// ]
// )->reduce(function ($acc, $item) {
// [$type, $tagNames] = $item;
//
// foreach ($tagNames as $name) {
// if (isset($acc[$type][$name])) {
// $acc[$type][$name] += 1;
// } else {
// $acc[$type][$name] = 1;
// }
// }
//
// return $acc;
// });
// }
}