src/Controller/PageDefaultController.php line 411

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\ServiceController;
  4. use JsonException;
  5. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. class PageDefaultController extends Controller
  10. {
  11.     private $invalidSetters = [
  12.         'setCreatedAt',
  13.         'setUpdatedAt',
  14.         'setTranslatableLocale'
  15.     ];
  16.     private \App\Service\ServiceController $serviceController;
  17.     public function __construct(ServiceController $serviceController)
  18.     {
  19.         $this->serviceController $serviceController;
  20.     }
  21.     /**
  22.      * @Route("/members/dash", name="members_dash")
  23.      */
  24.     public function membersDashAction()
  25.     {
  26.         return $this->render('@theme/members/members-dash.html.twig');
  27.     }
  28.     /**
  29.      * @Route("/special-user/dash", name="special_user_dash")
  30.      */
  31.     public function specialUserDashAction()
  32.     {
  33.         return $this->render('@theme/security/special-dash.html.twig');
  34.     }
  35.     public function generateAndModifyMetaDataTags($page$componentEnity)
  36.     {
  37.         //print_r(get_class_methods($componentEnity));
  38.         $possibleMetaTitles = ['getHeadline''getHeading''getTitle''getName''getMetaTitle'];
  39.         $possibleMetaDescription = ['getContent''getDescription''getExcerpt''getMetaDescription'];
  40.         // fallbacks
  41.         if ('' == $page->getMetatitle()) {
  42.             $page->setMetatitle($page->getTitle());
  43.         }
  44.         if ('' == $page->getMetadescription()) {
  45.             $page->setMetadescription($page->getContent());
  46.         }
  47.         $metaDataArray = [];
  48.         foreach ($possibleMetaTitles as $metaTitle) {
  49.             if (method_exists($componentEnity$metaTitle)) {
  50.                 $data call_user_func([$componentEnity$metaTitle]);
  51.                 if ('' != $data) {
  52.                     $metaDataArray['title'] = call_user_func([$componentEnity$metaTitle]);
  53.                 }
  54.             }
  55.         }
  56.         foreach ($possibleMetaDescription as $metaDescription) {
  57.             if (method_exists($componentEnity$metaDescription)) {
  58.                 $data call_user_func([$componentEnity$metaDescription]);
  59.                 if ('' != $data) {
  60.                     $metaDataArray['description'] = $data;
  61.                 }
  62.             }
  63.         }
  64.         if (array_key_exists('title'$metaDataArray)) {
  65.             $page->setMetatitle($metaDataArray['title'].' | '.$page->getMetatitle());
  66.         }
  67.         if (array_key_exists('description'$metaDataArray)) {
  68.             $page->setMetadescription(strip_tags($metaDataArray['description']));
  69.         }
  70.         return $page;
  71.     }
  72.     public function routeToControllerName($routename)
  73.     {
  74.         $routes $this->get('router')->getRouteCollection();
  75.         return $routes->get($routename)->getDefaults();
  76.     }
  77.     public function findPageSlugParameters($slug)
  78.     {
  79.         $matches = [];
  80.         $regex '/{(\w*)}/';
  81.         preg_match_all($regex$slug$matches);
  82.         return $matches[1];
  83.     }
  84.     public function pageChecks($page)
  85.     {
  86.         if (== $page->isActive()) {
  87.             return false;
  88.         }
  89.         return new \DateTime() >= $page->getViewableFrom();
  90.     }
  91.     /**
  92.      * @Route("/switch-locale/{_locale}", name="switch_locale")
  93.      *
  94.      * @param mixed $_locale
  95.      */
  96.     public function switchLocale(Request $request$_locale)
  97.     {
  98.         return $this->redirect('/');
  99.         // return $this->redirect($request->headers->get('referer'));
  100.     }
  101.     /**
  102.      * // @Route("/{_locale}", name="home", defaults={"slug": "home"}))
  103.      * // @Route("/{_locale}/{slug}", name="change_locale", requirements={"slug": ".+"}).
  104.      */
  105.     // public function changeLocale(Request $request, $_locale, $slug){
  106.     //  $pageData = $this->routeMatcher($request, $slug);
  107.     //  return $pageData;
  108.     // }
  109.     /**
  110.      * @Route("/page.php", name="page_php_home")
  111.      */
  112.     public function getMethodRouterAction(Request $request)
  113.     {
  114.         $params $request->query->all();
  115.         $debug $request->query->has('_debug');
  116.         $session $request->getSession();
  117.         $em $this->getDoctrine()->getManager();
  118.         $cmsComponentArray $this->serviceController->fetchCmsComponents();
  119.         // Using doctrine cache to store dynamic page slugs
  120.         // Used in twig function generatePath (converts id to slug) and assists links with translations
  121.         $slugCache $em->getRepository('App:Page')->findAllByLocale($request->getLocale());
  122.         $cacheDriver $this->container->get('doctrine_cache.providers.arraycache');
  123.         $cacheDriver->save('slugCache'$slugCache);
  124.         if ($request->query->has('_locale')) {
  125.             $this->debug($debug'<p>CHANGING LOCALE</p>');
  126.             if ($request->getLocale() != $request->query->get('_locale')) {
  127.                 $session->set('_locale'$request->query->get('_locale'));
  128.                 $request->setLocale($session->get('_locale'$request->query->get('_locale')));
  129.                 return $this->redirect($this->generateUrl($request->get('_route'), $request->query->all()));
  130.             }
  131.         }
  132.         $structureEntities = [];
  133.         $pageID $request->query->get('page');
  134.         if (!is_numeric($pageID)) {
  135.             throw $this->createNotFoundException('PCGC - No PageID passed');
  136.         }
  137.         $pageEntity $em->getRepository('App:Page')->find($pageID);
  138.         if (null === $pageEntity) {
  139.             throw $this->createNotFoundException('PCGC - No Page found for id#'.$pageID);
  140.         }
  141.         $pageSlugArray explode('/'$pageEntity->getSlug());
  142.         $fullSegmentOrder = [];
  143.         if (count($pageSlugArray) > 1) {
  144.             $pageSlugArrayCount count($pageSlugArray);
  145.             for ($i 0$i < ($pageSlugArrayCount 1); ++$i) {
  146.                 if (array_key_exists($i$pageSlugArray) && substr_count($pageSlugArray[$i], '{') > 0) {
  147.                     $fullSegmentOrder[] = $pageSlugArray[$i];
  148.                     unset($pageSlugArray[$i]);
  149.                 }
  150.             }
  151.         }
  152.         $this->debug($debug'<p>'.$pageEntity->getSlug().'</p>');
  153.         if (substr_count($pageEntity->getSlug(), '{') > 0) {
  154.             foreach ($params as $key => $id) {
  155.                 $key strtolower($key);
  156.                 if (('_locale' != $key) || ('page' != $key) || ('_debug' != $key)) {
  157.                     $comkey $this->searchArrayKeyVal('slugEntity'$key$cmsComponentArray);
  158.                     $this->debug($debug"<p>Searching for '".$key."' against slugEntity in cmsComponentArray</p>");
  159.                     if (is_numeric($comkey)) {
  160.                         $order array_search($cmsComponentArray[$comkey]['slug'], $fullSegmentOrder);
  161.                         $this->debug($debug'<p>'.$order.' - '.$cmsComponentArray[$comkey]['slugEntity'].'</p>');
  162.                         $bundle str_replace('\\'''$cmsComponentArray[$comkey]['bundle']).':'.$cmsComponentArray[$comkey]['slugEntity'];
  163.                         $structureEntities[$order] = $em->getRepository($bundle)->find($id);
  164.                     }
  165.                 }
  166.             }
  167.         }
  168.         $slugfixer implode('/'$pageSlugArray);
  169.         $slug $slugfixer;
  170.         ksort($structureEntities);
  171.         foreach ($structureEntities as $urlelement) {
  172.             $slug .= '/'.$urlelement->getSlug();
  173.         }
  174.         if ($debug) {
  175.             $this->debug($debug'<p>Path re-built to <strong>'.$slug.'</strong></p>');
  176.             $pageData $this->routeMatcherV2($requestltrim($slug'/'));
  177.             if (is_array($pageData)) {
  178.                 $pageAllowed $this->pageChecks($pageData['page']);
  179.                 if (false == $pageAllowed) {
  180.                     throw $this->createNotFoundException('PCGC: Page view checks for PageID# "'.$pageData['page']->getId().'" has failed (disabled, before viewdate ect...) - so showing 404');
  181.                 }
  182.                 // HTML Blocks
  183.                 $htmlblocks = [];
  184.                 $assignedHtmlblocks $pageData['page']->getHtmlblocks();
  185.                 if ((is_countable($assignedHtmlblocks) ? count($assignedHtmlblocks) : 0) > 0) {
  186.                     $allHtmlBlocks $em->getRepository('App:HtmlBlocks')->findBy(['deleted' => false]);
  187.                     foreach ($assignedHtmlblocks as $assignedblock) {
  188.                         foreach ($allHtmlBlocks as $allHtmlBlock) {
  189.                             if ($assignedblock['blockId'] == $allHtmlBlock->getId()) {
  190.                                 $htmlblocks[] = [
  191.                                     'blockId' => $allHtmlBlock->getId(),
  192.                                     'position' => $assignedblock['position'],
  193.                                     'data' => $allHtmlBlock->getHtml(),
  194.                                 ];
  195.                             }
  196.                         }
  197.                     }
  198.                 }
  199.                 $pageMeta $pageData['page'];
  200.                 // replace metatitle if empty
  201.                 if ('' == $pageData['page']->getMetatitle()) {
  202.                     $pageMeta->setMetatitle($pageData['page']->getTitle());
  203.                 }
  204.                 // replace metatitles if exist on components
  205.                 foreach ($pageData['pageComponents'] as $pageComp) {
  206.                     $pageMeta $this->generateAndModifyMetaDataTags($pageData['page'], $pageComp['entity']);
  207.                 }
  208.                 return $this->render('@theme/templates/'.$pageData['page']->getTemplate()->getTemplateFile(), [
  209.                     'page' => $pageMeta,
  210.                     'slug' => $pageData['slug'],
  211.                     'pageComponents' => $pageData['pageComponents'],
  212.                     'pageHtmlBlocks' => $htmlblocks,
  213.                     'longUrl' => strtolower(implode('/'$params)),
  214.                 ]);
  215.             }   // this will be a redirect
  216.             return $pageData;
  217.         }
  218.         return $this->redirect(str_replace('//''/'$slug));
  219.     }
  220.     /**
  221.      * @Route("/page-preview", name="page_preview_home")
  222.      */
  223.     public function getPreviewMethodRouterAction(Request $request)
  224.     {
  225.         $params $request->query->all();
  226.         $session $request->getSession();
  227.         $em $this->getDoctrine()->getManager();
  228.         $cmsComponentArray $this->serviceController->fetchCmsComponents();
  229.         // Using doctrine cache to store dynamic page slugs
  230.         // Used in twig function generatePath (converts id to slug) and assists links with translations
  231.         $slugCache $em->getRepository('App:Page')->findAllByLocale($request->getLocale());
  232.         $cacheDriver $this->container->get('doctrine_cache.providers.arraycache');
  233.         $cacheDriver->save('slugCache'$slugCache);
  234.         if ($request->query->has('_locale') && $request->getLocale() != $request->query->get('_locale')) {
  235.             $session->set('_locale'$request->query->get('_locale'));
  236.             $request->setLocale($session->get('_locale'$request->query->get('_locale')));
  237.             return $this->redirect($this->generateUrl($request->get('_route'), $request->query->all()));
  238.         }
  239.         $structureEntities = [];
  240.         $pageID $request->query->get('id');
  241.         if (!is_numeric($pageID)) {
  242.             throw $this->createNotFoundException('PCGC - No PageID passed');
  243.         }
  244.         $pageEntity $em->getRepository('App:Page')->find($pageID);
  245.         if (null === $pageEntity) {
  246.             throw $this->createNotFoundException('PCGC - No Page found for id#'.$pageID);
  247.         }
  248.         if ($request->query->has('preview')) {
  249.             $previewId $request->query->get('preview');
  250.             $previewEntity $em->getRepository('App:PagePreview')->find($previewId);
  251.             if (null === $previewEntity) {
  252.                 throw $this->createNotFoundException('PCGC - No PagePreview found for id#'.$previewId);
  253.             }
  254.             if ($previewEntity->getPage()->getId() != $pageEntity->getId()) {
  255.                 throw $this->createNotFoundException('PCGC - PagePreview->pageID#'.$previewEntity->getPage()->getId().' does not match PageID#'.$pageID);
  256.             }
  257.             // get nessacary getters (dup content)
  258.             $validSetters $this->getSetters($previewEntity$pageEntity);
  259.             foreach ($validSetters as $validSetter) {
  260.                 if (in_array($validSetter$this->invalidSetters)) {
  261.                     continue;
  262.                 }
  263.                 $validGetter str_replace('set''get'$validSetter);
  264.                 $pageEntity->{$validSetter}($previewEntity->{$validGetter}());
  265.             }
  266.         }
  267.         $pageSlugArray explode('/'$pageEntity->getSlug());
  268.         $fullSegmentOrder = [];
  269.         if (count($pageSlugArray) > 1) {
  270.             $pageSlugArrayCount count($pageSlugArray);
  271.             for ($i 0$i < ($pageSlugArrayCount 1); ++$i) {
  272.                 if (array_key_exists($i$pageSlugArray) && substr_count($pageSlugArray[$i], '{') > 0) {
  273.                     $fullSegmentOrder[] = $pageSlugArray[$i];
  274.                     unset($pageSlugArray[$i]);
  275.                 }
  276.             }
  277.         }
  278.         if (substr_count($pageEntity->getSlug(), '{') > 0) {
  279.             foreach ($params as $key => $id) {
  280.                 $key strtolower($key);
  281.                 if (('_locale' != $key) || ('page' != $key) || ('_debug' != $key)) {
  282.                     $comkey $this->searchArrayKeyVal('slugEntity'$key$cmsComponentArray);
  283.                     if (is_numeric($comkey)) {
  284.                         $order array_search($cmsComponentArray[$comkey]['slug'], $fullSegmentOrder);
  285.                         $bundle str_replace('\\'''$cmsComponentArray[$comkey]['bundle']).':'.$cmsComponentArray[$comkey]['slugEntity'];
  286.                         $structureEntities[$order] = $em->getRepository($bundle)->find($id);
  287.                     }
  288.                 }
  289.             }
  290.         }
  291.         $slugfixer implode('/'$pageSlugArray);
  292.         $slug $slugfixer;
  293.         ksort($structureEntities);
  294.         foreach ($structureEntities as $urlelement) {
  295.             $slug .= '/'.$urlelement->getSlug();
  296.         }
  297.         $pageData $this->routeMatcherV2($requestltrim($slug'/'));
  298.         $pageData['page'] = $pageEntity;
  299.         if (is_array($pageData)) {
  300.             $pageAllowed $this->pageChecks($pageData['page']);
  301.             if (false == $pageAllowed) {
  302.                 throw $this->createNotFoundException('PCGC: Page view checks for PageID# "'.$pageData['page']->getId().'" has failed (disabled, before viewdate ect...) - so showing 404');
  303.             }
  304.             // HTML Blocks
  305.             $htmlblocks = [];
  306.             $assignedHtmlblocks $pageData['page']->getHtmlblocks();
  307.             if ((is_countable($assignedHtmlblocks) ? count($assignedHtmlblocks) : 0) > 0) {
  308.                 $allHtmlBlocks $em->getRepository('App:HtmlBlocks')->findBy(['deleted' => false]);
  309.                 foreach ($assignedHtmlblocks as $assignedblock) {
  310.                     foreach ($allHtmlBlocks as $allHtmlBlock) {
  311.                         if ($assignedblock['blockId'] == $allHtmlBlock->getId()) {
  312.                             $htmlblocks[] = [
  313.                                 'blockId' => $allHtmlBlock->getId(),
  314.                                 'position' => $assignedblock['position'],
  315.                                 'data' => $allHtmlBlock->getHtml(),
  316.                             ];
  317.                         }
  318.                     }
  319.                 }
  320.             }
  321.             $pageMeta $pageData['page'];
  322.             // replace metatitle if empty
  323.             if ('' == $pageData['page']->getMetatitle()) {
  324.                 $pageMeta->setMetatitle($pageData['page']->getTitle());
  325.             }
  326.             // replace metatitles if exist on components
  327.             foreach ($pageData['pageComponents'] as $pageComp) {
  328.                 $pageMeta $this->generateAndModifyMetaDataTags($pageData['page'], $pageComp['entity']);
  329.             }
  330.             return $this->render('@theme/templates/'.$pageData['page']->getTemplate()->getTemplateFile(), [
  331.                 'page' => $pageMeta,
  332.                 'slug' => $pageData['slug'],
  333.                 'pageComponents' => $pageData['pageComponents'],
  334.                 'pageHtmlBlocks' => $htmlblocks,
  335.                 'longUrl' => strtolower(implode('/'$params)),
  336.                 'preview' => true,
  337.             ]);
  338.         }   // this will be a redirect
  339.         return $pageData;
  340.         return new Response('EOF');
  341.     }
  342.     public function routeMatcherV2($request$slug)
  343.     {
  344.         $multilingual $this->container->getParameter('multilingual');
  345.         $locale $request->getLocale();
  346.         $cmsComponentArray $this->serviceController->fetchCmsComponents();
  347.         $pcgcComponents = [];
  348.         $em $this->getDoctrine()->getManager();
  349.         $debug = (bool) $request->query->has('_debug');
  350.         $this->debug($debug'<p>ROUTER DEBUG<br/>This will show you feedback during the route match process</p>');
  351.         $this->debug($debug'<br/>Current Locale ['.$request->getLocale().']');
  352.         $this->debug($debug'<br/>Looking for: <strong>'.$slug.'</strong>');
  353.         //////////////////////////
  354.         // SIMPLE MATCHES
  355.         //////////////////////////
  356.         // simple direct match
  357.         // this will match the home page in any locale and any default 'en' page
  358.         $page $em->getRepository('App:Page')->findOneBy(['slug' => $slug'deleted' => false'active' => true]);
  359.         if (null !== $page) {
  360.             $pageComponents $this->getComponentData($debug$cmsComponentArray$page->getComponents(), $request$page->getId());
  361.             $this->debug($debug"<br/><span style='color:green' >(STEP1) Found - ".$page->getTitle().' (ID#'.$page->getId().')<br/>Will render page out of debug mode</span>');
  362.             return [
  363.                 'page' => $page,
  364.                 'slug' => $slug,
  365.                 'pageComponents' => $pageComponents,
  366.             ];
  367.         }
  368.         // simple direct match for SELECTED TRANSLATION
  369.         // this route will match translations - locales matched after query
  370.         $pageAll $em->getRepository('App:Page')->findAll();
  371.         foreach ($pageAll as $page) {
  372.             if ($page->getSlug() == $slug) {
  373.                 if (false == $request->query->has('preview') && ($page->isDeleted() || !$page->isActive())) {
  374.                     throw $this->createNotFoundException('PCGC: Page Route for "'.$slug.'" has been deactived or deleted');
  375.                 }
  376.                 $pageComponents $this->getComponentData($debug$cmsComponentArray$page->getComponents(), $request$page->getId());
  377.                 $this->debug($debug"<br/><span style='color:green' >(STEP2- transaltion) Found - ".$page->getTitle().' (ID#'.$page->getId().')<br/>Will render page out of debug mode</span>');
  378.                 return [
  379.                     'page' => $page,
  380.                     'slug' => $slug,
  381.                     'pageComponents' => $pageComponents,
  382.                 ];
  383.             }
  384.         }
  385.         $this->debug($debug'<p>No direct matches found - looking for complex matches  (has a url component was used?)<br/>Checking All Pages:</p>');
  386.         // if no direct matches found  ( usually means a url component was used )
  387.         //////////////////////////
  388.         // COMPLEX MATCHES
  389.         //////////////////////////
  390.         $urlSegments explode('/'$slug);
  391.         /////////////////////////////////////////
  392.         // this is for debug reasons only ( logic repeated after this loop )
  393.         if ($debug) {
  394.             $this->debug($debug'<pre>');
  395.             $this->debug($debug'<p><strong>COMPLEX ROUTE MATCHING</strong></p>');
  396.             foreach ($pageAll as $page) {
  397.                 $pageSlugParametersArray $this->findPageSlugParameters($page->getSlug());
  398.                 $possiblePageSegments explode('/'$page->getSlug());
  399.                 $slugMatches array_intersect($urlSegments$possiblePageSegments);
  400.                 $count 0;
  401.                 $this->debug($debug'Looking for: <strong>'.$slug.'</strong><br/>');
  402.                 $this->debug($debug'Looking at : <strong>'.$page->getSlug().'</strong> - ID#'.$page->getId().'<br/>');
  403.                 if (count($possiblePageSegments) === count($urlSegments)) {
  404.                     $this->debug($debug"<span style='color:green; font-weight:bold' >Passed phase 1</span>");
  405.                     ++$count;
  406.                 }
  407.                 $this->debug($debug' - '.count($possiblePageSegments).'/'.count($urlSegments).' URL Segment Count');
  408.                 if ((is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0) > 0) {
  409.                     ++$count;
  410.                     $this->debug($debug"<br/><span style='color:green; font-weight:bold' >Passed phase 2</span> - ".(is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0).' URL Parameter Components');
  411.                 } else {
  412.                     $this->debug($debug'<br/>No URL components on this page');
  413.                 }
  414.                 if (count($slugMatches) > 0) {
  415.                     ++$count;
  416.                     $this->debug($debug"<br/><span style='color:green; font-weight:bold' >Passed phase 3</span> - ".count($slugMatches).' URL slug matches');
  417.                 } else {
  418.                     $this->debug($debug'<br/>No URL slug matches on this page');
  419.                 }
  420.                 if ((is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0) + count($slugMatches) == count($urlSegments)) {
  421.                     ++$count;
  422.                     $this->debug($debug"<br/><span style='color:green; font-weight:bold' >Passed phase 4</span> - slugParameters + slugMatches = urlSegments");
  423.                 } else {
  424.                     $this->debug($debug'<br/>slugParameters + slugMatches dont add up to '.count($urlSegments));
  425.                 }
  426.                 if (== $count) {
  427.                     $this->debug($debug"<br/><span style='color:green; font-weight:bold' >SUCCESS!! - full match</span>");
  428.                     $confirmedDebugPage $page;
  429.                     $this->debug($debug"<br/><span style='color:green' >(STEP3- complex) Found - ".$confirmedDebugPage->getTitle().' (ID#'.$confirmedDebugPage->getId().')<br/>Will render page out of debug mode</span>');
  430.                 } else {
  431.                     $this->debug($debug'<br/>Not this page');
  432.                 }
  433.                 $this->debug($debug'<p>-----------------------------------</p>');
  434.             }// end of pages loop
  435.             if (!$confirmedDebugPage) {
  436.                 $this->debug($debug'<br/>Doh! - Route Not Matched ');
  437.             }
  438.             $this->debug($debug'</pre>');
  439.         }// end of debug
  440.         ///////////////////////////////////////
  441.         foreach ($pageAll as $page) {
  442.             $pageSlugParametersArray $this->findPageSlugParameters($page->getSlug());
  443.             $possiblePageSegments explode('/'$page->getSlug());
  444.             $slugMatches array_intersect($urlSegments$possiblePageSegments);
  445.             $count 0;
  446.             if (count($possiblePageSegments) === count($urlSegments)) {
  447.                 ++$count;
  448.             }
  449.             if ((is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0) > 0) {
  450.                 ++$count;
  451.             }
  452.             if (count($slugMatches) > 0) {
  453.                 ++$count;
  454.             }
  455.             if ((is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0) + count($slugMatches) == count($urlSegments)) {
  456.                 ++$count;
  457.             }
  458.             // Passed all 4 checks
  459.             if (== $count) {
  460.                 $confirmedPage $page;
  461.             }
  462.         }// end of pages loop
  463.         if (isset($confirmedPage)) {
  464.             $this->debug($debug'<p>Calling renderPageWithURLComponents</p>');
  465.             return $this->renderPageWithURLComponents($request$confirmedPage$slug$cmsComponentArray);
  466.         }
  467.         $this->debug($debug'<p><strong>STILL NO MATCH</strong> - START CHECKING TRANSLATIONS - with seperate indervidual url segments</p>');
  468.         // exit;
  469.         ////////////////////////////
  470.         // Lacale auto switcher
  471.         ////////////////////////////
  472.         // if page still not found check translations then change locale to match
  473.         // Note: for the switcher to work you have to refresh the page
  474.         if ($multilingual) {
  475.             $repository $em->getRepository(\Gedmo\Translatable\Entity\Translation::class);
  476.             foreach ($pageAll as $page) {
  477.                 $translations $repository->findTranslations($page);
  478.                 foreach ($translations as $locale => $fields) {
  479.                     foreach ($urlSegments as $segment) {
  480.                         $transSlug explode('/'$fields['slug']);
  481.                         foreach ($transSlug as $transSlugSegment) {
  482.                             $this->debug($debug'<br/>['.$locale.']'.$segment.':'.$transSlugSegment);
  483.                             if ($segment === $transSlugSegment) {
  484.                                 $this->debug($debug' <strong> - Match ***</strong>');
  485.                                 $diffrentLanguagesWithSameSlug[$locale] = 0;
  486.                                 $setLocale $locale;
  487.                                 //wasnt sure which was the correct method - keeps changing!
  488.                                 $request->getSession()->set('_locale'$setLocale);
  489.                                 $request->setLocale($setLocale);
  490.                                 if ($debug) {
  491.                                     $this->debug($debug'<p><strong>*** REFRESHING PAGE IN ['.$setLocale.'] - autoswitching ***</strong></p>');
  492.                                 } elseif ($request->query->has('_locale')) {
  493.                                     $this->debug($debug'<br/>Already Redirected - preventing loop');
  494.                                 } else {
  495.                                     return $this->redirect('/'.$slug.'?_locale='.$setLocale);
  496.                                 }
  497.                             }
  498.                         }
  499.                     }
  500.                 }
  501.             }
  502.             // check if en from different locale
  503.             foreach ($pageAll as $page) {
  504.                 $page->setTranslatableLocale('en');
  505.                 $em->refresh($page);
  506.                 foreach ($urlSegments as $segment) {
  507.                     $locale 'en';
  508.                     $transSlug explode('/'$page->getSlug());
  509.                     foreach ($transSlug as $transSlugSegment) {
  510.                         $this->debug($debug'<br/>['.$locale.']'.$segment.':'.$transSlugSegment);
  511.                         if ($segment === $transSlugSegment) {
  512.                             $this->debug($debug' <strong> - Match ***</strong>');
  513.                             $diffrentLanguagesWithSameSlug[$locale] = 0;
  514.                             $setLocale $locale;
  515.                             // wasnt sure which was the correct method - keeps changing!
  516.                             $request->getSession()->set('_locale'$setLocale);
  517.                             $request->setLocale($setLocale);
  518.                             if ($debug) {
  519.                                 $this->debug($debug'<p><strong>*** REFRESHING PAGE IN ['.$setLocale.'] - autoswitching ***</strong></p>');
  520.                             } elseif ($request->query->has('_locale')) {
  521.                                 $this->debug($debug'<br/>Already Redirected - preventing loop');
  522.                             } else {
  523.                                 return $this->redirect('/'.$slug.'?_locale='.$setLocale);
  524.                             }
  525.                         }
  526.                     }
  527.                 }
  528.             }
  529.         } // end if($multilingual)
  530.         // return new Response('<p>End - showing 404 page</p>');
  531.         throw $this->createNotFoundException('PCGC - Route not matched: showing 404 page');
  532.     }
  533.     public function renderPageWithURLComponents($request$confirmedPage$slug$cmsComponentArray)
  534.     {
  535.         $em $this->getDoctrine()->getManager();
  536.         $debug = (bool) $request->query->has('_debug');
  537.         $this->debug($debug'<br/>looking for components:<br/>');
  538.         $pageSlugParametersArray $this->findPageSlugParameters($confirmedPage->getSlug());
  539.         if ($debug) {
  540.             $this->debug($debug'Current URL components to match<br/>');
  541.             print_r($pageSlugParametersArray);
  542.             $this->debug($debug'<p>If more than one URL component then the last one will be checked by default ('.(is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0).' Found)</p>');
  543.         }
  544.         // extra check
  545.         $slugPieces explode('/'$slug);
  546.         $confirmedPagePieces explode('/'$confirmedPage->getSlug());
  547.         foreach ($cmsComponentArray as $cmsComponent) {
  548.             if ('' != $cmsComponent['slug']) {
  549.                 $slugCheck str_replace(' '''$cmsComponent['slug']);
  550.                 $this->debug($debug'<br/>Lookin at: '.$slugCheck);
  551.                 if ($slugCheck == '{'.end($pageSlugParametersArray).'}') {
  552.                     if ($debug) {
  553.                         $this->debug($debug' - Matched<br/>');
  554.                         print_r($cmsComponent);
  555.                     }
  556.                     $slugKey array_search('{'.end($pageSlugParametersArray).'}'$confirmedPagePieces);
  557.                     if (!is_numeric($slugKey)) {
  558.                         $this->debug($debug'<p>Oh No! -Key not found for "{'.end($pageSlugParametersArray).'}" in '.$confirmedPage->getSlug().'</p>');
  559.                     } else {
  560.                         $this->debug($debug"<p>Using the slug '".$slugPieces[$slugKey]."' on ".stripslashes($cmsComponent['bundle']).':'.$cmsComponent['slugEntity'].' </p>');
  561.                     }
  562.                     $component_find_slug $slugPieces[$slugKey];
  563.                     $pageComponents $this->getComponentData($debug$cmsComponentArray$confirmedPage->getComponents(), $request$confirmedPage->getId(), $component_find_slug$slugPieces$pageSlugParametersArray);
  564.                     return [
  565.                         'page' => $confirmedPage,
  566.                         'slug' => $slug,
  567.                         'pageComponents' => $pageComponents,
  568.                     ];
  569.                 }
  570.             }
  571.         }
  572.     }
  573.     public function getComponentData($debug$cmsComponentArray$pageComponents$request$confirmedPageId$component_find_slug null$slugPieces = [], $pageSlugParametersArray = [])
  574.     {
  575.         if ($debug) {
  576.             $this->debug($debug'<pre>');
  577.             $this->debug($debug'<strong>AVAILABLE COMPONENTS:</strong><br/>');
  578.             $this->debug($debug"<table cellpadding='10' width='100%'>");
  579.             $this->debug($debug"<tr style='border-bottom:1px solid #666; font-size:12px'><th>Name</th><th>Slug</th><th>SlugEntity</th><th>Route</th><th>Type</th><th>Bundle</th><tr>");
  580.             foreach ($cmsComponentArray as $com) {
  581.                 $this->debug($debug"<tr style='border-top:1px dashed #666; font-size:12px'>");
  582.                 $this->debug($debug"<td style='white-space:nowrap; padding-top:5px; padding-bottom:5px'>".$com['name'].'</td>');
  583.                 $this->debug($debug"<td style='white-space:nowrap'>".$com['slug'].'</td>');
  584.                 $this->debug($debug"<td style='white-space:nowrap'>".$com['slugEntity'].'</td>');
  585.                 $this->debug($debug"<td style='white-space:nowrap'>".$com['route'].'</td>');
  586.                 $this->debug($debug"<td style='white-space:nowrap'>".$com['componentType'].'</td>');
  587.                 $this->debug($debug"<td style='white-space:nowrap'>".$com['bundle'].'</td>');
  588.                 $this->debug($debug'<tr>');
  589.             }
  590.             $this->debug($debug'</table>');
  591.             $this->debug($debug'</pre>');
  592.             $this->debug($debug'<pre>');
  593.             $this->debug($debug'<strong>ACTIVE PAGE COMPONENTS:</strong><br/>');
  594.             $this->debug($debug"<table cellpadding='10' width='100%'>");
  595.             $this->debug($debug"<tr style='border-bottom:1px solid #666; font-size:12px'><th>Position</th><th>Route</th><tr>");
  596.             foreach ($pageComponents as $com) {
  597.                 $this->debug($debug"<tr style='border-top:1px dashed #666;  font-size:12px'>");
  598.                 $this->debug($debug"<td style='white-space:nowrap; padding-top:5px; padding-bottom:5px'>".$com['position'].'</td>');
  599.                 $this->debug($debug"<td style='white-space:nowrap'>".$com['route'].'</td>');
  600.             }
  601.             $this->debug($debug'</table>');
  602.             $this->debug($debug'</pre>');
  603.         }
  604.         $pageComponentsReturn = [];
  605.         // Find out which URL segments are dynamic by removing
  606.         // preceeding segments (parent and page)
  607.         $totalSlug is_countable($slugPieces) ? count($slugPieces) : 0;
  608.         $totalPara is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0;
  609.         $diff $totalSlug $totalPara;
  610.         for ($i 0$i $diff; ++$i) {
  611.             unset($slugPieces[$i]);
  612.         }
  613.         $slugPieces array_values($slugPieces);
  614.         $this->debug($debug'<pre>');
  615.         $this->debug($debug'<p><strong>COMPONENT LINKING</strong></p>');
  616.         // Workout extra segments - these will have no route
  617.         // and componentType = 'segment'
  618.         $extraUrlSegments $pageSlugParametersArray;
  619.         if ((is_countable($pageSlugParametersArray) ? count($pageSlugParametersArray) : 0) > 1) {
  620.             unset($extraUrlSegments[(is_countable($extraUrlSegments) ? count($extraUrlSegments) : 0) - 1], $slugPieces[count($slugPieces) - 1]);
  621.             $extraUrlSegments array_values($extraUrlSegments);
  622.             $slugPieces array_values($slugPieces);
  623.             $this->debug($debug'<p>SEGMENT ONLY ('.count($extraUrlSegments).' found)</p>');
  624.             // $this->debug($debug, "<br/>The next 2 array keys and values should match up");
  625.             // $this->debug($debug, "<br/>".print_r($extraUrlSegments, true));
  626.             // $this->debug($debug, "<br/>".print_r($slugPieces, true));
  627.             foreach ($extraUrlSegments as $index => $segment) {
  628.                 $comkey $this->searchArrayKeyVal('slug''{'.$segment.'}'$cmsComponentArray);
  629.                 if (is_numeric($comkey)) {
  630.                     $entity $this->getEntityData(['component' => $cmsComponentArray[$comkey], 'slug' => $slugPieces[$index]], $request$debug);
  631.                     $entityId $entity->getId();
  632.                     if ($entityId) {
  633.                         $pageComponentsReturn[] = [
  634.                             'position' => null,
  635.                             'urlKey' => $cmsComponentArray[$comkey]['slugEntity'],
  636.                             'urlValue' => $entityId,
  637.                             'data' => null,
  638.                             'entity' => $entity,
  639.                         ];
  640.                     }
  641.                 } else {
  642.                     $this->debug($debug"<p>Dynamic Slug '".$slugPieces[$index]."' for URL Annotation '".$segment."' NOT FOUND - but can continue, you should check your routes/link</p>");
  643.                 }
  644.             }
  645.         }
  646.         // Check all page components
  647.         $comCount 0;
  648.         foreach ($pageComponents as $pageComponent) {
  649.             if (null != $pageComponent['route']) {
  650.                 ++$comCount;
  651.                 $this->debug($debug'<p>------------------------------</p>');
  652.                 $this->debug($debug'<p>COMPONENT '.$comCount.'</p>');
  653.                 // found pagecomponent
  654.                 $comkey $this->searchArrayKeyVal('route'$pageComponent['route'], $cmsComponentArray);
  655.                 if (!is_numeric($comkey)) {
  656.                     $this->debug($debug'<p>The component <strong>'.$pageComponent['route'].'</strong> not found - has it been deleted?</p>');
  657.                     $pageComponentsReturn[] = [
  658.                         'position' => $pageComponent['position'],
  659.                         'urlKey' => null,
  660.                         'urlValue' => null,
  661.                         'data' => '',
  662.                         'entity' => null,
  663.                     ];
  664.                 } else {
  665.                     $this->debug($debug'<p>Comkey (#'.$comkey.') found for = '.$pageComponent['route']);
  666.                     $action $this->routeToControllerName($cmsComponentArray[$comkey]['route']);
  667.                     $this->debug($debug'<br/>Controller = '.$cmsComponentArray[$comkey]['route'].'</p>');
  668.                     // Non-URL reliant (slugless) component
  669.                     if (null == $cmsComponentArray[$comkey]['slug']) {
  670.                         $this->debug($debug'<p>SLUGLESS:<br/>RENDERING CONTROLLER into  = <strong>'.$action['_controller'].'</strong></p>');
  671.                         // fetch component data
  672.                         $response $this->forward($action['_controller'], ['request' => $request'pageId' => $confirmedPageId]);
  673.                         $pageComponentsReturn[] = [
  674.                             'position' => $pageComponent['position'],
  675.                             'urlKey' => null,
  676.                             'urlValue' => null,
  677.                             'data' => $response->getContent(),
  678.                             'entity' => null,
  679.                         ];
  680.                     } else {
  681.                         // URL Component found
  682.                         $removal = ['{''}']; //used for str_replace
  683.                         $controllerSlug str_replace($removal''$cmsComponentArray[$comkey]['slug']);
  684.                         // Get entityID for getMethodRouterAction - used to assist with locale/translation switching
  685.                         $entity $this->getEntityData(['component' => $cmsComponentArray[$comkey], 'slug' => $component_find_slug], $request$debug);
  686.                         $entityId $entity->getId();
  687.                         // fetch component data
  688.                         $this->debug($debug'<p>SLUG REQUIRED:<br/>RENDERING CONTROLLER = <strong>'.$action['_controller'].'</strong></p>');
  689.                         $response $this->forward($action['_controller'], ['request' => $request,  'pageId' => $confirmedPageId$controllerSlug => $component_find_slug]);
  690.                         $pageComponentsReturn[] = [
  691.                             'position' => $pageComponent['position'],
  692.                             'urlKey' => $cmsComponentArray[$comkey]['slugEntity'],
  693.                             'urlValue' => $entityId,
  694.                             'data' => $response->getContent(),
  695.                             'entity' => $entity,
  696.                         ];
  697.                     }
  698.                 } // end if(!is_numeric($comkey)
  699.             }
  700.         }
  701.         $this->debug($debug'</pre>');
  702.         return $pageComponentsReturn;
  703.     }
  704.     public function getEntityData($data$request$debug)
  705.     {
  706.         $em $this->getDoctrine()->getManager();
  707.         $locale $request->getLocale();
  708.         $queryEntity str_replace('\\'''$data['component']['bundle'].':'.$data['component']['slugEntity']);
  709.         $queryEntity str_replace('/'''$queryEntity);
  710.         $this->debug($debug'<p>ENTITY QUERY - '.$queryEntity);
  711.         if ('en' != $locale) {
  712.             $entity $em->getRepository($queryEntity)->findSlugWithLocale($data['slug'], $locale);
  713.             $this->debug($debug'->findSlugWithLocale(<strong>'.$data['slug'].'</strong>, <strong>'.$locale.'</strong>)');
  714.         } else {
  715.             $entity $em->getRepository($queryEntity)->findOneBySlug($data['slug']);
  716.             $this->debug($debug'->findOneBySlug(<strong>'.$data['slug'].'</strong>)');
  717.         }
  718.         if ($entity) {
  719.             $this->debug($debug'<br/>RESULT: EntityId =<strong>'.$entity->getId().'</strong></p>');
  720.             return $entity;
  721.         }
  722.         return false;
  723.     }
  724.     public function searchArrayKeyVal($sKey$id$array)
  725.     {
  726.         foreach ($array as $key => $val) {
  727.             if ($val[$sKey] == $id) {
  728.                 return $key;
  729.             }
  730.         }
  731.         foreach ($array as $key => $val) {
  732.             if (strtolower($val[$sKey]) === strtolower($id)) {
  733.                 return $key;
  734.             }
  735.         }
  736.         return false;
  737.     }
  738.     public function isJson($string)
  739.     {
  740.         try {
  741.             json_decode($stringfalse512JSON_THROW_ON_ERROR);
  742.             return true;
  743.         } catch (JsonException $jsonException) {
  744.             return false;
  745.         }
  746.     }
  747.     // function to compare entities and returns common setters
  748.     public function getSetters($entity$entity2)
  749.     {
  750.         $classMethods get_class_methods($entity);
  751.         $classMethods2 get_class_methods($entity2);
  752.         $settersArray = [];
  753.         foreach ($classMethods as $classMethod) {
  754.             if ('set' == substr($classMethod03)) {
  755.                 foreach ($classMethods2 as $classMethod2) {
  756.                     if ('set' == substr($classMethod203) && $classMethod == $classMethod2) {
  757.                         $settersArray[] = $classMethod2;
  758.                     }
  759.                 }
  760.             }
  761.         }
  762.         return $settersArray;
  763.     }
  764.     // THIS ROUTE MUST BE THE VERY LAST ROUTE LOADED
  765.     /**
  766.      * @Route("/", name="home", defaults={"slug": "home"}))
  767.      * @Route("/{slug}", name="router", requirements={"slug": ".+"})
  768.      *
  769.      * @param mixed $slug
  770.      */
  771.     public function routerAction(Request $request$slug)
  772.     {
  773.         $session $request->getSession();
  774.         $em $this->getDoctrine()->getManager();
  775.         $slugCache $em->getRepository('App:Page')->findAllByLocale($request->getLocale());
  776.         $cacheDriver $this->container->get('doctrine_cache.providers.arraycache');
  777.         $cacheDriver->save('slugCache'$slugCache);
  778.         $debug $request->query->has('_debug');
  779.         $this->debug($debug'Current Locale -'.$request->getLocale().' | request Locale -'.$request->query->get('_locale'));
  780.         if ($request->query->has('_locale')) {
  781.             $this->debug($debug'<p>CHANGING LOCALE</p>');
  782.             if ($request->getLocale() != $request->query->get('_locale')) {
  783.                 $session->set('_locale'$request->query->get('_locale'));
  784.                 $request->setLocale($session->get('_locale'$request->query->get('_locale')));
  785.                 return $this->redirect('/'.$slug);
  786.             }
  787.         }
  788.         $pageData $this->routeMatcherV2($request$slug);
  789.         // REDIRECT CHECKER
  790.         $this->debug($debug'Checking for redirects...');
  791.         foreach ($pageData['pageComponents'] as $pageComponent) {
  792.             $redirectCheck $pageComponent['data'];
  793.             if ($this->isJson($redirectCheck)) {
  794.                 $decoded json_decode($redirectCheckfalse512JSON_THROW_ON_ERROR);
  795.                 if (property_exists($decoded'componentRedirect') && null !== $decoded->componentRedirect) {
  796.                     $this->debug($debug'Redirect found ... will goto '.$decoded->componentRedirect);
  797.                     if (!$debug) {
  798.                         return $this->redirect($decoded->componentRedirect);
  799.                     }
  800.                 }
  801.             }
  802.         }
  803.         if (is_array($pageData)) {
  804.             $longUrl 'page.php?Page='.$pageData['page']->getId();
  805.             if (array_key_exists('pageComponents'$pageData) && null != $pageData['pageComponents']) {
  806.                 foreach ($pageData['pageComponents'] as $component) {
  807.                     if (array_key_exists('urlKey'$component) && null != $component['urlKey']) {
  808.                         $longUrl .= '&'.$component['urlKey'].'='.$component['urlValue'];
  809.                     }
  810.                 }
  811.             }
  812.             $pageAllowed $this->pageChecks($pageData['page']);
  813.             if (false == $pageAllowed) {
  814.                 throw $this->createNotFoundException('PCGC: Page Checks for pageId "'.$pageData['page']->getId().'" has failed (disabled, before viewdate ect...) - showing 404');
  815.             }
  816.             // HTML Blocks
  817.             $htmlblocks = [];
  818.             $assignedHtmlblocks $pageData['page']->getHtmlblocks();
  819.             if ((is_countable($assignedHtmlblocks) ? count($assignedHtmlblocks) : 0) > 0) {
  820.                 $allHtmlBlocks $em->getRepository('App:HtmlBlocks')->findBy(['deleted' => false]);
  821.                 foreach ($assignedHtmlblocks as $assignedblock) {
  822.                     foreach ($allHtmlBlocks as $allHtmlBlock) {
  823.                         if ($assignedblock['blockId'] == $allHtmlBlock->getId()) {
  824.                             $htmlblocks[] = [
  825.                                 'blockId' => $allHtmlBlock->getId(),
  826.                                 'position' => $assignedblock['position'],
  827.                                 'data' => $allHtmlBlock->getHtml(),
  828.                             ];
  829.                         }
  830.                     }
  831.                 }
  832.             }
  833.             $pageMeta $pageData['page'];
  834.             // replace metatitle if empty
  835.             if ('' == $pageData['page']->getMetatitle()) {
  836.                 $pageMeta->setMetatitle($pageData['page']->getTitle());
  837.             }
  838.             // replace metatitles if exist on components
  839.             foreach ($pageData['pageComponents'] as $pageComp) {
  840.                 $pageMeta $this->generateAndModifyMetaDataTags($pageData['page'], $pageComp['entity']);
  841.             }
  842.             return $this->render('@theme/templates/'.$pageData['page']->getTemplate()->getTemplateFile(), [
  843.                 'page' => $pageMeta,
  844.                 'slug' => $pageData['slug'],
  845.                 'pageComponents' => $pageData['pageComponents'],
  846.                 'pageHtmlBlocks' => $htmlblocks,
  847.                 'longUrl' => strtolower($longUrl),
  848.             ]);
  849.         }   // this will be a redirect
  850.         return $pageData;
  851.     }
  852.     private function debug(bool $debug$message): void
  853.     {
  854.         if ($debug) {
  855.             echo $message;
  856.         }
  857.     }
  858. }