src/Controller/Web/BlogController.php line 202

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Web;
  3. use App\Entity\Articles;
  4. use App\Entity\Pages;
  5. use App\Entity\Sitewide;
  6. use App\Entity\Tags;
  7. use DateTime;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Eko\FeedBundle\Feed\FeedManager;
  10. use Exception;
  11. use Pagerfanta\Adapter\ArrayAdapter;
  12. use Pagerfanta\Pagerfanta;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Cookie;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. class BlogController extends AbstractController
  20. {
  21.     /**
  22.      * @var Sitewide|object|null
  23.      */
  24.     private $sitewide;
  25.     /**
  26.      * @var EntityManagerInterface
  27.      */
  28.     private EntityManagerInterface $em;
  29.     /**
  30.      * DefaultController constructor.
  31.      *
  32.      * @param EntityManagerInterface $em
  33.      */
  34.     public function __construct(EntityManagerInterface $em)
  35.     {
  36.         $this->em $em;
  37.         $this->sitewide $this->em->getRepository(Sitewide::class)->findOneBy([], ['id' => 'asc']);
  38.     }
  39.     /**
  40.      * @Route("/blog/{slug}/{date}", name="Blog_Article", requirements={
  41.      *      "date" = "\d{8}"
  42.      * })
  43.      * @param Request $request
  44.      * @param $slug
  45.      * @param $date
  46.      *
  47.      * @return RedirectResponse|Response
  48.      * @throws Exception
  49.      */
  50.     public function blogAction(Request $request$slug$date)
  51.     {
  52.         $session $request->getSession();
  53.         $mainNav $this->em->getRepository(Pages::class)->findPubMainNavPageNames();
  54.         $otherNav $this->em->getRepository(Pages::class)->findPubOtherNavPageNames();
  55.         $pageEntity $this->em->getRepository(Pages::class)->findOneBy(['name' => 'Blog'], []);
  56.         $articles $this->em->getRepository(Articles::class)->findBy(['publish' => true],
  57.             ['datePublished' => 'DESC']);
  58.         $articleEntity $this->em->getRepository(Articles::class)->findOneBy(['slug' => $slug], []);
  59.         // if there is a slug but no article
  60.         if (($slug != '') && !$articleEntity) {
  61.             $session->getFlashBag()->add(
  62.                 'error',
  63.                 'Sorry!! We couldn\'t find the blog you were looking for. You can see all our blogs below.'
  64.             );
  65.             return $this->redirect($this->generateUrl('blog'), 301);
  66.         }
  67.         // if there is an article, but it hasn't been published
  68.         if (!$articleEntity->getPublish()) {
  69.             //return 'This blog is not published';
  70.             if (count($articleEntity->getTags()) == 0) {
  71.                 //if blog has no tag
  72.                 $session->getFlashBag()->add(
  73.                     'error',
  74.                     'Sorry!! We couldn\'t find the blog you were looking for. You can see all our blogs below.'
  75.                 );
  76.                 return $this->redirect($this->generateUrl('blog'), 301);
  77.             } else { // if blog has tag
  78.                 $i 0;
  79.                 $tagName null;
  80.                 foreach ($articleEntity->getTags() as $tag) {
  81.                     if ($i 1) {
  82.                         $tagName $tag->getName();
  83.                     }
  84.                     $i++;
  85.                 }
  86.                 $session->getFlashBag()->add(
  87.                     'error',
  88.                     'Sorry!! We couldn\'t find the blog you were looking for. You can see other blogs tagged '.$tagName.' below.'
  89.                 );
  90.                 return $this->redirect(
  91.                     $this->generateUrl('blog_tag', [
  92.                         'tag' => $tagName,
  93.                     ]),
  94.                     301
  95.                 );
  96.             }
  97.         }
  98.         //set cookies permission cookie
  99.         $cookies $request->cookies->get('cookies');
  100.         if (!$cookies) {
  101.             $cookie = new Cookie('cookies''true'time() + 3600 24 90);
  102.             $response = new Response();
  103.             $response->headers->setCookie($cookie);
  104.             $response->sendHeaders();
  105.         }
  106.         // increase count for a view
  107.         $articlesViews $articleEntity->getCount();
  108.         $articlesViews++;
  109.         $articleEntity->setCount($articlesViews);
  110.         $this->em->flush();
  111.         // set metaKeywords
  112.         $article $articleEntity->getTitle().' ';
  113.         $article .= $articleEntity->getContent().' ';
  114.         $metaKeywords $this->extractCommonWords2(strip_tags($article));
  115.         foreach ($metaKeywords as $key => $value) {
  116.             $metaKeywords[] = $key;
  117.             unset($metaKeywords[$key]);
  118.         }
  119.         $pageEntity->setMetaKeywords(implode(','$metaKeywords));
  120.         $monthsArray = [];
  121.         foreach ($articles as $value) {
  122.             $monthYear $value->getDatePublished()->format('\0\1 M Y');
  123.             $monthsArray[$monthYear][] = $value->getId();
  124.         }
  125.         $url $request->headers->get('referer');
  126.         return $this->render('web/Default/blog.html.twig', [
  127.             'pageEntity' => $pageEntity,
  128.             'sitewide' => $this->sitewide,
  129.             'mainNav' => $mainNav,
  130.             'otherNav' => $otherNav,
  131.             'article' => $articleEntity,
  132.             'tags' => $this->fetchTagsArray(),
  133.             'monthsArray' => $monthsArray,
  134.             'url' => $url,
  135.         ]);
  136.     }
  137.     /**
  138.      * * @Route("/blog/{year}/{month}/{page}", name="blog_month", defaults={
  139.      *      "date" = "",
  140.      *      "tag" = "",
  141.      *      "page" = "1"
  142.      * }, requirements={
  143.      *      "month" = "\d{2}",
  144.      *      "year" = "\d{4}",
  145.      *      "page" = "\d+",
  146.      *      "date" = "\d{8}"
  147.      * })
  148.      * @Route("/blog/{page}", name="blog", defaults={
  149.      *      "date" = "",
  150.      *      "year" = "",
  151.      *      "month" = "",
  152.      *      "tag" = "",
  153.      *      "page" = "1"
  154.      * }, requirements={
  155.      *      "month" = "\d{2}",
  156.      *      "year" = "\d{4}",
  157.      *      "page" = "\d+",
  158.      *      "date" = "\d{8}"
  159.      * }, options={"sitemap" = true})
  160.      * @Route("/blog/{tag}/{page}", name="blog_tag", defaults={
  161.      *      "date" = "",
  162.      *      "year" = "",
  163.      *      "month" = "",
  164.      *      "page" = "1"
  165.      * }, requirements={
  166.      *      "month" = "\d{2}",
  167.      *      "year" = "\d{4}",
  168.      *      "page" = "\d+",
  169.      *      "date" = "\d{8}"
  170.      * })
  171.      * @param Request $request
  172.      * @param $page
  173.      * @param $date
  174.      * @param $month
  175.      * @param $year
  176.      * @param $tag
  177.      *
  178.      * @return RedirectResponse|Response
  179.      * @throws Exception
  180.      */
  181.     public function blogsAction(Request $request$page$date$month$year$tag)
  182.     {
  183.         $mainNav $this->em->getRepository(Pages::class)->findPubMainNavPageNames();
  184.         $otherNav $this->em->getRepository(Pages::class)->findPubOtherNavPageNames();
  185.         $pageEntity $this->em->getRepository(Pages::class)->findOneBy(['name' => 'Blog'], []);
  186.         $articles $this->em->getRepository(Articles::class)->findBy(['publish' => true],
  187.             ['datePublished' => 'DESC']);
  188.         $articlesRep $this->em->getRepository(Articles::class);
  189.         $tagEntity $this->em->getRepository(Tags::class)->findOneBy(['slug' => $tag], []);
  190.         // redirect if no tag exists
  191.         if ($tag) {
  192.             if (!$tagEntity) {
  193.                 $request->getSession()->getFlashBag()->add(
  194.                     'error',
  195.                     'Sorry!! We couldn\'t find the tag you were looking for. You can see all our blogs below.'
  196.                 );
  197.                 return $this->redirect($this->generateUrl('blog'), 301);
  198.             }
  199.         }
  200.         //set cookies permission cookie
  201.         $cookies $request->cookies->get('cookies');
  202.         if (!$cookies) {
  203.             $cookie = new Cookie('cookies''true'time() + 3600 24 90);
  204.             $response = new Response();
  205.             $response->headers->setCookie($cookie);
  206.             $response->sendHeaders();
  207.         }
  208.         $monthsArray = [];
  209.         foreach ($articles as $key => $value) {
  210.             $monthYear $value->getDatePublished()->format('\0\1 M Y');
  211.             $monthsArray[$monthYear][] = $value->getId();
  212.         }
  213.         $queryBuilder $articlesRep->createQueryBuilder('a')
  214.             ->where('a.publish = true')
  215.             ->select('a')
  216.             ->leftjoin('a.tags''t')
  217.             ->orderby('a.datePublished''desc');
  218.         if ($tag != null) {
  219.             $queryBuilder $queryBuilder->andwhere('t.slug = :tag')->setParameter('tag'$tag);
  220.         }
  221.         if (($month !== '') && ($year !== '')) {
  222.             $monthStart = new DateTime($month.'/01/'.$year);
  223.             $monthEnd = new DateTime(date("m/t/Y"strtotime($month.'/01/'.$year)));
  224.             $queryBuilder $queryBuilder->andwhere('a.datePublished >= :monthStart')->setParameter(
  225.                 'monthStart',
  226.                 $monthStart
  227.             );
  228.             $queryBuilder $queryBuilder->andwhere('a.datePublished <= :monthEnd')->setParameter(
  229.                 'monthEnd',
  230.                 $monthEnd
  231.             );
  232.         }
  233.         $articlesQuery $queryBuilder->getQuery();
  234.         $articlesArray $articlesQuery->getResult();
  235.         $adapter = new ArrayAdapter($articlesArray);
  236.         //$adapter = new DoctrineORMAdapter($queryBuilder);
  237.         $pagerfanta = new Pagerfanta($adapter);
  238.         $pagerfanta->setMaxPerPage(8); // 10 by default
  239.         $pagerfanta->setCurrentPage($page);
  240.         $nbResults $pagerfanta->getNbResults();
  241.         $url $request->headers->get('referer');
  242.         return $this->render('web/Default/blogs.html.twig', [
  243.             'pageEntity' => $pageEntity,
  244.             'sitewide' => $this->sitewide,
  245.             'mainNav' => $mainNav,
  246.             'otherNav' => $otherNav,
  247.             'articles' => $pagerfanta,
  248.             'page' => $page,
  249.             'nbResults' => $nbResults,
  250.             'tags' => $this->fetchTagsArray(),
  251.             'tag' => $tagEntity,
  252.             'monthsArray' => $monthsArray,
  253.             'monthYear' => $month.'/01/'.$year,
  254.             'url' => $url,
  255.         ]);
  256.     }
  257.     private function fetchTagsArray(): array
  258.     {
  259.         $tags $this->em->getRepository(Tags::class)->findBy([], ['name' => 'asc']);
  260.         $tagsArray = [];
  261.         /** @var Tags $value */
  262.         foreach ($tags as $value) {
  263.             $i 1;
  264.             foreach ($value->getArticles() as $keyart => $valart) {
  265.                 if ($valart->getPublish()) {
  266.                     $tagsArray[$value->getName()] = ['slug' => $value->getSlug()];
  267.                     $tagsArray[$value->getName()]['articles'] = $i;
  268.                     $i++;
  269.                 }
  270.             }
  271.         }
  272.         ksort($tagsArray);
  273.         return $tagsArray;
  274.     }
  275.     private function extractCommonWords2(
  276.         $string
  277.     ): array {
  278.         // maybe take out phrases in first pass, and individual words in second pass, if it is possible
  279.         $findWords = [
  280.             'account',
  281.             'ad',
  282.             'ado',
  283.             'adobe',
  284.             'adobe-air',
  285.             'akamai',
  286.             'amazon',
  287.             'analyst',
  288.             'android',
  289.             'desktop',
  290.         ];
  291.         $string preg_replace('/\s\s+/i'' '$string); // replace whitespace - why do we do this?
  292.         $string trim($string); // trim the string
  293.         $string preg_replace(
  294.             '/[^a-zA-Z0-9 -]/',
  295.             '',
  296.             $string
  297.         ); // only take alphanumerical characters, but keep the spaces and dashes too…
  298.         $string strtolower($string); // make it lowercase
  299.         // preg_match_all('/\s.*?\s/i', $string, $matchWords); //somehwere here escapes out dashes
  300.         preg_match_all(
  301.             "/(?(?=[\-\w'])(?<![\-\w'])|(?<![^\-\w']))([\-\w']+)(?(?<=[\-\w'])(?![\-\w'])|(?![^\-\w']))/i",
  302.             $string,
  303.             $matchWords
  304.         ); //somehwere here escapes out dashes
  305.         $matchWords $matchWords[0];
  306.         $matches = [];
  307.         foreach ($matchWords as $item) {
  308.             if (in_array(strtolower(trim($item)), $findWords)) {
  309.                 $matches[] = $item;
  310.             }
  311.         }
  312.         $wordCountArr = [];
  313.         if (is_array($matches)) {
  314.             foreach ($matches as $val) {
  315.                 $val strtolower(trim($val));
  316.                 if (isset($wordCountArr[$val])) {
  317.                     $wordCountArr[$val]++;
  318.                 } else {
  319.                     $wordCountArr[$val] = 1;
  320.                 }
  321.             }
  322.         }
  323.         arsort($wordCountArr);
  324.         $wordCountArr array_slice($wordCountArr010);
  325.         return $wordCountArr;
  326.     }
  327.     /**
  328.      * Generate the article feed
  329.      * @Route("/blog-feed/{tag}", name="Blog_Feed")
  330.      *
  331.      * @param FeedManager $feedManager
  332.      * @param $tag
  333.      *
  334.      * @return Response XML Feed
  335.      */
  336.     public function feedAction(
  337.         FeedManager $feedManager,
  338.         $tag
  339.     ): Response {
  340.         $articles $this->em->getRepository(Articles::class)->findAll();
  341.         $feed $feedManager->get('article');
  342.         $feed->addFromArray($articles);
  343.         return new Response($feed->render('rss')); // or 'atom'
  344.     }
  345. }