<?php
namespace App\Controller\Api;
use App\Helper\ConvertUnitMeasures;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use App\Controller\Response;
use App\Entity\RecipeIngredients;
use App\Entity\Recipes;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/api/recipes", name="api_recipes_")
*/
class RecipesController extends AbstractController
{
use Response;
use \App\Controller\Request;
/**
* @Route("/{id}", name="view", methods={"GET"})
*/
public function viewRecipeAction($id, Request $request, EntityManagerInterface $em)
{
try {
$user = $this->getUser(); // TOKEN
$unitMeasure = $user->getUnitMeasure();
$lang = $this->getQueryLang($request);
$repository = $em->getRepository(Recipes::class);
$recipe = $repository->findById($id, $lang);
if ($recipe) {
$ingredientsRepository = $em->getRepository(RecipeIngredients::class);
$recipe['ingredients'] = $ingredientsRepository->findByRecipe($id, $lang);
foreach ($recipe['ingredients'] as &$ingredient){
if($unitMeasure == 2){
if($ingredient['abbreviation'] === 'g'){
$ingredient['converted_unit_measure'] = ConvertUnitMeasures::convertGrams($ingredient['quantity'], $lang);
} else if($ingredient['abbreviation'] === 'ml'){
$ingredient['converted_unit_measure'] = ConvertUnitMeasures::convertMl($ingredient['quantity'], $lang);
} else {
$ingredient['converted_unit_measure'] = $ingredient['quantity'] . ' ' . $ingredient['abbreviation'];
}
} else {
$ingredient['converted_unit_measure'] = $ingredient['quantity'] . ' ' . $ingredient['abbreviation'];
}
}
}
return $this->jsonResponse(['data' => $recipe]);
} catch (\Exception $e) {
return $this->errorJsonResponse(['message' => $e->getMessage()]);
}
}
}