<?php
namespace App\Controller;
use App\Entity\AllTyre;
use App\Entity\Favorite;
use App\Form\CreateTyreType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Routing\Annotation\Route;
use Intervention\Image\ImageManagerStatic as Image;
use Symfony\Component\Security\Core\Security;
class AllTyreController extends AbstractController
{
/**
* @Route("/all/tyre", name="app_all_tyre")
*/
public function index(EntityManagerInterface $entityManager): Response
{
$criteria = array('status' => 'true');
$product = $entityManager->getRepository(AllTyre::class)->findBy($criteria);
return $this->render('all_tyre/index.html.twig', [
'product' => $product,
'page_name' => 'Покрышки',
]);
}
/**
* @Route("/all/tyre/{param}/{unit}", name="app_all_tyre_param")
*/
public function withParam(String $param, String $unit, EntityManagerInterface $entityManager, Security $security): Response
{
$criteria = array('link' => $unit, 'status' => 'true');
$product = $entityManager->getRepository(AllTyre::class)->findOneBy($criteria);
if($product)
{
return $this->render('all_tyre/inwidth.html.twig', [
'param' => $param,
'unit' => $unit,
'product' => $product,
]);
}
else
{
return $this->redirect('/all/tyre');
}
}
/**
* @Route("/all/tyre/create", name="app_all_tyre_create")
*/
public function create(Request $request, EntityManagerInterface $entityManager): Response
{
$task = new AllTyre();
$user = $this->getUser();
$form = $this->createForm(CreateTyreType::class, $task);
$form->handleRequest($request);
if ($form->isSubmitted()){
// $form->getData() holds the submitted values
// but, the original `$task` variable has also been updated
// $task = $form->getData();
$data = $request->request->all('create_tyre');
$alltyre = new AllTyre();
// Получаем файл из запроса
$imageFile = $form->get('path')->getData();
// Генерируем уникальное имя файла
$filename = md5(uniqid()) . '.' . $imageFile->guessExtension();
// Путь к папке для сохранения изображений
$imagesDirectory = $this->getParameter('images_directory');
// Сохраняем файл на сервере
$imageFile->move($imagesDirectory, $filename);
// Полный путь к сохраненному файлу
$filePath = $imagesDirectory . '/' . $filename;
// Открываем изображение с помощью Intervention Image
$image = Image::make($filePath);
// Определяем желаемый размер файла (1 МБ в данном случае)
$desiredSizeInBytes = 1 * 1024 * 1024;
// Если размер изображения превышает желаемый размер, сжимаем его
if (filesize($filePath) > $desiredSizeInBytes) {
$quality = 90; // Качество сжатия (от 0 до 100)
// Уменьшаем качество изображения с заданным качеством до достижения желаемого размера
while (filesize($filePath) > $desiredSizeInBytes && $quality >= 10) {
$image->save($filePath, $quality);
$quality -= 10;
}
}
$fstr = $data['width'].'/'.$data['heigth'].'R'.$data['radius'].' '.$data['iparam'].' '.$data['brand'].' '.$data['model'];
$lstr = $data['width'].'-'.$data['heigth'].'-r'.$data['radius'].'-'.$data['iparam'].'-'.$data['brand'].'-'.$data['model'];
$alltyre->setName($user->getUsername());
$alltyre->setPrice($data["price"]);
$alltyre->setFstring($fstr);
$alltyre->setWidth($data["width"]);
$alltyre->setHeigth($data["heigth"]);
$alltyre->setRadius($data["radius"]);
$alltyre->setIparam($data["iparam"]);
$alltyre->setBrand($data["brand"]);
$alltyre->setModel($data["model"]);
$alltyre->setPath($filename);
$alltyre->setStatus('true');
$alltyre->setStatusLot('false');
$alltyre->setIdLot('0');
$alltyre->setLink($lstr);
// tell Doctrine you want to (eventually) save the Product (no queries yet)
$entityManager->persist($alltyre);
// actually executes the queries (i.e. the INSERT query)
$entityManager->flush();
$criteria = array('id' => $alltyre->getId(), 'name' => $user->getUsername());
$product = $entityManager->getRepository(AllTyre::class)->findOneBy($criteria);
$product->setLink($product->getLink().'-'.$alltyre->getId());
$entityManager->flush();
// return new Response('Saved new product with id '.$product->getId());
return $this->render('all_tyre/testdata.html.twig', [
'fstring' => $fstr,
]);
// return $this->redirectToRoute('task_success');
}
return $this->renderForm('all_tyre/create.html.twig', [
'namePage' => 'Добавить покрышку',
'form' => $form,
]);
}
/**
* @Route("/all/tyre/add", name="app_all_tyre_add")
*/
public function add(Request $request, EntityManagerInterface $entityManager): Response
{
}
/**
* @Route("/favorites/add/{productId}", name="add_to_favorites", methods={"POST"})
*/
public function addToFavorites(int $productId, EntityManagerInterface $entityManager, Request $request): Response
{
$product = $entityManager->getRepository(AllTyre::class)->find($productId);
if ($product) {
// Check if the user is authenticated
$this->denyAccessUnlessGranted('ROLE_USER');
// Get the user
$user = $this->getUser();
// Check if the product is already in the user's favorites
$favorite = $entityManager->getRepository(Favorite::class)->findOneBy([
'user' => $user,
'product' => $product,
]);
if ($favorite) {
// Product is already in favorites, remove it
$entityManager->remove($favorite);
} else {
// Product is not in favorites, add it
$favorite = new Favorite();
$favorite->setUser($user);
$favorite->setProduct($product);
$entityManager->persist($favorite);
}
// Save the changes
$entityManager->flush();
}
// Redirect back to the previous page
$referer = $request->headers->get('referer');
return $this->redirect($referer);
}
}