<?php
namespace App\Controller\Backend;
use App\Entity\Brand;
use App\Services\Helper;
use Exception;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class BrandController extends AbstractController
{
/**
* @Route("/{_locale}/dashboard/brand/list")
*/
public function listBrandAction(Request $request){
$em = $this->getDoctrine()->getManager();
$brands = $em->getRepository(Brand::class)->findBy(['deleted' => 0]);
return $this->render('/backend/brands/list.html.twig',[
'brands' => $brands
]);
}
/**
* @Route("/{_locale}/dashboard/brand/edit/{idBrand}")
* @Route("/{_locale}/dashboard/brand/add", defaults={"idBrand":null})
*/
public function editBrandAction(Request $request, Helper $helper){
$em = $this->getDoctrine()->getManager();
$idBrand = $helper->sanitize($request->get('idBrand'));
$brand = $em->getRepository(Brand::class)->findOneBy(['idBrand' => $idBrand]);
if(!$brand){
$brand = new Brand();
}
return $this->render('backend/brands/edit.html.twig',[
'brand' => $brand
]);
}
/**
* @Route("/{_locale}/dashboard/brand/save")
* @Security("has_role('ROLE_ADMINISTRADOR')")
*/
public function brandSaveAction(Request $request, Helper $helper){
$em = $this->getDoctrine()->getManager();
$response = new JsonResponse();
try{
$idBrand = $helper->sanitize($request->request->get('idBrand'));
$name = $helper->sanitize($request->request->get('name'));
if (!$name)
throw new Exception('Name not valid');
$brand = $em->getRepository(Brand::class)->findOneBy(['idBrand' => $idBrand]);
if(!$brand){
$brand = new Brand();
}
$brand->setName($name);
$brand->setDeleted(0);
$em->persist($brand);
$em->flush();
$response->setStatusCode(200);
$response->setData(array(
'response' => 'success',
'msg' => 'Action performed successfully',
'idBrand' => $brand->getIdBrand()
));
return $response;
} catch(Exception $e){
$response->setStatusCode(500);
$response->setData(array(
'response' => 'error',
'msg' => 'Something has gone wrong'
));
return $response;
}
}
/**
* @Route("/{_locale}/dashboard/brand/delete")
* @Security("has_role('ROLE_ADMINISTRADOR')")
*/
public function brandDeleteAction(Request $request, Helper $helper){
$em = $this->getDoctrine()->getManager();
$response = new JsonResponse();
try{
$idBrand = $helper->sanitize($request->request->get('idBrand'));
$brand = $em->getRepository(Brand::class)->findOneBy(['idBrand' => $idBrand]);
$brand->setDeleted(1);
$em->persist($brand);
$em->flush();
$response->setStatusCode(200);
$response->setData(array(
'response' => 'success'
));
return $response;
} catch(Exception $e){
$response->setStatusCode(500);
$response->setData(array(
'response' => 'error',
'msg' => 'Something has gone wrong'
));
return $response;
}
}
}