ClearBowl/api/app/Repositories/RecipesRepository.php

73 lines
2.0 KiB
PHP
Raw Normal View History

2019-12-15 15:45:22 +01:00
<?php
namespace App\Repositories;
2020-01-06 17:14:54 +01:00
use App\Models\Recipe;
use App\Models\RecipeProduct;
use App\Models\RecipeStep;
2019-12-15 15:45:22 +01:00
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')
];
return $recipe;
}
public function processIngredients(Collection $ingredients)
{
return $ingredients->map(function ($item) {
2019-12-15 18:59:50 +01:00
return collect(array_merge($item->toArray(), $item['product']->toArray()))
->only(['name', 'weight']);
2019-12-15 15:45:22 +01:00
});
}
2019-12-15 21:09:14 +01:00
public function paginate(array $filters)
2019-12-15 15:45:22 +01:00
{
2020-01-06 17:14:54 +01:00
$query = Recipe::query();
if(isset($filters['search'])){
$search = ucfirst($filters['search']);
$query->where('name', 'like', "%${search}%");
}
return $query->paginate($filters['limit']);
2019-12-15 15:45:22 +01:00
}
2020-01-06 17:14:54 +01:00
2019-12-15 15:45:22 +01:00
}