src/Controller/ProductController.php line 30

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Product;
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Component\Validator\Validator\ValidatorInterface;
  9. /**
  10.  * Class ProductController
  11.  *
  12.  * @package App\Controller
  13.  *
  14.  * @author Tristan Heckelsmüller <t.heckelsmueller@seonicals.de>
  15.  * @copyright Copyright (c) 2023, Seonicals GmbH
  16.  */
  17. class ProductController extends AbstractController
  18. {
  19.     #[Route('/products'name'app_product')]
  20.     public function index(): Response
  21.     {
  22.         return $this->render('product/index.html.twig', [
  23.             'controller_name' => 'ProductController',
  24.         ]);
  25.     }
  26.     #[Route('/products/{id}'name'app_product')]
  27.     public function show(ManagerRegistry $doctrineint $id) : Response
  28.     {
  29.         $product $doctrine->getRepository(Product::class)->find($id);
  30.         if (!$product) {
  31.             throw $this->createNotFoundException(
  32.                 'No product found for id '.$id
  33.             );
  34.         }
  35.         return new Response('Check out this great product: '.$product->getName());
  36.     }
  37.     #[Route('/products/create'name'create_product')]
  38.     public function createProduct(ManagerRegistry $doctrineValidatorInterface $validator): Response
  39.     {
  40.         $entityManager $doctrine->getManager();
  41.         $product = new Product();
  42.         $product->setName('Mouse');
  43.         $product->setPrice(100);
  44.         $errors $validator->validate($product);
  45.         if (count($errors) > 0) {
  46.             return new Response((string) $errors400);
  47.         }
  48.         $entityManager->persist($product);
  49.         $entityManager->flush();
  50.         return new Response('Saved new product with id '.$product->getId());
  51.     }
  52. }