src/Controller/AllTyreController.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AllTyre;
  4. use App\Entity\Favorite;
  5. use App\Form\CreateTyreType;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  11. use Symfony\Component\HttpFoundation\File\UploadedFile;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Intervention\Image\ImageManagerStatic as Image;
  14. use Symfony\Component\Security\Core\Security;
  15. class AllTyreController extends AbstractController
  16. {
  17.     /**
  18.      * @Route("/all/tyre", name="app_all_tyre")
  19.      */
  20.     public function index(EntityManagerInterface $entityManager): Response
  21.     {
  22.         $criteria = array('status' => 'true');
  23.         $product $entityManager->getRepository(AllTyre::class)->findBy($criteria);
  24.         return $this->render('all_tyre/index.html.twig', [
  25.             'product' => $product,
  26.             'page_name' => 'Покрышки',
  27.         ]);
  28.     }
  29.     /**
  30.      * @Route("/all/tyre/{param}/{unit}", name="app_all_tyre_param")
  31.      */
  32.     public function withParam(String $paramString $unitEntityManagerInterface $entityManagerSecurity $security): Response
  33.     {
  34.         $criteria = array('link' => $unit'status' => 'true');
  35.         $product $entityManager->getRepository(AllTyre::class)->findOneBy($criteria);
  36.         if($product)
  37.         {
  38.             return $this->render('all_tyre/inwidth.html.twig', [
  39.             'param' => $param,
  40.             'unit' => $unit,
  41.             'product' => $product,
  42.         ]);
  43.         }
  44.         else
  45.         {
  46.             return $this->redirect('/all/tyre');
  47.         }
  48.     }
  49.     /**
  50.      * @Route("/all/tyre/create", name="app_all_tyre_create")
  51.      */
  52.     public function create(Request $requestEntityManagerInterface $entityManager): Response
  53.     {
  54.         $task = new AllTyre();
  55.         $user $this->getUser();
  56.         $form $this->createForm(CreateTyreType::class, $task);
  57.         $form->handleRequest($request);
  58.         if ($form->isSubmitted()){
  59.             // $form->getData() holds the submitted values
  60.             // but, the original `$task` variable has also been updated
  61.             // $task = $form->getData();
  62.             $data $request->request->all('create_tyre');
  63.             $alltyre = new AllTyre();
  64.             // Получаем файл из запроса
  65.             $imageFile $form->get('path')->getData();
  66.             // Генерируем уникальное имя файла
  67.             $filename md5(uniqid()) . '.' $imageFile->guessExtension();
  68.             // Путь к папке для сохранения изображений
  69.             $imagesDirectory $this->getParameter('images_directory');
  70.             // Сохраняем файл на сервере
  71.             $imageFile->move($imagesDirectory$filename);
  72.             // Полный путь к сохраненному файлу
  73.             $filePath $imagesDirectory '/' $filename;
  74.             // Открываем изображение с помощью Intervention Image
  75.             $image Image::make($filePath);
  76.             // Определяем желаемый размер файла (1 МБ в данном случае)
  77.             $desiredSizeInBytes 1024 1024;
  78.             // Если размер изображения превышает желаемый размер, сжимаем его
  79.             if (filesize($filePath) > $desiredSizeInBytes) {
  80.                 $quality 90// Качество сжатия (от 0 до 100)                
  81.                 // Уменьшаем качество изображения с заданным качеством до достижения желаемого размера
  82.                 while (filesize($filePath) > $desiredSizeInBytes && $quality >= 10) {
  83.                     $image->save($filePath$quality);
  84.                     $quality -= 10;
  85.                 }
  86.             }
  87.             $fstr $data['width'].'/'.$data['heigth'].'R'.$data['radius'].' '.$data['iparam'].' '.$data['brand'].' '.$data['model'];
  88.             $lstr $data['width'].'-'.$data['heigth'].'-r'.$data['radius'].'-'.$data['iparam'].'-'.$data['brand'].'-'.$data['model'];
  89.             $alltyre->setName($user->getUsername());
  90.             $alltyre->setPrice($data["price"]);
  91.             $alltyre->setFstring($fstr);
  92.             $alltyre->setWidth($data["width"]);
  93.             $alltyre->setHeigth($data["heigth"]);
  94.             $alltyre->setRadius($data["radius"]);
  95.             $alltyre->setIparam($data["iparam"]);
  96.             $alltyre->setBrand($data["brand"]);
  97.             $alltyre->setModel($data["model"]);
  98.             $alltyre->setPath($filename);
  99.             $alltyre->setStatus('true');
  100.             $alltyre->setStatusLot('false');
  101.             $alltyre->setIdLot('0');
  102.             $alltyre->setLink($lstr);
  103.             // tell Doctrine you want to (eventually) save the Product (no queries yet)
  104.             $entityManager->persist($alltyre);
  105.             // actually executes the queries (i.e. the INSERT query)
  106.             $entityManager->flush();
  107.             $criteria = array('id' => $alltyre->getId(), 'name' => $user->getUsername());
  108.             $product $entityManager->getRepository(AllTyre::class)->findOneBy($criteria);
  109.             $product->setLink($product->getLink().'-'.$alltyre->getId());
  110.             $entityManager->flush();
  111.             // return new Response('Saved new product with id '.$product->getId());
  112.             return $this->render('all_tyre/testdata.html.twig', [
  113.                 'fstring' => $fstr,
  114.             ]);
  115.             // return $this->redirectToRoute('task_success');
  116.         }
  117.         return $this->renderForm('all_tyre/create.html.twig', [
  118.             'namePage' => 'Добавить покрышку',
  119.             'form' => $form,
  120.         ]);
  121.     }
  122.     /**
  123.      * @Route("/all/tyre/add", name="app_all_tyre_add")
  124.      */
  125.     public function add(Request $requestEntityManagerInterface $entityManager): Response
  126.     {
  127.         
  128.     }
  129.     /**
  130.      * @Route("/favorites/add/{productId}", name="add_to_favorites", methods={"POST"})
  131.      */
  132.     public function addToFavorites(int $productIdEntityManagerInterface $entityManagerRequest $request): Response
  133.     {
  134.         $product $entityManager->getRepository(AllTyre::class)->find($productId);
  135.         if ($product) {
  136.             // Check if the user is authenticated
  137.             $this->denyAccessUnlessGranted('ROLE_USER');
  138.             // Get the user
  139.             $user $this->getUser();
  140.             // Check if the product is already in the user's favorites
  141.             $favorite $entityManager->getRepository(Favorite::class)->findOneBy([
  142.                 'user' => $user,
  143.                 'product' => $product,
  144.             ]);
  145.             if ($favorite) {
  146.                 // Product is already in favorites, remove it
  147.                 $entityManager->remove($favorite);
  148.             } else {
  149.                 // Product is not in favorites, add it
  150.                 $favorite = new Favorite();
  151.                 $favorite->setUser($user);
  152.                 $favorite->setProduct($product);
  153.                 $entityManager->persist($favorite);
  154.             }
  155.             // Save the changes
  156.             $entityManager->flush();
  157.         }
  158.         // Redirect back to the previous page
  159.         $referer $request->headers->get('referer');
  160.         return $this->redirect($referer);
  161.     }
  162. }