ClearBowl/api/app/Repositories/RecipesRepository.php

66 lines
1.8 KiB
PHP
Raw Normal View History

2019-12-15 15:45:22 +01:00
<?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) {
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
});
}
public function paginate($chunkSize)
{
return Recipe::paginate($chunkSize);
}
}