ClearBowl/api/app/Repositories/RecipesRepository.php

74 lines
2.1 KiB
PHP

<?php
namespace App\Repositories;
use App\Models\Recipe;
use App\Models\RecipeProduct;
use App\Models\RecipeStep;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class RecipesRepository implements RecipesRepositoryInterface
{
public function create(Collection $data)
{
return DB::transaction(function () use ($data) {
$recipeData = $data->only(['name', 'description']);
$ingredients = $data->get('ingredients');
$steps = $data->get('steps');
$recipe = Recipe::create($recipeData->toArray());
foreach ($ingredients as $ingredient) {
RecipeProduct::create([
'recipe_id' => $recipe['id'],
'product_id' => $ingredient['id'],
'weight' => $ingredient['weight']
]);
}
foreach ($steps as $step) {
RecipeStep::create(['recipe_id' => $recipe['id'], 'step' => $step]);
}
return $this->get($recipe['id']);
});
}
public function get(int $id)
{
$rawRecipe = Recipe::where('id', $id)->first();
$recipe = [
'name' => $rawRecipe['name'],
'description' => $rawRecipe['description'],
'ingredients' => $this->processIngredients($rawRecipe['ingredients']),
'steps' => $rawRecipe['steps']->pluck('step'),
'nutrition' => $rawRecipe['nutrition']
];
return $recipe;
}
public function processIngredients(Collection $ingredients)
{
return $ingredients->map(function ($item) {
return collect(array_merge($item->toArray(), $item['product']->toArray()))
->only(['name', 'weight']);
});
}
public function paginate(array $filters)
{
$query = Recipe::query();
if(isset($filters['search'])){
$search = ucfirst($filters['search']);
$query->where('name', 'like', "%${search}%");
}
return $query->paginate($filters['limit']);
}
}