src/Controller/ProductController.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\Validator\Validator\ValidatorInterface;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use App\Entity\Product;
  12. use App\Repository\ProductRepository;
  13. class ProductController extends AbstractController
  14. {
  15.     #[Route('/{_locale<%app.supported_locales%>}/products'methods: ['GET''HEAD'])]
  16.     public function list(TranslatorInterface $translator): Response
  17.     {
  18.         return $this->render('product/list.html.twig', [
  19.             'title' => $translator->trans('inventory')
  20.         ]);
  21.     }
  22.     
  23.     #[Route('/{_locale<%app.supported_locales%>}/products/new'methods: ['GET''HEAD'])]
  24.     public function new(TranslatorInterface $translator): Response
  25.     {
  26.         return $this->render('product/new.html.twig', [
  27.             'title' => $translator->trans('newProduct')
  28.         ]);
  29.     }
  30.     
  31.     #[Route('/{_locale<%app.supported_locales%>}/products/edit/{id<\d+>}'methods: ['GET''HEAD'])]
  32.     public function edit(int $idTranslatorInterface $translator): Response
  33.     {
  34.         return $this->render('product/edit.html.twig', [
  35.             'title' => $translator->trans('editProduct')
  36.         ]);
  37.     }
  38.     
  39.     #[Route('/api/v1/product/create'methods: ['POST'])]
  40.     public function create(Request $requestValidatorInterface $validatorEntityManagerInterface $em): JsonResponse
  41.     {
  42.         // ->toArray() deals with empty or malformed request bodies for us (and throws exceptions)
  43.         $payload $request->toArray();
  44.         
  45.         // normalize form field values @todo build normalizer
  46.         $stock $payload['stock'];
  47.         if ('' === $stock$stock null;
  48.         if (is_numeric($stock)) $stock intval($stock);
  49.         
  50.         $stockAlert $payload['stockAlert'];
  51.         if ('' === $stockAlert$stockAlert null;
  52.         if (is_numeric($stockAlert)) $stockAlert intval($stockAlert);
  53.         
  54.         // create new product
  55.         $product = new Product();
  56.         $product->setName($payload['name']);
  57.         $product->setDescription($payload['description']);
  58.         $product->setStock($stock);
  59.         $product->setStockAlert($stockAlert);
  60.         
  61.         // validate product
  62.         $violations $validator->validate($product);
  63.         if ($violations->count() > 0) {
  64.             $violationMessages = [];
  65.             foreach ($violations as $violation) {
  66.                 $violationMessages[$violation->getPropertyPath()] = $violation->getMessage();
  67.             }
  68.             return new JsonResponse($violationMessagesResponse::HTTP_UNPROCESSABLE_ENTITY);
  69.         }
  70.         
  71.         // persist product
  72.         $em->persist($product);
  73.         $em->flush();
  74.         
  75.         // give feedback
  76.         return $this->json([
  77.             'message' => 'successful',
  78.             'id' => $product->getId()
  79.         ]);
  80.     }
  81.     
  82.     #[Route('/api/v1/product/read/{id<\d+>}'methods: ['GET''HEAD'])]
  83.     public function read(int $idRequest $requestProductRepository $productRepo
  84.         TranslatorInterface $translator): JsonResponse
  85.     {
  86.         // get product
  87.         $product $productRepo->find($id);
  88.         if (empty($product)) {
  89.             return new JsonResponse(['message' => $translator->trans('entryNotFound')], Response::HTTP_NOT_FOUND);
  90.         }
  91.         
  92.         // return product
  93.         return $this->json($product);
  94.     }
  95.     
  96.     #[Route('/api/v1/product/read'methods: ['GET''HEAD'])]
  97.     public function readAll(Request $requestProductRepository $productRepo,
  98.         TranslatorInterface $translator): JsonResponse
  99.         {
  100.             // get products
  101.             $products $productRepo->findBy([], ['name' => 'asc']);
  102.             if (empty($products)) {
  103.                 return new JsonResponse(['message' => $translator->trans('noEntriesFound')], Response::HTTP_NOT_FOUND);
  104.             }
  105.             
  106.             // return products
  107.             return $this->json($products);
  108.     }
  109.     
  110.     #[Route('/api/v1/product/update/{id<\d+>}'methods: ['PATCH'])]
  111.     public function update(int $idRequest $requestValidatorInterface $validatorProductRepository $productRepo
  112.         EntityManagerInterface $emTranslatorInterface $translator): JsonResponse
  113.     {
  114.         // ->toArray() deals with empty or malformed request bodies for us (and throws exceptions)
  115.         $payload $request->toArray();
  116.         
  117.         // get product
  118.         $product $productRepo->find($id);
  119.         if (empty($product)) {
  120.             return new JsonResponse(['message' => $translator->trans('entryNotFound')], Response::HTTP_NOT_FOUND);
  121.         }
  122.         
  123.         // normalize form field values @todo build normalizer
  124.         $stock $payload['stock'];
  125.         if ('' === $stock$stock null;
  126.         if (is_numeric($stock)) $stock intval($stock);
  127.         
  128.         $stockAlert $payload['stockAlert'];
  129.         if ('' === $stockAlert$stockAlert null;
  130.         if (is_numeric($stockAlert)) $stockAlert intval($stockAlert);
  131.         
  132.         // update product
  133.         $product->setName($payload['name']);
  134.         $product->setDescription($payload['description']);
  135.         $product->setStock($stock);
  136.         $product->setStockAlert($stockAlert);
  137.         
  138.         // validate product
  139.         $violations $validator->validate($product);
  140.         if ($violations->count() > 0) {
  141.             $violationMessages = [];
  142.             foreach ($violations as $violation) {
  143.                 $violationMessages[$violation->getPropertyPath()] = $violation->getMessage();
  144.             }
  145.             return new JsonResponse($violationMessagesResponse::HTTP_UNPROCESSABLE_ENTITY);
  146.         }
  147.         
  148.         // write changes
  149.         $em->flush();
  150.         
  151.         // give feedback
  152.         return $this->json([
  153.             'message' => 'successful'
  154.         ]);
  155.     }
  156.     
  157.     #[Route('/api/v1/product/increment/{id<\d+>}'methods: ['PATCH'])]
  158.     public function increment(int $idRequest $requestValidatorInterface $validatorProductRepository $productRepo,
  159.         EntityManagerInterface $emTranslatorInterface $translator): JsonResponse
  160.         {
  161.             // ->toArray() deals with empty or malformed request bodies for us (and throws exceptions)
  162.             $payload $request->toArray();
  163.             
  164.             // get product
  165.             $product $productRepo->find($id);
  166.             if (empty($product)) {
  167.                 return new JsonResponse(['message' => $translator->trans('entryNotFound')], Response::HTTP_NOT_FOUND);
  168.             }
  169.             
  170.             // custom validation @todo build validator
  171.             $violationMessages = [];
  172.             if (empty($payload['property'])) {
  173.                 $violationMessages['property'] = $translator->trans('notBlank', [], 'validators');
  174.             }
  175.             elseif (!in_array($payload['property'], ['stock''stockAlert'])) {
  176.                 $violationMessages['property'] = $translator->trans('inappropriate', [], 'validators');
  177.             }
  178.             if (empty($payload['amount'])) {
  179.                 $violationMessages['amount'] = $translator->trans('notBlank', [], 'validators');
  180.             }
  181.             elseif (!is_numeric($payload['amount'])) {
  182.                 $violationMessages['amount'] = $translator->trans('inappropriate', [], 'validators');
  183.             }
  184.             if (empty($payload['sign'])) {
  185.                 $violationMessages['sign'] = $translator->trans('notBlank', [], 'validators');
  186.             }
  187.             elseif (!in_array($payload['sign'], ['+''-'])) {
  188.                 $violationMessages['sign'] = $translator->trans('inappropriate', [], 'validators');
  189.             }
  190.             if (!empty($violationMessages)) {
  191.                 return new JsonResponse($violationMessagesResponse::HTTP_UNPROCESSABLE_ENTITY);
  192.             }
  193.             
  194.             // normalize values @todo build normalizer
  195.             $amount intval($payload['amount']);
  196.             
  197.             // update product
  198.             $getter 'get' ucfirst($payload['property']);
  199.             $setter 'set' ucfirst($payload['property']);
  200.             $currVal intval($product->$getter());
  201.             if ('+' === $payload['sign']) $product->$setter($currVal $amount);
  202.             if ('-' === $payload['sign']) {
  203.                 if ($currVal $amount >= 0$product->$setter($currVal $amount);
  204.                 else return new JsonResponse([
  205.                     'amount' => $translator->trans('inappropriate', [], 'validators')
  206.                 ], Response::HTTP_UNPROCESSABLE_ENTITY);
  207.             }
  208.             
  209.             // write changes
  210.             $em->flush();
  211.             
  212.             // give feedback
  213.             return $this->json([
  214.                 'message' => 'successful'
  215.             ]);
  216.     }
  217.     
  218.     #[Route('/api/v1/product/delete/{id<\d+>}'methods: ['DELETE'])]
  219.     public function delete(int $idRequest $requestValidatorInterface $validatorProductRepository $productRepo,
  220.         EntityManagerInterface $emTranslatorInterface $translator): JsonResponse
  221.         {
  222.             // get product
  223.             $product $productRepo->find($id);
  224.             if (empty($product)) {
  225.                 return new JsonResponse(['message' => $translator->trans('entryNotFound')], Response::HTTP_NOT_FOUND);
  226.             }
  227.             
  228.             // remove product
  229.             $em->remove($product);
  230.             $em->flush();
  231.             
  232.             // give feedback
  233.             return $this->json([
  234.                 'message' => 'successful'
  235.             ]);
  236.     }
  237. }