<?php
namespace MLDev\PublicationBundle\Controller;
use Doctrine\ORM\NoResultException;
use MLDev\BaseBundle\Controller\FrontController;
use MLDev\BaseBundle\Entity\Page;
use MLDev\BaseBundle\Service\PageManager;
use MLDev\PublicationBundle\Entity\Item;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class ItemController
* @package MLDev\PublicationBundle\Controller
*/
class ItemController extends FrontController
{
/**
* @Route("/{uri}/{alias}-publication-{id}.html", name="mldev-front-publication-show", requirements={"uri":".*", "alias":".*", "id":"\d+"})
*/
public function show(PageManager $pageManager, Request $request, Item $item, string $uri, string $alias): Response
{
// validate request and redirect to validated url
if (($valid = $this->validateRequest($item, $request)) && $valid instanceof Response) {
return $valid;
}
try {
$page = $this->getDoctrine()->getRepository(Page::class)->getPageByUri($uri);
} catch (NoResultException $exception) {
throw $this->createNotFoundException('Not found', $exception);
}
$url = $this->getUrlByEntity($item);
$virtualChild = $pageManager->createVirtualChildEntity(
$item->getCategory()->getPage(),
$item->getName(),
$item->getAlias(),
$url
);
$virtualChild->setSeoInfo(
$item->getSeoInfo()
);
$otherLastThreeQueryBuilder = $this->getDoctrine()->getRepository(Item::class)->getOtherLastThreeQueryBuilder(
$item->getCategory()->getId()
);
$otherLastThreeQueryBuilder->andWhere(
$otherLastThreeQueryBuilder->expr()->neq('item.id', $item->getId())
);
return $this->renderCustomTemplate($virtualChild, '@MLDevPublication/templates/default.html.twig', [
'item' => $item,
'other_news_list' => $otherLastThreeQueryBuilder->getQuery()->getResult()
]);
}
/**
* @return boolean|Response
*/
private function validateRequest(Item $entity, Request $request)
{
$url = $this->getUrlByEntity($entity);
if ($request->getPathInfo() !== $url) {
return $this->redirect($url . ($request->getQueryString() ? '?' . $request->getQueryString() : ''));
}
return true;
}
private function getUrlByEntity(Item $entity): string
{
return $this->generateUrl('mldev-front-publication-show', [
'uri' => str_replace('/', '', $entity->getCategory()->getPage()->getUri()),
'alias' => $entity->getAlias(),
'id' => $entity->getId(),
]);
}
}