<?php
namespace App\Controller\CashBox;
use App\Entity\Category;
use App\Repository\CategoryRepository;
use App\Service\CashBox\ProductService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use App\Service\CashBox\PriceService;
/**
* @Route("/")
*/
class CategoryController extends AbstractController
{
private PriceService $priceService;
/**
* CategoryController constructor.
*/
public function __construct()
{
$this->priceService = new PriceService();
}
/**
* @Route("/categories/tree", name="caschbox_categories_tree", methods={"GET"})
* @param CategoryRepository $categoryRepository
* @param EntityManagerInterface $entityManager
* @return Response
*/
public function tree(CategoryRepository $categoryRepository, EntityManagerInterface $entityManager): Response
{
$repo = $entityManager->getRepository(Category::class);
$ret = [];
// $categories = $categoryRepository->findAll();
$categories = $repo->getChildren();
foreach ($categories as $category) {
$c = [];
$parent = $category->getParent();
$back = null;
if ($parent === null) {
$_parent = 0;
} else {
$_parent = $parent->getId();
$back = $parent->getParent();
}
if ($back === null) {
$_back = 0;
} else {
$_back = $back->getId();
}
$c['id'] = $category->getId();
$c['name'] = $category->getName();
$c['lvl'] = $category->getLvl();
$c['hasChildren'] = count($category->getChildren()) > 0;
$c['hasProducts'] = count($category->getProducts()) > 0;
$c['parent'] = $_parent;
$c['back'] = $_back;
$pathContainer = $repo->getPath($category);
/**
* @var Category $item
*/
$path = [];
foreach ($pathContainer as $item) {
$path[] = [
'id' => $item->getId(),
'name' => $item->getName(),
];
}
$c['path'] = $path;
$ret[$_parent][$category->getName()] = $c;
}
return $this->json($ret);
}
/**
* @Route("/categories/products", name="caschbox_categories_products", methods={"GET"})
* @param CategoryRepository $categoryRepository
* @return Response
*/
public function products(CategoryRepository $categoryRepository, ProductService $productService): Response
{
$ret = [];
$categories = $categoryRepository->findAll();
foreach ($categories as $category) {
$_p = $category->getProducts();
foreach ($_p as $product) {
if ($product->getStatus() === true) {
$ret[$category->getId()][$product->getId()] = $productService->buildFrontendProductFromProduct($product);
}
}
}
return $this->json($ret);
}
}