85 lines
2.6 KiB
PHP
85 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Cqs\Queries\Recipes;
|
|
|
|
use App\Contracts\Query;
|
|
use App\Contracts\QueryInput;
|
|
use App\Models\Recipe;
|
|
use Domain\Models\ValueObjects\Products\ProductCategory;
|
|
use Domain\Models\ValueObjects\Recipes\ConsumptionTime;
|
|
use Domain\Models\ValueObjects\Recipes\Inspiration;
|
|
use Domain\Models\ValueObjects\Recipes\Season;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use SortDirection;
|
|
use Webmozart\Assert\Assert;
|
|
|
|
/**
|
|
* phpcs:disable Generic.Files.LineLength
|
|
*
|
|
* @implements \App\Contracts\Query<\App\Cqs\Queries\Recipes\GetBoPaginatedRecipesQueryInput, \App\Cqs\Queries\Recipes\GetBoPaginatedRecipesQueryOutput>
|
|
* phpcs:enable
|
|
*/
|
|
final readonly class GetBoPaginatedRecipesQuery implements Query
|
|
{
|
|
private const array SORTABLE_COLUMNS = [
|
|
'name',
|
|
'product_category',
|
|
'consomption_time',
|
|
'inspiration',
|
|
'season',
|
|
'is_published',
|
|
'created_at',
|
|
'updated_at',
|
|
];
|
|
|
|
#[\Override]
|
|
public function __invoke(QueryInput $input): GetBoPaginatedRecipesQueryOutput
|
|
{
|
|
Assert::isAOf($input, GetBoPaginatedRecipesQueryInput::class);
|
|
|
|
/** @var Builder<Recipe> $query */
|
|
$query = Recipe::query();
|
|
|
|
if ($input->isTrash) {
|
|
$query->onlyTrashed();
|
|
}
|
|
|
|
if ($input->search !== null && $input->search !== '') {
|
|
$words = array_filter(explode(' ', $input->search));
|
|
$query->where(function (Builder $q) use ($words, $input): void {
|
|
foreach ($words as $word) {
|
|
$q->where('name', 'like', "%{$word}%");
|
|
}
|
|
$q->orWhere('name', 'like', "%{$input->search}%");
|
|
});
|
|
}
|
|
|
|
$sortCol = in_array($input->sortCol, self::SORTABLE_COLUMNS, true)
|
|
? $input->sortCol
|
|
: 'name';
|
|
|
|
$direction = $input->sortDirection === SortDirection::Descending ? 'desc' : 'asc';
|
|
$query->orderBy($sortCol, $direction);
|
|
|
|
$paginated = $query->paginate(
|
|
perPage: $input->pagination->pageSize(),
|
|
page: $input->pagination->pageNumber(),
|
|
)->withQueryString();
|
|
|
|
$searchFields = \implode(', ', [
|
|
trans('validation.attributes.name'),
|
|
]);
|
|
|
|
return new GetBoPaginatedRecipesQueryOutput(
|
|
paginatedRecipes: $paginated,
|
|
search: $input->search,
|
|
searchFields: $searchFields,
|
|
categories: ProductCategory::toArray(),
|
|
consumptionTimes: ConsumptionTime::toArray(),
|
|
inspirations: Inspiration::toArray(),
|
|
seasons: Season::toArray(),
|
|
);
|
|
}
|
|
}
|