src/Controller/BaseController.php line 396

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Currency;
  4. use App\Entity\PageCategory;
  5. use App\Entity\Setting;
  6. use App\Service\WebticariClient;
  7. use Doctrine\Common\Collections\ArrayCollection;
  8. use Doctrine\ORM\EntityManager;
  9. use Doctrine\ORM\Query;
  10. use JMS\Serializer\SerializationContext;
  11. use JMS\Serializer\Serializer;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Fixtures\UserProvider\DummyProvider;
  14. use Symfony\Component\HttpFoundation\Cookie;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpFoundation\Session\Session;
  17. use Symfony\Component\Yaml\Yaml;
  18. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  19. use App\Entity\Cart;
  20. use App\Entity\Category;
  21. use App\Entity\Menu;
  22. use App\Entity\Page;
  23. use App\Entity\Store;
  24. use App\Entity\User;
  25. use App\Entity\UserComment;
  26. use App\Entity\UserSettings;
  27. use App\Entity\UserWishlist;
  28. use Symfony\Component\HttpFoundation\RequestStack;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. abstract class BaseController extends AbstractController
  31. {
  32.     private $state = [];
  33.     private $firstPageIsLogin;
  34.     protected $requestStack;
  35.     /**
  36.      * @var Serializer
  37.      */
  38.     private $serializer;
  39.     /**
  40.      * @var WebticariClient
  41.      */
  42.     private $webticariClient;
  43.     /**
  44.      * BaseController constructor.
  45.      * @param Serializer $serializer
  46.      * @param EntityManager $em
  47.      * @param WebticariClient $webticariClient
  48.      */
  49.     public function __construct(Serializer $serializerEntityManager $emwebticariClient $webticariClient,RequestStack $requestStack)
  50.     {
  51.         $this->serializer $serializer;
  52.         $this->webticariClient $webticariClient;
  53.         $this->requestStack $requestStack;
  54.     }
  55.     protected function serialize($data$format 'json')
  56.     {
  57.         $context = new SerializationContext();
  58.         $groups[] = 'Default';
  59.         $context->setGroups($groups);
  60.         return $this->serializer->serialize($data$format$context);
  61.     }
  62.     protected function normalize($data$format 'json')
  63.     {
  64.         $context = new SerializationContext();
  65.         $groups[] = 'Default';
  66.         $context->setGroups($groups);
  67.         return $this->serializer->toArray($data$context);
  68.     }
  69.     protected function setState($key$value)
  70.     {
  71.         $this->state[$key] = $value;
  72.     }
  73.     protected function pushState($state)
  74.     {
  75.         $this->state array_merge($this->state$state);
  76.     }
  77.     protected function response(string $view$data = [], $headers = []): Response
  78.     {
  79.         $response = new Response();
  80.         $request $this->get('request_stack')->getCurrentRequest();
  81.         $accessAllowedRoutes = [
  82.             'catalog_page',
  83.             'catalog_dealership_form',
  84.             'catalog_checkout_pay',
  85.             'catalog_checkout_summary',
  86.             'catalog_checkout_address''catalog_payment',
  87.             'catalog_payment_success',
  88.             'catalog_payment_error',
  89.             'wishlist'
  90.         ];
  91.         if ($this->firstPageIsLogin && !$this->isGranted('ROLE_USER') && !in_array($request->attributes->get('_route'), $accessAllowedRoutes)) {
  92.             throw new AuthenticationException();
  93.         }
  94.         $cartCookie $request->cookies->get('CART_ID');
  95.         $firstCookieArray = [];
  96.         if($request->cookies->get('device_view') == 'full'){
  97.             $firstCookie $request->cookies->get('FIRST');
  98.             $firstCookieArray[0] = $firstCookie;
  99.         }else {
  100.             $firstCookieArray[0] =1;
  101.         }
  102.         $this->setState('firstCookie', [
  103.             'items' => $firstCookieArray
  104.         ]);
  105. //        $denemeArray = $this->state;
  106. //        dump($denemeArray['firstCookie']['items'][0]);
  107.         if ($cartCookie === null) {
  108.             $date = new \DateTime();
  109.             $date->add(new \DateInterval('P10Y'));
  110.             // $cookie = new Cookie('CART_ID', $this->getSession()->getId(), $date, '/', null, true, true, false, 'None');
  111.             $cookie = new Cookie('CART_ID'$this->getSession()->getId(), $date'/'nullfalsetruefalsenull);
  112.             $response->headers->setCookie($cookie);
  113.         }
  114.         $response->headers->set('Cache-Control''no-cache, no-store, must-revalidate');
  115.         $response->headers->set('Pragma''no-cache');
  116.         $response->headers->set('Expires''-1');
  117.         foreach ($headers as $key => $value) {
  118.             $response->headers->set($key$value);
  119.         }
  120.         $currencies $this->getCurrencies();
  121.         $this->setState('currency'$currencies);
  122.         $favicon $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'favicon']);
  123.         $this->setState('favicon'$favicon->getValue());
  124.         $data['favicon'] = $favicon->getValue();
  125.         $wplocation $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'wpDestekButonYonu']);
  126.         if ($wplocation == !null) {
  127.             $this->setState('wplocation'$wplocation->getValue());
  128.             $data['wplocation'] = $wplocation->getValue();
  129.         } else {
  130.             $this->setState('wplocation'"0");
  131.             $data['wplocation'] = "0";
  132.         }
  133.         $translationsTr __DIR__ '/../../translations/catalog.tr.yaml';
  134.         $translationsEn __DIR__ '/../../translations/catalog.en.yaml';
  135.         $parsedTranslationsTr Yaml::parse(file_get_contents($translationsTr));
  136.         $parsedTranslationsEn Yaml::parse(file_get_contents($translationsEn));
  137.         $this->setState('translate', [
  138.             'activeLocale' => $request->getLocale(),
  139.             'languages' => [
  140.                 'tr' => $parsedTranslationsTr,
  141.                 'en' => $parsedTranslationsEn
  142.             ]
  143.         ]);
  144.         $this->setState('cart'$this->getCart());
  145.         $this->setState('deneme'$this->getCart());
  146.         $this->setState('address'$this->getAddresses());
  147.         $this->setState('wishlist'$this->getWishlist());
  148.         $this->setState('accountInfo'$this->getAccountInfo());
  149.         $this->setState('comment'$this->getComments());
  150.         $this->setState('commentByUser'$this->getCommentItemsByUser());
  151. //        $this->setState('campaignProduct', $this->getCampaignProduct());
  152.         $store $this->getDoctrine()->getRepository(Store::class)->find(1);
  153.         $this->setState('store'$store);
  154.         if($this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'ucretsizKargoSecenek'])){
  155.             $ucretsizKargoSecenek $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'ucretsizKargoSecenek']);
  156.             $ucretsizKargoMiktar $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'ucretsizKargoMiktar']);
  157.         }else{$ucretsizKargoSecenek =null;
  158.             $ucretsizKargoMiktar =null;
  159.         }
  160.         $themeColor $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'theme-color']);
  161.         $themeHoverColor $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'theme-color-2']);
  162.         $this->setState('route', [
  163.             'cart' => $this->generateUrl('catalog_cart'),
  164.             'backToShop' => $this->generateUrl('catalog_search'),
  165.             'login' => $this->generateUrl('app_login'),
  166.             'checkout' => [
  167.                 'cart' => $this->generateUrl('catalog_checkout_cart'),
  168.                 'payment' => $this->generateUrl('catalog_checkout_pay'),
  169.                 'summary' => $this->generateUrl('catalog_checkout_summary'),
  170.                 'address' => $this->generateUrl('catalog_checkout_address'),
  171.             ],
  172.         ]);
  173.         $explodedMetaTagsArray explode('ç'$this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'metatags'])
  174.             ->getValue());
  175.         $lastMetaTags = [];
  176.         foreach ($explodedMetaTagsArray as $metatags) {
  177.             $metatags html_entity_decode($metatags);
  178. //            $metatags = htmlentities($metatags);
  179.             array_push($lastMetaTags$metatags);
  180.         };
  181. //        $data['fb_id'] = $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'fb_id'])
  182. //            ->getValue();
  183.         $data['pagec'] = $this->getDoctrine()->getRepository(Page::class)->createQueryBuilder('page')->orderBy('page.id''DESC')->getQuery()->getResult();
  184.         $data['mainPageCategories'] = $this->getDoctrine()
  185.             ->getRepository(PageCategory::class)
  186.             ->createQueryBuilder('category')
  187.             ->orderBy('category.id''ASC')
  188.             ->getQuery()
  189.             ->getResult();
  190.         $data['mainCategories'] = $this->getDoctrine()->getRepository(Category::class)->findAllCategories();
  191.         $data['metaTags'] = $lastMetaTags;
  192.         $data['ucretsizKargoSecenek'] = $ucretsizKargoSecenek;
  193.         $data['ucretsizKargoMiktar'] = $ucretsizKargoMiktar;
  194.         $data['themeColor'] = $themeColor;
  195.         $data['themeHoverColor'] = $themeHoverColor;
  196.         $data['isAuthenticated'] = $this->isGranted('ROLE_USER');
  197.         $data['currency'] = $currencies;
  198.         $data['salesRepresentative'] = null;
  199.         $data['user'] = null;
  200.         $array =$this->getDoctrine()
  201.             ->getRepository(Menu::class)
  202.             ->createQueryBuilder('menu')
  203.             ->orderBy('menu.sortStatus''ASC')
  204.             ->getQuery()
  205.             ->getResult();
  206.             $array2=[];
  207.         foreach ($array as $menu){
  208.             if($menu->getPage()!=null){
  209.                 array_push($array2,[
  210.                     'type' => 0,
  211.                     'sortStatus'=> $menu->getSortStatus(),
  212.                     'url' => $menu->getPage()->getSeo() ? 'sayfalar/'.$menu->getPage()->getSeo() :'',
  213.                     'name' => $menu->getPage()->getTitle(),
  214.                     'category'=>null,
  215.                     'childStatus'=>null,
  216.                 ]);
  217.             }
  218.             else if($menu->getCategory()!=null) {
  219.                 array_push($array2,[
  220.                     'type' => 1,
  221.                     'sortStatus'=> $menu->getSortStatus(),
  222.                     'url' => '',
  223.                     'name' => null,
  224.                     'category'=>$menu->getCategory(),
  225.                     'childStatus'=>$menu->getChildStatus(),
  226.                 ]);
  227.             }
  228.             else{
  229.                 array_push($array2,[
  230.                     'type' => 0,
  231.                     'sortStatus'=> $menu->getSortStatus(),
  232.                     'url' => $menu->getUrl() ?$menu->getUrl() : '' ,
  233.                     'name' => $menu->getName(),
  234.                     'category'=>null,
  235.                     'childStatus'=>null,
  236.                 ]);
  237.             }
  238.         }
  239. //        dump($array2);
  240.         $data['menu'] = $array2;
  241.         if ($this->getUser()) {
  242.             $user $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
  243.             $this->setState('customerBranchState', [
  244.                     'branches' => $user $user->getCustomerBranches() : [],
  245.                     'branch' => $this->getSession()->get('branch')
  246.                 ]
  247.             );
  248.             $data['salesRepresentative'] = $user $user->getSalesRepresentative() : null;
  249.             $data['user'] = $user;
  250.         }
  251.         $settings $this->getDoctrine()->getRepository(Setting::class)->findAll();
  252.         $settingState = [];
  253.         $privateSettings = [
  254.             'baslik',
  255.             'imza',
  256.             'kulad',
  257.             'mailadres',
  258.             'popauth',
  259.             'popport',
  260.             'popserverad',
  261.             'popssl',
  262.             'port',
  263.             'serverad',
  264.             'sifre',
  265.             'smtpauth',
  266.             'smtpssl'
  267.         ];
  268.         foreach ($settings as $setting) {
  269.             if (!in_array($setting->getKey(), $privateSettings)) {
  270.                 $settingState[$setting->getKey()] = (string)$setting->getValue();
  271.             }
  272.         }
  273.         $settingState['showPriceStatus'] = $data['user'] !== null "1" : ($settingState['showPriceStatus'] == "0" "0" "1");
  274.         $topHeaderInfo = isset($settingState['topHeaderInfo']) ? explode(','$settingState['topHeaderInfo']) : [];
  275.         $data['topHeaderInfo'] = [
  276.             'salesRepresentativeName' => in_array('salesRepresentativeName'$topHeaderInfo) && $data['salesRepresentative'] ? $data['salesRepresentative']->getName() : null,
  277.             'salesRepresentativePhone' => in_array('salesRepresentativePhone'$topHeaderInfo) && $data['salesRepresentative'] ? $data['salesRepresentative']->getPhone() : null,
  278.             'salesRepresentativeEmail' => in_array('salesRepresentativeEmail'$topHeaderInfo) && $data['salesRepresentative'] ? $data['salesRepresentative']->getEmail() : null,
  279.             'customerName' => in_array('customerName'$topHeaderInfo) && $data['user'] ? $data['user']->getName() : null,
  280.             'customerBalance' => in_array('customerBalance'$topHeaderInfo) && $this->getSession()->get('customerInformation') ? $this->getSession()->get('customerInformation')['balance'] : null,
  281.             'customerCurrency' => in_array('customerBalance'$topHeaderInfo) && $this->getSession()->get('customerInformation') ? $this->getSession()->get('customerInformation')['currency'] : null,
  282.         ];
  283.         $this->setState('settingState'$settingState);
  284.         $data['searchQuery'] = $request->query->has('q') ? $request->query->get('q') : '';
  285.         $data['searchCategory'] = 0;
  286.         if ($request->query->has('category')) {
  287.             $category explode('_'$request->query->get('category'));
  288.             $data['searchCategory'] = $category[0];
  289.         }
  290.         $data['store'] = $this->getDoctrine()->getRepository(Store::class)->find(1);
  291.         $data['setting'] = $settingState;
  292.         return $this->render($viewarray_merge(['state' => $this->serialize($this->state)], $data), $response);
  293.     }
  294.     public function getSession()
  295.     {
  296.         if (null === $this->requestStack) {
  297.             throw new \LogicException('RequestStack is null.');
  298.         }
  299.         return $this->requestStack->getSession();
  300.     }
  301.     private function getCurrencies(): array
  302.     {
  303.         $currencies = new ArrayCollection($this->getDoctrine()->getRepository(Currency::class)->findAll());
  304.         $getDefaultCurrencySetting $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['key' => 'defaultCurrency']);
  305.         $defaultCurrencySetting $getDefaultCurrencySetting ? ($getDefaultCurrencySetting->getValue() === 'Customer' null $getDefaultCurrencySetting->getValue()) : null;
  306.         $session $this->getSession();
  307.         $defaultCurrency null;
  308.         if ($this->getUser() !== null && $defaultCurrencySetting === null) {
  309.             $user $this->getUser();
  310.             $defaultCurrency $currencies->filter(static function (Currency $currency) use ($user) {
  311.                 return $currency->getCode() === $user->getCurrency();
  312.             })->first();
  313.         } else if ($this->getUser() !== null && $defaultCurrencySetting !== null) {
  314.             $defaultCurrency $currencies->filter(static function (Currency $currency) use ($defaultCurrencySetting) {
  315.                 return $currency->getCode() === $defaultCurrencySetting;
  316.             })->first();
  317.         } else if ($this->getUser() === null) {
  318.             $defaultCurrency $defaultCurrencySetting !== null $currencies->filter(static function (Currency $currency) use ($defaultCurrencySetting) {
  319.                 return $currency->getCode() === $defaultCurrencySetting;
  320.             })->first() : $currencies[0];
  321.         }
  322.         if ($session->get('defaultCurrency') === null) {
  323.             $session->set('defaultCurrency'$defaultCurrency);
  324.         }
  325.         return [
  326.             'currencies' => $currencies,
  327.             'defaultCurrency' => $session->get('defaultCurrency'$defaultCurrency),
  328.             'userCurrency' => $defaultCurrency,
  329.         ];
  330.     }
  331.     private function getCart(): array
  332.     {
  333.         if ($this->getUser()) {
  334.             $cartItems $this->getDoctrine()->getRepository(Cart::class)->findCartItemsByUser($this->getUser());
  335.         } else {
  336.             $cartCookie $this->get('request_stack')->getCurrentRequest()->cookies->get('CART_ID');
  337.             $cartItems $this->getDoctrine()->getRepository(Cart::class)->findCartItemsByCookie($cartCookie);
  338.         }
  339.         return [
  340.             'items' => $cartItems
  341.         ];
  342.     }
  343.     private function getAddresses(): array
  344.     {
  345.         if ($this->getUser()) {
  346.             $user $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
  347.             $userX $user->getId();
  348.             $em $this->getDoctrine()->getManager();
  349.             $result $em->createQuery('select m from App:UserAddress m where m.userControl = ' $userX ' ')
  350.                 ->getResult(Query::HYDRATE_ARRAY);
  351.         } else {
  352.             $result = [];
  353.         }
  354.         return [
  355.             'items' => $result
  356.         ];
  357.     }
  358.     private function getWishlist(): array
  359.     {
  360.         if ($this->getUser()) {
  361.             $user $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
  362.             $userX $user->getId();
  363.             $em $this->getDoctrine()->getManager();
  364.             $wishlistItems $this->getDoctrine()->getRepository(UserWishlist::class)->findWishlistItemsByUser
  365.             ($this->getUser());
  366.         } else {
  367.             $wishlistItems = [];
  368.         }
  369.         return [
  370.             'items' => $wishlistItems
  371.         ];
  372.     }
  373.     private function getAccountInfo(): array
  374.     {
  375.         if ($this->getUser()) {
  376.             $user $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
  377.             $usersettingcontrol $this->getDoctrine()->getRepository(UserSettings::class)->findOneBy(['user' => $user->getId()]);
  378.         } else {
  379.             $usersettingcontrol = [];
  380.         }
  381.         return [
  382.             'items' => $usersettingcontrol
  383.         ];
  384.     }
  385.     private function getComments(): array
  386.     {
  387.         $result $this->getDoctrine()->getRepository(UserComment::class)->findAll();
  388.         return [
  389.             'items' => $result
  390.         ];
  391.     }
  392. //    private function getCampaignProduct(): array
  393. //    {
  394. //        $campaignProductItems = $this->getDoctrine()->getRepository('App:Product')
  395. //            ->findAll();
  396. //
  397. //        return [
  398. //            'items' => $campaignProductItems
  399. //        ];
  400. //    }
  401.     private function getCommentItemsByUser(): array
  402.     {
  403.         if ($this->getUser()) {
  404.             $user $this->getDoctrine()->getRepository(User::class)->find($this->getUser()->getId());
  405.             $userX $user->getId();
  406.             $em $this->getDoctrine()->getManager();
  407.             $commentItems $this->getDoctrine()->getRepository(UserComment::class)->findCommentItemsByUser
  408.             ($this->getUser());
  409.         } else {
  410.             $commentItems = [];
  411.         }
  412.         return [
  413.             'items' => $commentItems
  414.         ];
  415.     }
  416. }