<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\Advice;
use App\Entity\AdviceCategory;
use App\Entity\ContactData;
use App\Entity\CropType;
use App\Entity\Distributor;
use App\Entity\DistributorBranch;
use App\Entity\Module;
use App\Entity\News;
use App\Entity\NewsFilter;
use App\Entity\Page;
use App\Entity\PageModule;
use App\Entity\Product;
use App\Entity\ProductDistributorDistributorBranch;
use App\Entity\ProductType;
use App\Entity\WeedAtlas;
use App\Form\ContactFormType;
use App\Form\SearchFormType;
use App\Service\ApiGoogleService;
use App\Service\ApiMapService;
use App\Service\BreadcrumbService;
use App\Service\Notification\ContactNotificationService;
use App\Service\PdfFileService;
use App\Service\QRCodeGeneratorService;
use App\Service\RtcpService;
use App\Util\CacheInterface;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use InvalidArgumentException;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Psr\Cache\CacheItemPoolInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class DefaultController extends BaseController
{
private $randomStringService;
private $imageProvider;
private $descService;
private $logger;
private $searchService;
private $personalDataInspector;
private $personalDataAdministrator;
public function __construct(
EntityManagerInterface $em,
SerializerInterface $serializer,
private TokenStorageInterface $tokenStorage,
private RequestStack $requestStack,
PaginatorInterface $paginator,
ValidatorInterface $validator,
UserPasswordEncoderInterface $passwordEncoder,
private BreadcrumbService $breadcrumbs,
private CacheItemPoolInterface $cachePool,
private CacheInterface $cacheUtil,
private ApiGoogleService $apiGoogle,
private QRCodeGeneratorService $QRCodeGenerator,
private PdfFileService $pdfFile,
private ContactNotificationService $contactNotificationService,
) {
$data = new DateTime('now');
$this->month = (int)$data->format('m');
$this->year = $data->format('Y');
$this->user = $tokenStorage->getToken()->getUser();
$this->request = $requestStack->getCurrentRequest();
$this->paginator = $paginator;
$this->em = $em;
$this->serializer = $serializer;
$this->validator = $validator;
$this->passwordEncoder = $passwordEncoder;
}
/**
* @Route("/contact", name="app_contact")
*/
public function contact(Request $request, RtcpService $rtcpService)
{
try {
list($domain, $locale) = $this->getRequestParameter();
/** @var Page $pageObject */
$pageObject = $this->em->getRepository(Page::class)->getPageByParameterByUrl('contact', $domain, $locale);
if (!$pageObject) {
throw $this->createNotFoundException();
}
$seoPage = [];
$seoPage['meta-title'] = $pageObject->getMetaTitle();
$seoPage['meta-desc'] = $pageObject->getMetaDescription();
$seoPage['meta-keywords'] = $pageObject->getMetaKeywords();
$seoPage['nofollow'] = $pageObject->getInformationNoFollow();
} catch (Exception) {
$seoPage = [];
}
$contactData = new ContactData();
$contactData->setRtcp($rtcpService->getCurrentCode());
$form = $this->createForm(ContactFormType::class, $contactData);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$contactData = $form->getData();
$this->contactNotificationService->sendContactEmail($contactData);
$this->addFlash('success', 'pages.contact.flash.sent');
return $this->redirectToRoute('app_contact', ['_locale' => $request->getLocale()]);
}
return $this->render(
'main/contact.html.twig',
[
'domain' => $domain,
'locale' => $locale,
'seo' => $seoPage,
'form' => $form->createView(),
'page' => $pageObject
]
);
}
/**
* @Route("/change-domain/{domain}", name="main_changeDomain")
*/
public function changeDomain($domain, Request $request)
{
$cookie = new Cookie(
'domain',
$domain,
99999999999
);
$res = new Response();
$res->headers->setCookie($cookie);
$res->send();
return new Response("OK", Response::HTTP_OK);
}
/**
* @Route("/remove-cache", name="main_removeCache")
*/
public function removeCache(KernelInterface $kernel, Request $request)
{
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'sonata:cache:flush-all',
]);
$output = new BufferedOutput();
$application->run($input, $output);
$this->cacheUtil->deleteAll($this->cachePool);
$request->getSession()->getFlashBag()->add("success", "Cache wyczyszczony.");
$referer = $request->headers->get('referer');
return $this->redirect($referer);
}
// /**
// * @Route("/{_locale}/{url}", name="app_page", requirements={"_locale"="%app_locales%", "url"=".+"}, defaults={"_locale": "pl"})
// * @Route("/{url}", name="app_page_default", requirements={"url"="^(?!admin|profiler).+"}, defaults={"_locale": "pl"})
// */
// public function pageItem($url, ManagerRegistry $doctrine): Response
// {
// return $this->page($url);
// }
private function page(string $url = null): Response
{
list($domain, $locale) = $this->getRequestParameter();
/** @var Page $page */
$page = $this->em->getRepository(Page::class)->getPageByParameterByUrl($url, $domain = null, $locale = null);
if (!$page) {
throw $this->createNotFoundException();
}
$response = $this->cacheUtil->getItem($this->cachePool, $page->getId() . "_" . $domain->getName() . '_' . $locale->getSlug());
if (!$response) {
$modules = $page->getModules();
$list = [];
$i = 0;
/** @var PageModule $item */
foreach ($modules as $item) {
/** @var Module $module */
$module = $item->getModule();
if ($module && $item->getActive()) {
$list[$i]['id'] = $module->getId();
$list[$i]['type'] = $module->getTypeName();
$list[$i]['countItems'] = $module->getCountItems();
$list[$i]['template'] = $module->getTemplate();
$i++;
}
}
$response = $this->serializer->serialize($list, 'json', SerializationContext::create()->setSerializeNull(true));
$this->cacheUtil->saveItem($this->cachePool, $page->getId() . "_" . $domain->getName() . '_' . $locale->getSlug(), $response);
}
$modules = json_decode($response, true);
$seo = null;
return $this->render('main/page.html.twig', ['page' => $page, 'modules' => $modules, 'seo' => $seo, 'domain' => $domain, 'locale' => $locale]);
}
/**
* @Route("/qr", name="app_qr_generate")
*/
public function qrCodeGenerate(Request $request): Response
{
list($domain, $locale) = $this->getRequestParameter();
$tripId = (int) $request->get("trip-id", null);
$orderId = (int) $request->get("order-id", null);
if (empty($tripId) || empty($orderId)) {
return new JsonResponse([
'status' => false,
'message' => 'The trip-id and order-id parameters are necessary.'
]);
}
try {
$qrCodeFile = $this->QRCodeGenerator->createQRCode($tripId, $orderId);
$pdfFile = $this->pdfFile->saveTicketToPdfFile($qrCodeFile, $tripId, $orderId);
return new JsonResponse([
'status' => true,
'message' => $pdfFile
]);
} catch (Exception $e) {
return new JsonResponse([
'status' => false,
'message' => $e->getMessage()
]);
}
}
}