<?php declare(strict_types=1);
namespace App\Product\Controller;
use App\Framework\Controller\APIController;
use App\Framework\Serializer\APISerializerGroup;
use App\Product\Entity\Product;
use App\Product\Entity\ProductCategory;
use App\Product\Repository\ProductCategoryRepository;
use App\Product\Repository\ProductRepository;
use App\Product\Service\ProductCategoryService;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
#[Route(path: '/api/categories')]
class ProductCategoryController extends APIController
{
/**
* @throws ExceptionInterface
*
* @return mixed[]|ProductCategory[]|void
*/
#[Route(path: '', methods: ['GET'])]
#[APISerializerGroup('productcategory:default')]
public function indexAction(ProductCategoryRepository $productCategoryRepository): array
{
if ($this->isGranted('ROLE_ADMIN')) {
return $productCategoryRepository->findAll();
} else {
return $productCategoryRepository->findBy([
'display' => 1,
]);
}
}
#[Route(path: '', methods: ['POST'])]
#[APISerializerGroup('productcategory:default')]
#[Security("is_granted('ROLE_ADMIN')")]
public function createAction(ProductCategoryService $categoryService): ProductCategory
{
$name = $this->getRequestBodyData('name', true);
$visible = $this->getRequestBodyData('visible', false, false);
return $categoryService->createProductCategory($name, $visible);
}
#[Route(path: '/{id}', methods: ['PATCH'])]
#[APISerializerGroup('productcategory:default')]
#[Security("is_granted('ROLE_ADMIN')")]
public function updateAction(ProductCategory $category, ProductCategoryService $categoryService): ProductCategory
{
$name = $this->getRequestBodyData('name', true);
$visible = $this->getRequestBodyData('visible', true);
return $categoryService->updateProductCategory($category, $name, $visible);
}
#[Route(path: '/{id}', methods: ['DELETE'])]
#[APISerializerGroup('productcategory:default')]
#[Security("is_granted('ROLE_ADMIN')")]
public function deleteAction(ProductCategory $category, ProductCategoryService $categoryService): void
{
$categoryService->deleteProductCategory($category);
}
/**
* @throws ExceptionInterface
*
* @return Product[]
*/
#[Route(path: '/{id}', methods: ['GET'])]
#[APISerializerGroup('product:list')]
public function listAction(int $id, ProductRepository $productRepository): array
{
// TODO: Use service instead of repository directly
return $productRepository->findForSaleByCategoryId($id);
}
}