65 lines
1.8 KiB
PHP
65 lines
1.8 KiB
PHP
<?php
|
|
|
|
|
|
namespace App\Repositories;
|
|
|
|
|
|
use App\Recipe;
|
|
use App\RecipeProduct;
|
|
use App\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')
|
|
];
|
|
|
|
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($chunkSize)
|
|
{
|
|
return Recipe::paginate($chunkSize);
|
|
}
|
|
}
|