src/Repository/ContentRepository.php line 83

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Repository;
  4. use App\Entity\Content\Content;
  5. use App\Entity\Menu\Item;
  6. use App\Entity\User\User;
  7. use App\Pagination\Paginator;
  8. use App\Service\FavoriteContentManager;
  9. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  10. use Doctrine\Persistence\ManagerRegistry;
  11. use Doctrine\ORM\QueryBuilder;
  12. use App\Exception\Exception;
  13. use App\Exception\RuntimeException;
  14. use DateTime;
  15. use DateTimeZone;
  16. use Doctrine\DBAL\Connection;
  17. use Doctrine\DBAL\ParameterType;
  18. use Doctrine\ORM\Query\Expr\OrderBy;
  19. use Doctrine\ORM\Tools\Pagination\Paginator as QueryPaginator;
  20. use Symfony\Component\Security\Core\Security;
  21. /**
  22.  * Content Repository
  23.  *
  24.  * @author  Marcin Skrzeszewski <marcin.skrzeszewski@avt.pl>
  25.  * @package App\Repository
  26.  */
  27. class ContentRepository extends ServiceEntityRepository
  28. {
  29.     protected Security $security;
  30.     protected FavoriteContentManager $favManager;
  31.     public const ORDER_CONTENT_DATE_PUBLISH_DESC = 0;
  32.     public const ORDER_CONTENT_DATE_PUBLISH_ASC = 1;
  33.     public const ORDER_CONTENT_ID_DESC = 2;
  34.     public const ORDER_CONTENT_ID_ASC = 3;
  35.     public const ORDER_CONTENT_TITLE_DESC = 4;
  36.     public const ORDER_CONTENT_TITLE_ASC = 5;
  37.     public const ORDER_CONTENT_FIELD_ID = 6;
  38.     public const ORDER = [
  39.         self::ORDER_CONTENT_DATE_PUBLISH_DESC => [
  40.             'title' => 'Data publikacji - Malejąco',
  41.             'sort' => 'publishAt',
  42.             'order' => 'DESC'
  43.         ],
  44.         self::ORDER_CONTENT_DATE_PUBLISH_ASC => [
  45.             'title' => 'Data publikacji - Rosnąco',
  46.             'sort' => 'publishAt',
  47.             'order' => 'ASC'
  48.         ],
  49.         self::ORDER_CONTENT_ID_DESC => [
  50.             'title' => 'ID - Malejąco',
  51.             'sort' => 'id',
  52.             'order' => 'DESC'
  53.         ],
  54.         self::ORDER_CONTENT_ID_ASC => [
  55.             'title' => 'ID - Rosnąco',
  56.             'sort' => 'id',
  57.             'order' => 'ASC'
  58.         ],
  59.         self::ORDER_CONTENT_TITLE_DESC => [
  60.             'title' => 'Tytuł - Malejąco',
  61.             'sort' => 'title',
  62.             'order' => 'DESC'
  63.         ],
  64.         self::ORDER_CONTENT_TITLE_ASC => [
  65.             'title' => 'Tytuł - Rosnąco',
  66.             'sort' => 'title',
  67.             'order' => 'ASC'
  68.         ],
  69.         self::ORDER_CONTENT_FIELD_ID => [
  70.             'title' => 'Kolejność wg. podanych ID',
  71.             'sort' => 'FIELD',
  72.             'order' => ''
  73.         ]
  74.     ];
  75.     public function __construct(ManagerRegistry $registry, Security $security, FavoriteContentManager $favoriteContentManager)
  76.     {
  77.         parent::__construct($registry, Content::class);
  78.         $this->security = $security;
  79.         $this->favManager = $favoriteContentManager;
  80.     }
  81.     public function getBaseQB(): QueryBuilder
  82.     {
  83.         return $this->createQueryBuilder('c')->select('c');
  84.     }
  85.     public function findPublicById(int $id): ?Content
  86.     {
  87.         $items = $this->findPublicByIds([$id]);
  88.         return $items ? current($items) : null;
  89.     }
  90.     public function findPublicByIds(array $ids, bool $restrictToMenu = true): array
  91.     {
  92.         $qb = $this->getBaseQB();
  93.         $qb = $this->getQbIds($qb, $ids);
  94.         $qb = $this->addPublicRestrictions($qb, $restrictToMenu);
  95.         return $qb->getQuery()->getResult();
  96.     }
  97.     public function findAllPaginated(int $page = 1, int $itemsPerPage = 10, array $filters = [], QueryBuilder $qb = null): Paginator
  98.     {
  99.         if ($qb == null) {
  100.             $qb = $this->getBaseQB();
  101.         }
  102.         $expr = $qb->expr();
  103.         $conn = $this->getEntityManager()->getConnection();
  104.         if (array_key_exists('order', $filters['dynamic']) && $filters['dynamic']['order'] !== null) {
  105.             $qb = $this->addOrder($qb, $filters['dynamic']['order']);
  106.         } else {
  107.             $qb = $this->addOrder($qb, self::ORDER_CONTENT_DATE_PUBLISH_DESC);
  108.         }
  109.         if (!empty($filters['dynamic']['title'])) {
  110.             $qb->andWhere('c.title LIKE :title')
  111.                 ->setParameter('title', '%'.$filters['dynamic']['title'].'%');
  112.         }
  113.         if (!empty($cats = $filters['dynamic']['categories'])) {
  114.             if (!empty($filters['dynamic']['matchCategories'])) { // Content have to match all categories
  115.                 // Get content id which matches all categories
  116.                 $sql = 'SELECT content_id, category_id, count(category_id) as categoryCount
  117.                 FROM conn_content_category
  118.                 WHERE category_id IN (?)
  119.                 GROUP BY content_id
  120.                 HAVING categoryCount >= ?';
  121.                 $values = [$cats, count($cats)];
  122.                 $types = [Connection::PARAM_INT_ARRAY, \PDO::PARAM_INT];
  123.                 $stmt = $conn->executeQuery($sql, $values, $types);
  124.                 $result = $stmt->fetchAllAssociative();
  125.                 // Apply filter
  126.                 if (empty($result)) { // force to 0 results
  127.                     $qb->andWhere('c.id = 0');
  128.                 } else {
  129.                     $catContentIds = [];
  130.                     foreach ($result as $r) {
  131.                         $catContentIds[] = $r['content_id'];
  132.                     }
  133.                     $qb->andWhere('c.id IN (:catContentIds)')
  134.                         ->setParameter('catContentIds', $catContentIds);
  135.                 }
  136.             } else { // Content have to match only one from categories
  137.                 $qb->innerJoin('c.categories', 'cc', 'WITH', 'cc.id IN (:categories)')
  138.                     ->setParameter('categories', $filters['dynamic']['categories']);
  139.             }
  140.         }
  141.         if (!empty($filters['dynamic']['types'])) {
  142.             $qb->innerJoin('c.type', 't', 'WITH', 't.id IN (:types)')
  143.                 ->setParameter('types', $filters['dynamic']['types']);
  144.         }
  145.         if (!empty($filters['dynamic']['tags'])) {
  146.             $qb->innerJoin('c.tags', 'tags', 'WITH', 'tags.id IN (:tags)')
  147.                 ->setParameter('tags', $filters['dynamic']['tags']);
  148.         }
  149.         // Favorites
  150.         if (isset($filters['dynamic']['favorites'])) {
  151.             $qb->andWhere('c.id IN (:favs)')
  152.                 ->setParameter('favs', $this->favManager->getFavoritesIds($filters['dynamic']['favorites_key']));
  153.         }
  154.         $qb = $this->addPublicRestrictions($qb);
  155.         if ($itemsPerPage > -1) {
  156.             $firstResult = ($page - 1) * $itemsPerPage;
  157.             $qb->setMaxResults($itemsPerPage);
  158.             $qb->setFirstResult($firstResult);
  159.         }
  160.         return (new Paginator($qb, $itemsPerPage))->paginate($page);
  161.     }
  162.     public function findAdminAllPaginated(int $page = 1, int $itemsPerPage = 10, array $filters = []): Paginator
  163.     {
  164.         $qb = $this->createQueryBuilder('c')
  165.             ->addSelect('c');
  166.         $expr = $qb->expr();
  167.         if (!empty($filters['static'])) {
  168.             foreach ($filters['static'] as $col => $dir) {
  169.                 $qb->orderBy("c.$col", $dir);
  170.             }
  171.         } else {
  172.             $qb->orderBy('c.id', 'DESC');
  173.         }
  174.         if (!empty($filters['dynamic']['title'])) {
  175.             $qb->andWhere(
  176.                 $expr->orX(
  177.                     $expr->like('c.title', ':title'),
  178.                     $expr->eq('c.id', ':id')
  179.                 )
  180.             );
  181.             $qb->setParameter('title', '%'.$filters['dynamic']['title'].'%')
  182.                 ->setParameter('id', $filters['dynamic']['title']);
  183.         }
  184.         if (!empty($filters['dynamic']['categories'])) {
  185.             $qb->innerJoin('c.categories', 'cc')
  186.                 ->andWhere('cc.id IN (:categories)')
  187.                 ->setParameter('categories', $filters['dynamic']['categories']);
  188.         }
  189.         if (!empty($filters['dynamic']['types'])) {
  190.             $qb->innerJoin('c.type', 't', 'WITH', 't.id IN (:types)')
  191.                 ->setParameter('types', $filters['dynamic']['types']);
  192.         }
  193.         if (!empty($filters['dynamic']['user'])) {
  194.             $qb->innerJoin('c.user', 'u', 'WITH', 'u.id IN (:user)')
  195.                 ->setParameter('user', $filters['dynamic']['user']);
  196.         }
  197.         if (!empty($filters['dynamic']['state'])) {
  198.             $qb->andWhere('c.state IN (:states)')
  199.                 ->setParameter('states', $filters['dynamic']['state']);
  200.         }
  201.         if ($itemsPerPage > -1) {
  202.             $firstResult = ($page - 1) * $itemsPerPage;
  203.             $qb->setMaxResults($itemsPerPage);
  204.             $qb->setFirstResult($firstResult);
  205.         }
  206.         return (new Paginator($qb, $itemsPerPage))->paginate($page);
  207.     }
  208.     public function findAllContentWithRoutesForGenerator(): array
  209.     {
  210.         return $this->createQueryBuilder('c')
  211.             ->select('c.id, c.alias, m.id AS menuItemId, r.name AS route')
  212.             ->innerJoin('c.menuItem', 'm')
  213.             ->innerJoin('m.routes', 'r')
  214.             ->where('c.state = :state')
  215.             ->andWhere('r.name LIKE :rname')
  216.             ->addOrderBy('c.publishAt', 'ASC')
  217.             ->setParameter('state', Content::STATE_PUBLISHED)
  218.             ->setParameter('rname', '%_single')
  219.             ->getQuery()
  220.             ->getArrayResult();
  221.     }
  222.     public function getQbChoices(?QueryBuilder $qb = null): QueryBuilder
  223.     {
  224.         if ($qb === null)
  225.             $qb = $this->getBaseQB();
  226.         $qb->select('c.id, c.title');
  227.         return $qb;
  228.     }
  229.     public function getQbIds(QueryBuilder $qb, array $ids): QueryBuilder
  230.     {
  231.         $qb->andWhere('c.id IN (:ids)')
  232.             ->setParameter('ids', $ids);
  233.         return $qb;
  234.     }
  235.     public function contentsExcludeIds(array $ids, ?QueryBuilder $qb = null): QueryBuilder
  236.     {
  237.         if (!$qb)
  238.             $qb = $this->createQueryBuilder('c');
  239.         if (!empty($ids) && !empty($ids[0])) {
  240.             $qb->andWhere('c.id NOT IN (:excludeIds)')
  241.                 ->setParameter('excludeIds', $ids);
  242.         }
  243.         return $qb;
  244.     }
  245.     public function getQbByCategoryIds(QueryBuilder $qb, array $catIds): QueryBuilder
  246.     {
  247.         $qb->innerJoin('c.categories', 'cc', 'WITH', 'cc.id IN (:catIds)')
  248.             ->setParameter('catIds', $catIds);
  249.         return $qb;
  250.     }
  251.     public function getQbByTypeIds(QueryBuilder $qb, array $typeIds): QueryBuilder
  252.     {
  253.         $qb->innerJoin('c.type', 't', 'WITH', 't.id IN (:typeIds)')
  254.             ->setParameter('typeIds', $typeIds);
  255.         return $qb;
  256.     }
  257.     public function getQbByTagIds(QueryBuilder $qb, array $tagIds): QueryBuilder
  258.     {
  259.         $qb->innerJoin('c.tags', 'tags')
  260.             ->andWhere('tags.id IN (:tagIds)')
  261.             ->setParameter('tagIds', $tagIds);
  262.         return $qb;
  263.     }
  264.     public function getQbAfterPublishDate(QueryBuilder $qb, DateTime $date): QueryBuilder
  265.     {
  266.         $qb->andWhere('c.publishAt > :afterPublishAt')
  267.             ->setParameter('afterPublishAt', $date);
  268.         return $qb;
  269.     }
  270.     public function getContentNext(Content $content): ?Content
  271.     {
  272.         $qb = $this->getQbNextPrev($content);
  273.         return $qb->getQuery()->getOneOrNullResult();
  274.     }
  275.     public function getContentPrev(Content $content): ?Content
  276.     {
  277.         $qb = $this->getQbNextPrev($content, 2);
  278.         return $qb->getQuery()->getOneOrNullResult();
  279.     }
  280.     /**
  281.      * @var int $type 1 for next, 2 for prev
  282.      */
  283.     public function getQbNextPrev(Content $content, int $type = 1): QueryBuilder
  284.     {
  285.         $qb = $this->createQueryBuilder('c')
  286.             ->andWhere('c.menuItem = :menuItem')
  287.             ->andWhere('c.id <> :id')
  288.             ->setParameter('menuItem', $content->getMenuItem()->getId())
  289.             ->setParameter('id', $content->getId());
  290.         if ($type == 1) {
  291.             $qb->andWhere('c.publishAt >= :publishAt');
  292.             $qb = $this->addOrder($qb, self::ORDER_CONTENT_DATE_PUBLISH_ASC);
  293.         } else {
  294.             $qb->andWhere('c.publishAt < :publishAt');
  295.             $qb = $this->addOrder($qb, self::ORDER_CONTENT_DATE_PUBLISH_DESC);
  296.         }
  297.         
  298.         $qb->setMaxResults(1);
  299.         $qb->setParameter('publishAt', $content->getPublishAt());
  300.         $qb = $this->addPublicRestrictions($qb);
  301.         return $qb;
  302.     }
  303.     public function addPublicRestrictions(QueryBuilder $qb, bool $restrictToMenu = true, bool $restrictUserAccess = true): QueryBuilder
  304.     {
  305.         $currentDate = new DateTime('now', new DateTimeZone('Europe/Warsaw'));
  306.         $expr = $qb->expr();
  307.         // State, date params
  308.         $qb->andWhere('c.state = :state')
  309.             ->andWhere('c.publishAt < :currentDate')
  310.             ->andWhere(
  311.                 $expr->orX(
  312.                     $expr->isNull('c.expiresAt'),
  313.                     $expr->gt('c.expiresAt', ':currentDate')
  314.                 )
  315.             )
  316.             ->setParameter('state', Content::STATE_PUBLISHED)
  317.             ->setParameter('currentDate', $currentDate);
  318.         if ($restrictToMenu)
  319.             $qb = $this->addMenuItemRestrictions($qb);
  320.         if ($restrictUserAccess)
  321.             $qb = $this->addCurrentUserAccessRestriction($qb);
  322.         return $qb;
  323.     }
  324.     public function addMenuItemRestrictions(QueryBuilder $qb): QueryBuilder
  325.     {
  326.         $qb->innerJoin('c.menuItem', 'mi')
  327.             ->andWhere('mi.state = :menuState')
  328.             ->setParameter('menuState', Item::STATE_ACTIVE);
  329.         return $qb;
  330.     }
  331.     public function addCurrentUserAccessRestriction(QueryBuilder $qb): QueryBuilder
  332.     {
  333.         $access = $this->getUserAccessParam();
  334.         $qb->andWhere('c.access <= :access')
  335.             ->setParameter('access', $access);
  336.         return $qb;
  337.     }
  338.     public function getUserAccessParam(): int
  339.     {
  340.         $user = $this->security->getUser();
  341.         if (!$user)
  342.             return Content::ACCESS_PUBLIC;
  343.         if (in_array(User::ROLE_SUPER_ADMIN, $user->getRoles()))
  344.             return Content::ACCESS_SUPERADMIN;
  345.         if (in_array(User::ROLE_ADMIN, $user->getRoles()))
  346.             return Content::ACCESS_ADMIN;
  347.         if (in_array(User::ROLE_USER, $user->getRoles()))
  348.             return Content::ACCESS_USER;
  349.     
  350.         return Content::ACCESS_PUBLIC;
  351.     }
  352.     public function addOrder(QueryBuilder $qb, int $orderType): QueryBuilder
  353.     {
  354.         if (!array_key_exists($orderType, self::ORDER))
  355.             return $qb;
  356.         $rootAlias = current($qb->getRootAliases());
  357.         if ($orderType == self::ORDER_CONTENT_FIELD_ID) {
  358.             if ($qb->getParameter('ids') === null) 
  359.                 return $qb;
  360.             $qb->orderBy(sprintf('FIELD(%s.id,:ids)', $rootAlias));
  361.             return $qb;
  362.         }
  363.         $qb->addOrderBy(sprintf('%s.%s', $rootAlias, self::ORDER[$orderType]['sort']), self::ORDER[$orderType]['order']);
  364.         return $qb;
  365.     }
  366.     public function aliasExists(string $alias, ?Content $content = null): bool
  367.     {
  368.         $qb = $this->createQueryBuilder('c');
  369.         $qb->where('c.alias = :alias')
  370.             ->setParameter('alias', $alias)
  371.             ->setMaxResults(1);
  372.         if ($content instanceof Content && !empty($content->getId())) {
  373.             $qb->andWhere('c.id <> :id')
  374.                 ->setParameter('id', $content->getId());
  375.         }
  376.         $content = $qb->getQuery()->getOneOrNullResult();
  377.         return !empty($content);
  378.     }
  379.     public function prepareAlias(Content $content): string
  380.     {
  381.         $aliasCounter = 2;
  382.         $alias = $content->getAlias();
  383.         $preparedAlias = $alias;
  384.         while ($this->aliasExists($preparedAlias, $content)) {
  385.             $preparedAlias = $alias . '-' . $aliasCounter;
  386.             $aliasCounter++;
  387.         }
  388.         return $preparedAlias;
  389.     }
  390.     public function delete(Content $content): void
  391.     {
  392.         if (!$content->getChildrens()->isEmpty()) {
  393.             throw new RuntimeException("Cannot delete content with descendant contents");
  394.         }
  395.         $this->_em->remove($content);
  396.         $this->_em->flush();
  397.     }
  398.     public function addHits(Content $content, int $hits = 1): void
  399.     {
  400.         $conn = $this->_em->getConnection();
  401.         $conn->executeStatement('UPDATE content SET hits = hits + ? WHERE id = ?', [$hits, $content->getId()]);
  402.     }
  403.     /**
  404.      * Returns result as array of objects for complex queries with multiple joins.
  405.      * Using Doctrine Paginator to get correct results, because of this:
  406.      * https://www.doctrine-project.org/projects/doctrine-orm/en/2.10/tutorials/pagination.html
  407.      */
  408.     public function getQbResultAsArray(QueryBuilder $qb): array
  409.     {
  410.         $results = [];
  411.         $paginator = new QueryPaginator($qb);
  412.         foreach ($paginator as $item) {
  413.             $results[] = $item;
  414.         }
  415.         unset($paginator); // Cleanup
  416.         return $results;
  417.     }
  418.     public function getOrderChoices(): array
  419.     {
  420.         $orderChoices = array_map(function($item)
  421.         {
  422.             return $item['title'];
  423.         }, self::ORDER);
  424.         return array_flip($orderChoices);
  425.     }
  426.     /**
  427.      * Used by Elastica to transform results to model
  428.      * 
  429.      * @param string $entityAlias
  430.      * @return  QueryBuilder
  431.      */
  432.     public function createAdvancedSearchQB($entityAlias): QueryBuilder
  433.     {
  434.         $qb = $this->createQueryBuilder($entityAlias);
  435.         return $qb->select($entityAlias, 'cf', 'p')
  436.             ->join($entityAlias.'.customFields', 'cf')
  437.             ->join($entityAlias.'.products', 'p');
  438.     }
  439. }