forked from eatvio/eatvio-infra
85 lines
2.6 KiB
PHP
85 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services\BlogPost;
|
|
|
|
use App\Livewire\BlogPost\ListView;
|
|
use App\Models\BlogPost;
|
|
use App\Services\Strategy\Criteried\AuthorCriteriaStrategy;
|
|
use App\Services\Strategy\Criteried\CriteriaStrategy;
|
|
use App\Services\Strategy\Criteried\DefaultCriteriaStrategy;
|
|
use App\Services\Strategy\Criteried\SearchCriteriaStrategy;
|
|
use App\Services\Strategy\Criteried\TagCriteriaStrategy;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Relations\MorphToMany;
|
|
|
|
class ListViewService
|
|
{
|
|
private ListView $parentState;
|
|
|
|
public function __construct(ListView $parent)
|
|
{
|
|
$this->parentState = $parent;
|
|
}
|
|
|
|
public function buildBlogPosts(): BlogPost|Builder
|
|
{
|
|
$posts = $this->getPrimaryCriteriedBlogPosts();
|
|
|
|
return $this->getSecondaryCriteriedBlogPosts($posts);
|
|
}
|
|
|
|
private function getPrimaryCriteriedBlogPosts(): Builder|BlogPost|MorphToMany|array
|
|
{
|
|
$criteria = $this->getCriteriaStrategy();
|
|
return $criteria->getBlogPosts();
|
|
}
|
|
|
|
private function getCriteriaStrategy(): CriteriaStrategy
|
|
{
|
|
$strategies = [
|
|
'author' => AuthorCriteriaStrategy::class,
|
|
'tag' => TagCriteriaStrategy::class,
|
|
'search' => SearchCriteriaStrategy::class,
|
|
];
|
|
|
|
foreach ($strategies as $condition => $strategyClass) {
|
|
if ($this->parentState->{$condition}) {
|
|
return new $strategyClass($this->parentState->{$condition});
|
|
}
|
|
}
|
|
|
|
return new DefaultCriteriaStrategy();
|
|
}
|
|
|
|
private function getSecondaryCriteriedBlogPosts(Builder|BlogPost|MorphToMany|array $posts): BlogPost|Builder
|
|
{
|
|
return match ($this->parentState->typeFilter) {
|
|
'user' => $posts->whereRelation('author', 'is_consultant', false),
|
|
'consultant' => $posts->whereRelation('author', 'is_consultant', true),
|
|
default => $posts,
|
|
};
|
|
}
|
|
|
|
// 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;
|
|
// });
|
|
// }
|
|
}
|