src/Controller/ProductController.php line 30
<?php
namespace App\Controller;
use App\Entity\Product;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Class ProductController
*
* @package App\Controller
*
* @author Tristan Heckelsmüller <t.heckelsmueller@seonicals.de>
* @copyright Copyright (c) 2023, Seonicals GmbH
*/
class ProductController extends AbstractController
{
#[Route('/products', name: 'app_product')]
public function index(): Response
{
return $this->render('product/index.html.twig', [
'controller_name' => 'ProductController',
]);
}
#[Route('/products/{id}', name: 'app_product')]
public function show(ManagerRegistry $doctrine, int $id) : Response
{
$product = $doctrine->getRepository(Product::class)->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
return new Response('Check out this great product: '.$product->getName());
}
#[Route('/products/create', name: 'create_product')]
public function createProduct(ManagerRegistry $doctrine, ValidatorInterface $validator): Response
{
$entityManager = $doctrine->getManager();
$product = new Product();
$product->setName('Mouse');
$product->setPrice(100);
$errors = $validator->validate($product);
if (count($errors) > 0) {
return new Response((string) $errors, 400);
}
$entityManager->persist($product);
$entityManager->flush();
return new Response('Saved new product with id '.$product->getId());
}
}