src/WebBundle/Repository/CollectionRepository.php line 603

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Repository;
  3. use Doctrine\DBAL\Connection;
  4. use Doctrine\DBAL\DBALException;
  5. use Doctrine\DBAL\Driver\Exception as DriverException;
  6. use Doctrine\DBAL\Exception as DoctrineDBALException;
  7. use Doctrine\DBAL\Exception\LockWaitTimeoutException;
  8. use Doctrine\ORM\NonUniqueResultException;
  9. use Doctrine\ORM\NoResultException;
  10. use Doctrine\ORM\Query\ResultSetMapping;
  11. use Doctrine\ORM\QueryBuilder;
  12. use Exception;
  13. use FlexApp\Classes\CommentableEntityTypes;
  14. use FlexApp\Constant\TimeConstant;
  15. use FlexApp\Entity\CommentEntity;
  16. use FlexApp\Repository\CommentRepository;
  17. use FlexApp\Service\RedisCachePool;
  18. use Import1CBundle\Helper\v3\BiConst;
  19. use Import1CBundle\Helper\v3\ConnectionHelper;
  20. use PDO;
  21. use WebBundle\Entity\Collection;
  22. use WebBundle\Entity\ProductReviewsCache;
  23. use WebBundle\Entity\SampleEntity;
  24. use WebBundle\Entity\User;
  25. use WebBundle\Helper\App;
  26. use WebBundle\Helper\ArrHelper;
  27. use WebBundle\Helper\HideFactoryCountriesHelper;
  28. use WebBundle\Helper\LocaleHelper;
  29. use WebBundle\Helper\PathHelper;
  30. class CollectionRepository extends ExtendEntityRepository
  31. {
  32.     private const COLLECTION_QUERY_FILTER_MAPPING = [
  33.         'collection'   => ['alias' => 'c''field' => 'id'],
  34.         'country'      => ['join' => ['path' => 'c.factory'], 'alias' => 'f''field' => 'country'],
  35.         'rewards'      => ['alias' => 'c''field' => 'awards'],
  36.         'reviews'      => ['join' => ['path' => ProductReviewsCache::class], 'alias' => 'reviews''field' => 'star'],
  37.     ];
  38.     /**
  39.      * Получаем коллекции с учетом локали, где есть хотя бы один коммент
  40.      * @param $locale
  41.      * @return array
  42.      */
  43.     public function getActivePagesArrays($locale): array
  44.     {
  45.         $query $this->getEntityManager()->createQuery(
  46.             "
  47.             SELECT
  48.                 DISTINCT coll.unid as portalThemeUnid
  49.             FROM WebBundle\Entity\Collection coll
  50.             JOIN FlexApp\Entity\CommentEntity comm
  51.                 WITH COLLATE(coll.unid,utf8mb4_unicode_ci) = COLLATE(comm.commentableUnid,utf8mb4_unicode_ci)
  52.                 AND comm.locale = :locale
  53.         "
  54.         );
  55.         $query->setParameter('locale'$locale);
  56.         $result $query->getResult();
  57.         foreach ($result as &$row) {
  58.             $row['locale'] = $locale;
  59.             $row['type'] = CommentableEntityTypes::COLLECTION;
  60.         }
  61.         return $result;
  62.     }
  63.     /**
  64.      * @param string $alias
  65.      * @return QueryBuilder
  66.      */
  67.     public function joinQuery($alias 'c')
  68.     {
  69.         return $this->createQueryBuilder($alias)
  70.             ->select("{$alias}, body, metaDescription, metaKeywords")
  71.             ->leftJoin("{$alias}.body"'body')
  72.             ->leftJoin("{$alias}.metaDescription"'metaDescription')
  73.             ->leftJoin("{$alias}.metaKeywords"'metaKeywords')
  74.             ->leftJoin("{$alias}.factory"'factory')
  75.             ->leftJoin('factory.user''user');
  76.     }
  77.     public function getCollectionsProcess()
  78.     {
  79.         $q $this->createQueryBuilder('c')
  80.             ->select('c, f')
  81.             ->innerJoin('c.factory''f')
  82.             ->leftJoin('c.interiors''i')
  83.             ->andWhere('c.status = :status')
  84.             ->andWhere('f.status = :status')
  85.             ->andWhere('i.status = 1')
  86.             ->andWhere('i.file IS NOT NULL')
  87.             ->andWhere('c.process IS NULL')
  88.             ->groupBy('i.id')
  89.             ->setParameter('status'BiConst::STATE_PUBLISHED);
  90.         return $q->getQuery()->getResult();
  91.     }
  92.     /**
  93.      * НЕ ИЗМЕНЯТЬ специальный запрос для API
  94.      * @param null $factoryId
  95.      * @return array|null
  96.      */
  97.     public function getCollectionsArrayAPI($factoryId null)
  98.     {
  99.         $q $this->createQueryBuilder('c')
  100.             ->select('c.id,c.name,c.alternateName,c.code')
  101.             ->leftJoin('c.factory''f')
  102.             ->andWhere('c.status = :status')
  103.             ->setParameter('status'BiConst::STATE_PUBLISHED);
  104.         if (!empty($factoryId)) {
  105.             $q->andWhere('f.id = :factory OR f.unid  = :factory')
  106.                 ->setParameter('factory'$factoryId);
  107.         }
  108.         return $q->getQuery()->getArrayResult();
  109.     }
  110.     /**
  111.      * @param null $factoryId
  112.      * @param null $status
  113.      * @return array
  114.      * @throws Exception
  115.      */
  116.     public function getCollectionsStatusArrayAPI($factoryId null$status null)
  117.     {
  118.         $q $this->createQueryBuilder('c')
  119.             ->select('c.id,c.name,c.alternateName,c.code')
  120.             ->leftJoin('c.factory''f');
  121.         if (!App::isRole('ROLE_TEST')) {
  122.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  123.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  124.         }
  125.         if (!empty($factoryId) and $factoryId != 'all') {
  126.             $q->andWhere('f.id = :factory OR f.unid  = :factory')
  127.                 ->setParameter('factory'$factoryId);
  128.         }
  129.         $states BiConst::listStateAll();
  130.         if ($status !== null and in_array($status$states)) {
  131.             $q->andWhere('c.status = :status')
  132.                 ->setParameter('status'$status);
  133.         }
  134.         $r $q->getQuery();
  135.         $result $r->getArrayResult();
  136.         return $result;
  137.     }
  138.     /**
  139.      * @param $cId
  140.      * @return mixed
  141.      * @throws NonUniqueResultException
  142.      * @throws NoResultException
  143.      */
  144.     public function collectionCountInteriors($cId)
  145.     {
  146.         return $this->createQueryBuilder('c')
  147.             ->select('count(i.id)')
  148.             ->leftJoin('c.interiors''i')
  149.             ->where('i.status = 1')
  150.             ->andWhere('c.id = :id')
  151.             ->setParameter('id'$cId)
  152.             ->getQuery()
  153.             ->enableResultCache()
  154.             ->getSingleScalarResult();
  155.     }
  156.     /**
  157.      * @return QueryBuilder
  158.      * @throws Exception
  159.      */
  160.     private function queryForCommandHeader()
  161.     {
  162.         $q $this->createQueryBuilder('c')
  163.             ->select('c.id, m.id material, t.id type')
  164.             ->leftJoin('c.factory''f')
  165.             ->leftJoin('c.articles''a')
  166.             ->leftJoin('a.type''t')
  167.             ->leftJoin('a.material''m')
  168.             ->andWhere('f.status IN (1,2,3)')
  169.             ->andWhere('f.unid IS NOT null')
  170.             ->andWhere('c.status != 0')
  171.             ->andWhere('a.delivery != 6 OR a.delivery = 6 AND (f.status IN (2,3) OR c.status IN (2,3))')
  172.             ->orderBy('f.name');
  173.         if (!App::isRole('ROLE_TEST')) {
  174.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  175.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  176.         }
  177.         return $q;
  178.     }
  179.     /**
  180.      * @param array $params
  181.      * @return array
  182.      * @throws Exception
  183.      */
  184.     public function getCollectionsForCommandHeader($params = [])
  185.     {
  186.         $q $this->queryForCommandHeader();
  187.         if (!empty($params['id'])) {
  188.             $q->andWhere('c.id = :id')
  189.                 ->setParameter('id'$params['id']);
  190.         }
  191.         $r $q->getQuery()
  192.             ->useQueryCache(true)
  193.             ->enableResultCache(3600);
  194.         $res = [];
  195.         $items $r->getArrayResult();
  196.         foreach ($items as $item) {
  197.             $res[$item['id']]['articles'][] = [
  198.                 'type' => $item['type'],
  199.                 'material' => $item['material'],
  200.             ];
  201.         }
  202.         return $res;
  203.     }
  204.     /**
  205.      * @param $id
  206.      * @return null
  207.      * @throws Exception
  208.      */
  209.     public function getCollForAlsoById($id)
  210.     {
  211.         $q $this->createQueryBuilder('c')
  212.             ->select('c, fc')
  213.             ->leftJoin('c.factory''fc')
  214.             ->andWhere('c.id = :id')
  215.             ->setParameter('id'$id);
  216.         if (!App::isRole('ROLE_TEST')) {
  217.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  218.             $q->andWhere('fc.testAccess IS NULL OR fc.testAccess = 0');
  219.         }
  220.         $r $q->getQuery()
  221.             ->useQueryCache(true)
  222.             ->enableResultCache(3600 24 30);
  223.         $result $r->getResult();
  224.         $item count($result) > $result[0] : null;
  225.         return $item;
  226.     }
  227.     /**
  228.      * @param $id
  229.      * @return null
  230.      * @throws Exception
  231.      */
  232.     public function getCollAuthor($id)
  233.     {
  234.         $q $this->createQueryBuilder('c')
  235.             ->select('c.author')
  236.             ->andWhere('c.id = :id')
  237.             ->setParameter('id'$id);
  238.         if (!App::isRole('ROLE_TEST')) {
  239.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  240.         }
  241.         $r $q->getQuery()
  242.             ->useQueryCache(true)
  243.             ->enableResultCache(3600 24 30);
  244.         $result $r->getArrayResult();
  245.         $item count($result) > $result[0]['author'] : null;
  246.         return $item;
  247.     }
  248.     /**
  249.      * @param null $c_name
  250.      * @param null $f_name
  251.      * @return array
  252.      * @throws Exception
  253.      */
  254.     public function getCollectionsF($c_name null$f_name null)
  255.     {
  256.         $q $this->createQueryBuilder('c')
  257.             ->select('c.url c_url, c.code c_code, c.name c_name, f.url f_url, f.id f_id, c.publishDate publishDate ,c.updateDate updateDate')
  258.             ->leftJoin('c.factory''f')
  259.             ->leftJoin('c.interiors''i')
  260.             ->andWhere('c.status = :c_status')
  261.             ->andWhere('f.status = :f_status')
  262.             ->andWhere('i.status < :i_status OR i.status is null')
  263.             ->setParameter('c_status'BiConst::STATE_PUBLISHED)
  264.             ->setParameter('f_status'BiConst::STATE_PUBLISHED)
  265.             ->setParameter('i_status'BiConst::STATE_DISCONTINUED)
  266.             ->groupBy('c.id');
  267.         if (!App::isRole('ROLE_TEST')) {
  268.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  269.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  270.         }
  271.         if (!empty($c_name) && !empty($f_name)) {
  272.             $q->andWhere('c.name LIKE :c_name')
  273.                 ->andWhere('f.name LIKE :f_name')
  274.                 ->setParameter('c_name'$c_name)
  275.                 ->setParameter('f_name'$f_name);
  276.         }
  277.         $r $q->getQuery()
  278.             ->useQueryCache(true);
  279.         return $r->getArrayResult();
  280.     }
  281.     /**
  282.      * @param $code
  283.      * @return null
  284.      * @throws Exception
  285.      */
  286.     public function getCollBM($code)
  287.     {
  288.         $q $this->createQueryBuilder('c')
  289.             ->select('c.code c_code, c.name c_name, c.url c_url, f.url f_url, f.name f_name, u.username')
  290.             ->leftJoin('c.factory''f')
  291.             ->leftJoin('f.user''u')
  292.             ->andWhere('c.code=:code')
  293.             ->setParameter('code'$code)
  294.             ->setMaxResults(1);
  295.         if (!App::isRole('ROLE_TEST')) {
  296.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  297.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  298.         }
  299.         $r $q->getQuery()->useQueryCache(false);
  300.         $items $r->getArrayResult();
  301.         return empty($items[0]) ? null $items[0];
  302.     }
  303.     /**
  304.      * @param $ides
  305.      * @param $limit
  306.      * @param string $sign
  307.      * @return array
  308.      * @throws Exception
  309.      */
  310.     public function getCollectionAlsoViewedNative($ides$limit$sign 'IN')
  311.     {
  312.         // на случай если в массиве один элемент чтобы работало FIELD
  313.         $ides array_merge([0], $ides);
  314.         $rsm = new ResultSetMapping();
  315.         $rsm->addEntityResult('WebBundle\Entity\Collection''c');
  316.         $rsm->addFieldResult('c''id''id');
  317.         $rsm->addFieldResult('c''name''name');
  318.         $rsm->addFieldResult('c''alternate_name''alternateName');
  319.         $rsm->addFieldResult('c''url''url');
  320.         $rsm->addFieldResult('c''awards''awards');
  321.         $rsm->addFieldResult('c''publish_date''publishDate');
  322.         $rsm->addFieldResult('c''rating''rating');
  323.         $rsm->addJoinedEntityResult('WebBundle\Entity\Factory''f''c''factory');
  324.         $rsm->addFieldResult('f''f_id''id');
  325.         $rsm->addFieldResult('f''f_name''name');
  326.         $rsm->addFieldResult('f''f_alternate_name''alternateName');
  327.         $rsm->addFieldResult('f''f_url''url');
  328.         $rsm->addJoinedEntityResult('WebBundle\Entity\ListCountry''lc''f''country');
  329.         $rsm->addFieldResult('lc''lc_id''id');
  330.         $rsm->addFieldResult('lc''lc_alias''alias');
  331.         $rsm->addFieldResult('lc''lc_code''code');
  332.         $rsm->addJoinedEntityResult('WebBundle\Entity\Interior''i''c''interiors');
  333.         $rsm->addEntityResult('WebBundle\Entity\Interior''i');
  334.         $rsm->addFieldResult('i''i_id''id');
  335.         $ides join(','$ides);
  336.         $sort $sign == 'IN' "FIELD({$ides})" 'c.id';
  337.         $where '';
  338.         if (!App::isRole('ROLE_TEST')) {
  339.             $where ' AND (c.test_access IS NULL OR c.test_access = 0) AND f.test_access IS NULL AND (c.accessible IS NULL OR c.accessible = 0)';
  340.         }
  341.         $query $this->_em->createNativeQuery(
  342.             "SELECT
  343.               c.id,
  344.               c.name,
  345.               c.alternate_name,
  346.               c.url,
  347.               c.awards,
  348.               c.publish_date,
  349.               c.rating,
  350.               f.id AS f_id,
  351.               f.name AS f_name,
  352.               f.alternate_name AS f_alternate_name,
  353.               f.url AS f_url,
  354.               lc.id AS lc_id,
  355.               lc.alias AS lc_alias,
  356.               lc.code AS lc_code,
  357.               i.id AS i_id
  358.             FROM
  359.               collection c
  360.             LEFT JOIN factory f ON f.id = c.factory
  361.             LEFT JOIN list_country lc ON lc.id = f.country
  362.             LEFT JOIN interior i ON c.id = i.collection
  363.             WHERE i.is_main = 1{$where} AND c.id {$sign} ({$ides}) AND c.status = 1 AND f.status = 1
  364.             GROUP BY c.id
  365.             ORDER BY {$sort} DESC, i.is_main DESC, i.is_head DESC LIMIT {$limit}",
  366.             $rsm
  367.         );
  368.         return $query->getArrayResult();
  369.     }
  370.     /**
  371.      * @param $id
  372.      * @return array
  373.      * @throws Exception
  374.      */
  375.     public function getCollectionForInformer(int $id): array
  376.     {
  377.         $q $this->createQueryBuilder('c')
  378.             ->select('c,f,a,measure,measurementSize')
  379.             ->leftJoin('c.factory''f')
  380.             ->leftJoin('c.articles''a')
  381.             ->leftJoin('a.measure''measure')
  382.             ->leftJoin('a.measurementSize''measurementSize')
  383.             ->andWhere('c.id = :id')
  384.             ->setParameter('id'$id);
  385.         if (!App::isRole('ROLE_TEST')) {
  386.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  387.         }
  388.         $r $q->getQuery()
  389.             ->useQueryCache(true);
  390.         $items $r->getArrayResult();
  391.         if (count($items) > 0) {
  392.             return $items[0];
  393.         }
  394.         return [];
  395.     }
  396.     /**
  397.      * @param $factoryUrl
  398.      * @param $collectionUrl
  399.      * @return array|mixed|null
  400.      * @throws Exception
  401.      */
  402.     public function getSlideCollection($factoryUrl$collectionUrl)
  403.     {
  404.         $q $this->createQueryBuilder('c')
  405.             ->addSelect('f, ct')
  406.             ->innerJoin('c.factory''f')
  407.             ->innerJoin('f.country''ct')
  408.             ->andWhere('f.url = :factory')
  409.             ->andWhere('c.url = :collection')
  410.             ->andWhere('c.status IN (:cStatus)')
  411.             ->setParameters([
  412.                 'factory' => $factoryUrl,
  413.                 'collection' => $collectionUrl,
  414.                 'cStatus' => [
  415.                     BiConst::STATE_PUBLISHED,
  416.                     BiConst::STATE_DISCONTINUED,
  417.                     BiConst::STATE_WORK_CONTINUED,
  418.                     BiConst::STATE_CHECKING,
  419.                     BiConst::STATE_PROCESSING,
  420.                 ],
  421.             ]);
  422.         if (!App::isRole('ROLE_TEST')) {
  423.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  424.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  425.         }
  426.         $item $q->setMaxResults(1)
  427.             ->getQuery()
  428.             ->enableResultCache(TimeConstant::HOUR)
  429.             ->getArrayResult();
  430.         if (empty($item[0])) {
  431.             return null;
  432.         }
  433.         $res $item[0];
  434.         // закрываем некоторые фабрики для некоторых стран
  435.         if (in_array($res['factory']['id'], HideFactoryCountriesHelper::codes())) {
  436.             $res['factory']['status'] = 3;
  437.             $res['status'] = 3;
  438.         }
  439.         if (!empty($res['status']) && $res['status'] > 3) {
  440.             $res['status'] = 3;
  441.         }
  442.         return $res;
  443.     }
  444.     /**
  445.      * @param array $param
  446.      * @return mixed
  447.      * @throws Exception
  448.      */
  449.     public function getCollectionsForMenuFilters($param = [])
  450.     {
  451.         $q $this->createQueryBuilder('c')
  452.             ->select('c, f')
  453.             ->leftJoin('c.factory''f')
  454.             ->andWhere('c.factory != \'\'')
  455.             ->andWhere('f.status = :f_status')
  456.             ->andWhere('c.status = :c_status')
  457.             ->setParameter('f_status'BiConst::STATE_PUBLISHED)
  458.             ->setParameter('c_status'BiConst::STATE_PUBLISHED)
  459.             ->orderBy('c.name, c.publishDate DESC, c.id');
  460.         if (!App::isRole('ROLE_TEST')) {
  461.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  462.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  463.         }
  464.         if (!empty($param['factoryId'])) {
  465.             $q->andWhere('f.id IN (' join(', '$param['factoryId']) . ')');
  466.         }
  467.         if (!empty($param['id'])) {
  468.             $q->andWhere('c.id = :collId');
  469.             $q->setParameter('collId'$param['id']);
  470.         }
  471.         $r $q->getQuery();
  472.         // todo для кеша места не хвататет, надо выборку уменьшить.
  473.         //$r->useQueryCache(true)->useResultCache(true, 60 * 60 * 4, $this->buildCacheName('getCollectionsForFilters', $param));
  474.         $items $r->getResult();
  475.         return $items;
  476.     }
  477.     /**
  478.      * @param int $page
  479.      * @param int $limit
  480.      * @param string $orderBy
  481.      * @return array
  482.      * @throws Exception
  483.      */
  484.     public function getCollectionIdes(
  485.         int $page 1,
  486.         int $limit 20,
  487.         string $orderBy 'c.publishDate DESC, c.id'
  488.     ): array {
  489.         $q $this->createQueryBuilder('c')
  490.             ->select('c.id')
  491.             ->leftJoin('c.factory''f')
  492.             ->leftJoin('f.filter''b')// это сущность из базы фильтров
  493.             ->andWhere('c.status = :status')
  494.             ->andWhere('c.showMain = :showMain')
  495.             ->andWhere('c.accessible != :accessible OR c.accessible is null')
  496.             ->andWhere('f.filter IS NOT null')
  497.             ->andWhere('f.status = :status')
  498.             ->andWhere('c.factory != :factory')
  499.             ->setParameters([
  500.                 'status' => BiConst::STATE_PUBLISHED,
  501.                 'showMain' => true,
  502.                 'accessible' => true,
  503.                 'factory' => ''
  504.             ])
  505.             ->orderBy($orderBy)
  506.             ->setMaxResults($limit)
  507.             ->setFirstResult($limit $page $limit);
  508.         if (!App::isRole('ROLE_TEST')) {
  509.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  510.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  511.         }
  512.         $res $q->getQuery()
  513.             ->enableResultCache(600)
  514.             ->getArrayResult();
  515.         return $res array_column($res'id') : [];
  516.     }
  517.     /**
  518.      * @param array $param
  519.      * @param bool $wTest
  520.      * @return array
  521.      * @throws Exception
  522.      */
  523.     public function getCollections(array $param = [], bool $wTest false): array
  524.     {
  525.         $redisCachePool App::getContainer()->get(RedisCachePool::class)->getPool();
  526.         $memKey md5(
  527.             json_encode($param) . $wTest '2' App::getCurLocale() . LocaleHelper::getCur(
  528.             ) . LocaleHelper::getUserMeasure()
  529.         );
  530.         $cacheItem $redisCachePool->getItem('getCollections.' $memKey);
  531.         $cacheItem->expiresAfter(600);
  532.         $cacheCreatedAtItem $redisCachePool->getItem('createdCollectionAt.' $memKey);
  533.         $cacheCreatedAtItem->expiresAfter(600);
  534.         $cacheUpdatedAtItem $redisCachePool->getItem('updateCollections');
  535.         $cacheUpdatedAtItem->expiresAfter(600);
  536.         $createdAt $cacheCreatedAtItem->get() ?? false;
  537.         $updatedAt $cacheUpdatedAtItem->get() ?? false;
  538.         $expired $createdAt && $updatedAt && ($updatedAt $createdAt);
  539.         if (!$cacheItem->isHit() || $expired) {
  540.             $q $this->createQueryBuilder('c')
  541.                 ->innerJoin('c.factory''f')
  542.                 ->innerJoin('f.filter''b')// это сущность из базы фильтров
  543.                 ->innerJoin('f.country''ct')
  544.                 ->andWhere('f.filter IS NOT null')
  545.                 ->andWhere('c.factory != \'\'')
  546.                 ->andWhere('f.status = :f_status')
  547.                 ->setParameter('f_status'BiConst::STATE_PUBLISHED);
  548.             if (HideFactoryCountriesHelper::length() > 0) {
  549.                 $q->andWhere('f.id NOT IN (:hide_factories)')
  550.                     ->setParameter('hide_factories'HideFactoryCountriesHelper::codes());
  551.             }
  552.             if (!App::isRole('ROLE_TEST') && !$wTest) {
  553.                 $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  554.                 $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  555.             }
  556.             if (isset($param['collectionId'])) {
  557.                 $cid $param['collectionId'];
  558.                 if (is_array($cid)) {
  559.                     $cid implode(' ,'$cid);
  560.                     $q->andWhere('c.status = :c_status and c.id IN (:collectionId)');
  561.                     $q->setParameter('collectionId'$cid);
  562.                 } else {
  563.                     $q->andWhere('c.status = :c_status and c.id = :collectionId');
  564.                     $q->setParameter('collectionId'$param['collectionId']);
  565.                 }
  566.                 $q->setParameter('c_status'BiConst::STATE_PUBLISHED);
  567.             } else {
  568.                 $q->andWhere('c.status = :c_status')
  569.                     ->setParameter('c_status'BiConst::STATE_PUBLISHED);
  570.             }
  571.             if (!empty($param['leftCollectionCount']) && $param['leftCollectionCount']) {
  572.                 $q->andWhere('c.status = :c_status');
  573.                 $q->andWhere('f.status = :f_status');
  574.                 $q->setParameter('c_status'BiConst::STATE_PUBLISHED)
  575.                     ->setParameter('f_status'BiConst::STATE_PUBLISHED);
  576.             }
  577.             if (!empty($param['onlyId'])) {
  578.                 $q->select('c.id');
  579.             } elseif (empty($param['onlyCF'])) {
  580.                 $q->select('c,f,ct,i,id')
  581.                     ->leftJoin('c.interiors''i')
  582.                     ->leftJoin('i.ideas''id')
  583.                     ->groupBy('c.id');
  584.             } else {
  585.                 $q->select('c.id,c.url,c.code,c.name,c.alternateName,c.nameFull,f.id fId,f.url fUrl,f.unid fUnid');
  586.                 if (!empty($param['locale'])) {
  587.                     $q->leftJoin('b.url''burl');
  588.                     $q->leftJoin('b.page''bpage');
  589.                     $q->addSELECT("b.id brandId, f.url brandUrl, f.name brandName");
  590.                 }
  591.             }
  592.             if (!empty($param['factoryId'])) {
  593.                 $q->andWhere('f.id IN (' join(', '$param['factoryId']) . ')');
  594.             }
  595.             if (!empty($param['order'])) {
  596.                 $q->orderBy($param['order']);
  597.             } else {
  598.                 $q->orderBy('c.publishDate DESC, c.id');
  599.             }
  600.             if (!empty($param['ides'])) {
  601.                 $q->andWhere('c.id IN (' join(', '$param['ides']) . ')');
  602.             }
  603.             if (!empty($param['noIdes'])) {
  604.                 $q->andWhere('c.id NOT IN (' join(', '$param['noIdes']) . ')');
  605.             }
  606.             if (!empty($param['limit'])) {
  607.                 $q->setMaxResults($param['limit']);
  608.             }
  609.             if (!empty($param['start_with'])) {
  610.                 $q->setFirstResult($param['start_with']);
  611.             }
  612.             if (!empty($param['archive'])) {
  613.                 $q->andWhere('c.archive = ' $param['archive']);
  614.             }
  615.             if (!empty($param['code'])) {
  616.                 $code ArrHelper::get($param'code');
  617.                 $code is_array($code) ? $code[0] : $code;
  618.                 foreach ($code as $i => $item) {
  619.                     $code[$i] = "'{$item}'";
  620.                 }
  621.                 $code implode(', '$code);
  622.                 $q->andWhere("c.code in ({$code})");
  623.             }
  624.             if (empty($param['noReviewCount'])) {
  625.                 // специальные подзапросы для отзывов по коллекциям
  626.                 $q->addSELECT(
  627.                     '(SELECT COUNT(prc.star) FROM WebBundle\Entity\ProductReviewsCache prc Where prc.sku = c.code) prc_count'
  628.                 );
  629.                 $q->addSELECT(
  630.                     '(SELECT SUM(prc2.star) FROM WebBundle\Entity\ProductReviewsCache prc2 Where prc2.sku = c.code) prc_vote'
  631.                 );
  632.             }
  633.             $r $q->getQuery()->useQueryCache(true);
  634.             $items $r->getArrayResult();
  635.             foreach ($items as $key => $item) {
  636.                 if (!empty($item[0])) {
  637.                     $items[$key] = array_merge($item[0], $item);
  638.                     unset($items[$key][0]);
  639.                 }
  640.             }
  641.             $cacheItem->set($items);
  642.             $cacheCreatedAtItem->set(time());
  643.             $redisCachePool->save($cacheItem);
  644.         }
  645.         $collections $cacheItem->get();
  646.         if (isset($collections[0]['rating'])) {
  647.             $ids = [];
  648.             foreach ($collections as $collection) {
  649.                 $ids[] = $collection['id'] ?? 0;
  650.             }
  651.             //Делаем один дополнительный sql запрос на получение пачки коллекций
  652.             $actualData $this->findBy(['id' => $ids]);
  653.             foreach ($collections as &$collection) {
  654.                 $collection['rating'] = $this->getRating($collection['id'], $actualData);
  655.             }
  656.         }
  657.         return $collections;
  658.     }
  659.     public function getListForMenu(array $param): array
  660.     {
  661.         $status BiConst::STATE_PUBLISHED ', ' BiConst::STATE_WORK_CONTINUED;
  662.         $whereCid '';
  663.         if (!empty($param['collectionId'])) {
  664.             $cid $param['collectionId'];
  665.             if (is_array($cid)) {
  666.                 $cid implode(' ,'$cid);
  667.             }
  668.             $whereCid "AND c.id IN ({$cid})";
  669.         }
  670.         $whereFid '';
  671.         if (!empty($param['factoryId'])) {
  672.             $fid implode(' ,'$param['factoryId']);
  673.             $whereCid "AND b.id IN ({$fid})";
  674.         }
  675.         // доработал запрос чтобы не попадали коллекции у которых нет выборки для каталога
  676.         // https://te.remote.team/#/discus/E82653AE-437D-D61C-AE0D-F985799FE15E/
  677.         $sql "SELECT
  678.                 c.id AS `id`,
  679.                 c.status AS `status`,
  680.                 c.url AS `slug`,
  681.                 c.name AS `name`,
  682.                 c.name_full AS `nameFull`,
  683.                 b.id AS `b.id`,
  684.                 b.name AS `b.name`,
  685.                 b.url AS `b.slug`
  686.             FROM
  687.                 collection c
  688.             INNER JOIN factory b ON b.id = c.factory
  689.             INNER JOIN article a ON a.collection = c.id AND a.delivery <> 6 AND a.file IS NOT NULL AND a.file <> '' AND a.price_euro > 0
  690.             WHERE c.factory IS NOT NULL
  691.                 AND c.factory != ''
  692.                 AND c.url IS NOT NULL
  693.                 AND c.url != ''
  694.                 AND b.url IS NOT NULL
  695.                 AND b.url != ''
  696.                 AND b.filter IS NOT null
  697.                 AND b.status IN ({$status})
  698.                 AND c.status IN ({$status})
  699.                 {$whereCid} {$whereFid}
  700.             GROUP BY c.id
  701.             ORDER BY c.name, b.name
  702.             ";
  703.         $rows $this
  704.             ->_em
  705.             ->getConnection()
  706.             ->fetchAllAssociative($sql);
  707.         foreach ($rows as $i => $row) {
  708.             $name $row['nameFull'] ? $row['nameFull'] : $row['name'];
  709.             $item = [
  710.                 'fId' => intval($row['b.id']),
  711.                 'id' => intval($row['id']),
  712.                 'status' => intval($row['status']),
  713.                 'slug' => $row['slug'],
  714.                 'name' => html_entity_decode($name),
  715.                 'factory' => [
  716.                     'id' => intval($row['b.id']),
  717.                     'slug' => $row['b.slug'],
  718.                     'name' => html_entity_decode($row['b.name']),
  719.                 ],
  720.             ];
  721.             $rows[$i] = $item;
  722.         }
  723.         return $rows;
  724.     }
  725.     /**
  726.      * @param array $param
  727.      * @return int
  728.      * @throws Exception
  729.      */
  730.     public function countCollections($param = [])
  731.     {
  732.         $q $this->createQueryBuilder('c')
  733.             ->select('COUNT(c.id)')
  734.             ->leftJoin('c.factory''f')
  735.             ->leftJoin('c.articles''a')
  736.             ->andWhere('c.factory != \'\'')
  737.             ->andWhere('f.id != 99')
  738.             ->andWhere('f.status = :f_status')
  739.             ->andWhere('c.status = :c_status')
  740.             ->andWhere('c.archive != 1')
  741.             ->andWhere('a.priceEuro IS NOT null')
  742.             ->setParameter('c_status'BiConst::STATE_PUBLISHED)
  743.             ->setParameter('f_status'BiConst::STATE_PUBLISHED)
  744.             ->orderBy('c.name, c.publishDate')
  745.             ->groupBy('c.id');
  746.         if (!App::isRole('ROLE_TEST')) {
  747.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  748.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  749.         }
  750.         if (!empty($param['factoryId'])) {
  751.             $param['factoryId'] = is_array($param['factoryId']) ? $param['factoryId'] : [$param['factoryId']];
  752.             $q->andWhere('f.id IN (' join(', '$param['factoryId']) . ')');
  753.         }
  754.         $r $q->getQuery()->useQueryCache(true);
  755.         $items count($r->getArrayResult());
  756.         return $items;
  757.     }
  758.     /**
  759.      * @param $factoryUnid
  760.      * @return array|null
  761.      */
  762.     public function getCollectionsByFactoryUnid($factoryUnid)
  763.     {
  764.         $r $this->createQueryBuilder('c')
  765.             ->select('c,f')
  766.             ->leftJoin('c.factory''f')
  767.             ->andWhere('f.unid = :unid')
  768.             ->setParameters(['unid' => $factoryUnid])
  769.             ->getQuery();
  770.         return $r->getResult();
  771.     }
  772.     /**
  773.      * получить коллекции для установки тем и участников из админки
  774.      * @param null $ids
  775.      * @param null $limit
  776.      * @return array|null
  777.      */
  778.     public function getCollectionsParticipant($ids null$limit null)
  779.     {
  780.         $q $this
  781.             ->createQueryBuilder('c')
  782.             ->andWhere('c.status =:c_status')
  783.             ->setParameter('c_status'BiConst::STATE_PUBLISHED);
  784.         if ($ids) {
  785.             $ids preg_replace('#[\s]+#i'''trim($ids));
  786.             $IDS explode(','$ids);
  787.             $q->andWhere('c.id in (:ids)')
  788.                 ->setParameter('ids'$IDS);
  789.         }
  790.         if ($limit) {
  791.             $q->setMaxResults($limit);
  792.         }
  793.         $r $q->getQuery();
  794.         return $r->getResult();
  795.     }
  796.     /**
  797.      * @param int $p
  798.      * @param int $l
  799.      * @param null $id
  800.      * @return array|null
  801.      */
  802.     public function getCollCheck($p$l 10000$id null)
  803.     {
  804.         $offset $l $p $l;
  805.         $rsm = new ResultSetMapping();
  806.         $rsm->addEntityResult('WebBundle\Entity\Factory''f');
  807.         $rsm->addFieldResult('f''f_id''id');
  808.         $rsm->addFieldResult('f''f_url''url');
  809.         $rsm->addJoinedEntityResult('WebBundle\Entity\User''u''f''user');
  810.         $rsm->addFieldResult('u''u_id''id');
  811.         $rsm->addFieldResult('u''username''username');
  812.         $rsm->addJoinedEntityResult('WebBundle\Entity\Article''a''c''articles');
  813.         $rsm->addFieldResult('a''id''id');
  814.         $rsm->addFieldResult('a''file''file');
  815.         $rsm->addJoinedEntityResult('WebBundle\Entity\Collection''c''f''collection');
  816.         $rsm->addFieldResult('c''c_id''id');
  817.         $rsm->addFieldResult('c''c_url''url');
  818.         $rsm->addJoinedEntityResult('WebBundle\Entity\Interior''i''c''interiors');
  819.         $rsm->addFieldResult('i''i_id''id');
  820.         $rsm->addFieldResult('i''i_name''name');
  821.         $rsm->addFieldResult('i''i_file''file');
  822.         $ID $id != null ? ('c.id=' $id ' AND ') : '';
  823.         $query $this->_em->createNativeQuery(
  824.             'SELECT
  825.                 f.id AS f_id,
  826.                 f.url AS f_url,
  827.                 u.id AS u_id,
  828.                 u.username,
  829.                 c.id AS c_id,
  830.                 c.url AS c_url,
  831.                 a.id,
  832.                 a.file,
  833.                 i.id AS i_id,
  834.                 i.name AS i_name,
  835.                 i.file AS i_file
  836.             FROM factory f
  837.             LEFT JOIN user u ON f.user_id = u.id
  838.             LEFT JOIN collection c ON c.factory = f.id
  839.             LEFT JOIN article a ON a.collection = c.id
  840.             LEFT JOIN interior i ON i.collection = c.id
  841.             WHERE ' $ID 'c.status IN (' BiConst::STATE_PUBLISHED ', ' BiConst::STATE_DISCONTINUED ') AND f.status > ' BiConst::STATE_DISCONTINUED ' AND a.file IS NOT NULL AND a.delivery <> 6 LIMIT ' $l ' OFFSET ' $offset ';',
  842.             $rsm
  843.         );
  844.         $result $query->getArrayResult();
  845.         return $result;
  846.     }
  847.     /**
  848.      * @return int|mixed
  849.      * @throws NoResultException
  850.      * @throws NonUniqueResultException
  851.      */
  852.     public function countAllCollection()
  853.     {
  854.         $q $this->createQueryBuilder('q');
  855.         $q->select('count(q.id)')
  856.             ->andWhere('q.status = :status')
  857.             ->setParameter('status'BiConst::STATE_PUBLISHED);
  858.         $count $q->getQuery()->getSingleScalarResult();
  859.         return $count;
  860.     }
  861.     /**
  862.      * Получаем рейтинги для коллекций отдельно, чтобы не чистить из-за них кеш
  863.      * @param array $id
  864.      * @return array|null
  865.      */
  866.     public function getRatings(array $id)
  867.     {
  868.         if (count($id) == 0) {
  869.             return [];
  870.         }
  871.         if (is_array($id)) {
  872.             $id implode(', '$id);
  873.             $id "($id)";
  874.         }
  875.         $q $this->createQueryBuilder('c')
  876.             ->select('c.id, c.rating')
  877.             ->andWhere("c.id IN {$id}");
  878.         $r $q->getQuery()->useQueryCache(true);
  879.         $items $r->getArrayResult();
  880.         $res = [];
  881.         foreach ($items as $item) {
  882.             $res[$item['id']] = $item['rating'];
  883.         }
  884.         return $res;
  885.     }
  886.     /**
  887.      * todo remove from bi
  888.      * @return array|null
  889.      */
  890.     public function _getOutputLastCollectionsInteriorImg()
  891.     {
  892.         $limit 55;
  893.         $q $this
  894.             ->createQueryBuilder('c')
  895.             ->andWhere('(SELECT count(i.id) FROM WebBundle\Entity\Interior i Where c.id=i.collection) > :count')
  896.             ->setParameter('count'5)
  897.             ->orderBy('c.rating''desc')
  898.             ->setMaxResults($limit)
  899.             ->getQuery();
  900.         $items $q->getResult();
  901.         $oui = [];
  902.         /** @var Collection $item */
  903.         foreach ($items as $k => $item) {
  904.             foreach ($item->getInteriors() as $key => $interior) {
  905.                 if ($key 3) {
  906.                     $oui[] = [
  907.                         'collection' => $item,
  908.                         'interior' => $interior,
  909.                     ];
  910.                 } else {
  911.                     break;
  912.                 }
  913.             }
  914.         }
  915.         return $oui;
  916.     }
  917.     /**
  918.      * Список БМов, которые задействованы в коллекциях
  919.      * @return array
  920.      * @throws Exception
  921.      */
  922.     public function getListActiveBM()
  923.     {
  924.         $q $this->createQueryBuilder('c')
  925.             ->select('DISTINCT(user) AS uid, user.alias, user.username')
  926.             ->leftJoin('c.factory''factory')
  927.             ->leftJoin('factory.user''user')
  928.             ->andWhere('c.factory is not null')
  929.             ->andWhere('factory.status != 2')
  930.             ->andWhere('factory.status != 3')
  931.             ->andWhere('factory.status != 0')
  932.             ->getQuery();
  933.         $list = [];
  934.         $oServiceUser App::getContainer()->get('adm.service.users');
  935.         foreach ($q->getArrayResult() as $item) {
  936.             if (!empty($item['uid'])) {
  937.                 $name $item['alias'] ? $item['alias'] : $item['username'];
  938.                 $list[$item['uid']] = $oServiceUser->buildEasyName($name);
  939.             }
  940.         }
  941.         return $list;
  942.     }
  943.     /**
  944.      * @return array
  945.      */
  946.     public function getCollForVideo()
  947.     {
  948.         $q $this->createQueryBuilder('c')
  949.             ->select('c, b')
  950.             ->leftJoin('c.body''b')
  951.             ->andWhere('b.en LIKE \'%youtube%\'')
  952.             ->getQuery();
  953.         return $q->getResult();
  954.     }
  955.     /**
  956.      * todo remove from bi
  957.      * получить набор коллекций для загрузки оброаботанных дизайнером изображений
  958.      * @param Collection|null $collection
  959.      * @return array|null
  960.      */
  961.     public function _getCollectionsByCollection(Collection $collection null)
  962.     {
  963.         $q $this->createQueryBuilder('c')
  964.             ->andWhere('c.status = :status1 or c.status = :status4')
  965.             ->setParameter('status1'BiConst::STATE_PUBLISHED)
  966.             ->setParameter('status4'BiConst::STATE_PROCESSING);
  967.         if ($collection) {
  968.             $id $collection->getId();
  969.             $q
  970.                 ->andWhere('c.id = :id')
  971.                 ->setParameter('id'$id);
  972.         }
  973.         $r $q->getQuery()
  974.             ->useQueryCache(true)
  975.             ->enableResultCache(3600 24 30);
  976.         return $r->getResult();
  977.     }
  978.     /**
  979.      * todo remove from bi
  980.      * @param User $user
  981.      * @return array|null
  982.      */
  983.     public function _getCollectionsForBm(User $user)
  984.     {
  985.         $q $this->createQueryBuilder('c')
  986.             ->leftJoin('c.factory''f')
  987.             ->leftJoin('f.user''u');
  988.         if ($user->hasRole('ROLE_BM')) {
  989.             $q
  990.                 ->andWhere('u.id = :user')
  991.                 ->setParameter('user'$user->getId());
  992.         }
  993.         $r $q
  994.             ->andWhere('f.status = :fstatus')
  995.             ->andWhere('c.status = :cstatus1 or c.status = :cstatus4')
  996.             ->setParameter('fstatus'BiConst::STATE_PUBLISHED)
  997.             ->setParameter('cstatus1'BiConst::STATE_PUBLISHED)
  998.             ->setParameter('cstatus4'BiConst::STATE_PROCESSING)
  999.             ->orderBy('f.url, c.url')
  1000.             ->getQuery();
  1001.         return $r->getResult();
  1002.     }
  1003.     /**
  1004.      * Получение списка для проверки на наличие кириллических символов
  1005.      * @return array
  1006.      */
  1007.     public function getCollectionsAdmForCheckCyrillic()
  1008.     {
  1009.         $q $this->createQueryBuilder('c')
  1010.             ->select('c, body')
  1011.             ->leftJoin('c.body''body')
  1012.             ->andWhere('c.status = :status')
  1013.             ->setParameter('status'BiConst::STATE_PUBLISHED);
  1014.         return $q->getQuery()->getArrayResult();
  1015.     }
  1016.     /**
  1017.      * Получение списка блогов с которыми связана коллекция
  1018.      * @param        $collectionId
  1019.      * @param string $lc
  1020.      * @return array
  1021.      * @throws Exception
  1022.      */
  1023.     public function getPublications($collectionId$lc)
  1024.     {
  1025.         // получаем полную локаль, для формирования ссылки
  1026.         $lcFull $lc;
  1027.         if ($lcFull != ($cc App::getCurCountry())) {
  1028.             $lcFull "$lc-$cc";
  1029.         }
  1030.         $unid 'unid';
  1031.         $q $this->createQueryBuilder('c')
  1032.             ->select(
  1033.                 "c.id cId, c.code cCode, c.{$unid} unid, p.view view, p.publishDate publishDate, p.unid pUnid, p.id pId, title.{$lc} pTitle, body.{$lc} pBody, url.{$lc} pUrl, pr.default preview"
  1034.             )
  1035.             ->leftJoin('c.publications''p')
  1036.             ->leftJoin('p.url''url')
  1037.             ->leftJoin('p.title''title')
  1038.             ->leftJoin('p.body''body')
  1039.             ->leftJoin('p.preview''pr')
  1040.             ->andWhere('p.enable = true OR p.id IS NULL')
  1041.             ->andWhere('c.id = :id')
  1042.             ->setParameter('id'$collectionId);
  1043.         $res = [
  1044.             'publications' => [],
  1045.         ];
  1046.         /** @var CommentRepository $repoComment */
  1047.         $repoComment App::getRepository(CommentEntity::class);
  1048.         foreach ($q->getQuery()->getArrayResult() as $row) {
  1049.             if (empty($res['id'])) {
  1050.                 $res['id'] = $row['cId'];
  1051.             }
  1052.             if (empty($res['code'])) {
  1053.                 $res['code'] = $row['cCode'];
  1054.             }
  1055.             if (empty($res['unid'])) {
  1056.                 $res['unid'] = $row['unid'];
  1057.             }
  1058.             if (!empty($row['pUrl']) && !empty($row['pTitle'])) {
  1059.                 $res['publications'][] = [
  1060.                     'link' => App::generateUrl('app_publication_single', ['id' => $row['pUrl'], '_locale' => $lcFull]),
  1061.                     'title' => $row['pTitle'],
  1062.                     'body' => $row['pBody'],
  1063.                     'publishDate' => $row['publishDate'],
  1064.                     'view' => $row['view'],
  1065.                     'preview' => PathHelper::pathGenerate(
  1066.                         'publication',
  1067.                         [
  1068.                             'id' => $row['pId'],
  1069.                             'preview' => $row['preview'],
  1070.                         ]
  1071.                     ),
  1072.                     'commentCnt' => !empty($row['pUnid'])
  1073.                         ? $repoComment->getCountPublicationsByUnid($lc$row['pUnid'])
  1074.                         : 0
  1075.                 ];
  1076.             }
  1077.         }
  1078.         return $res;
  1079.     }
  1080.     /**
  1081.      * Установка парамтеров к запросу для выборки коллекции на главной
  1082.      * @param $factory
  1083.      * @param $collection
  1084.      * @return mixed|null
  1085.      */
  1086.     public function getMainBaseCollectionLight($factory$collection)
  1087.     {
  1088.         $query $this->createQueryBuilder('c')
  1089.             ->select('c, f, country, body, metaKeywords, metaDescription')
  1090.             ->leftJoin('c.factory''f')
  1091.             ->leftJoin('f.country''country')
  1092.             ->leftJoin('c.body''body')
  1093.             ->leftJoin('c.metaKeywords''metaKeywords')
  1094.             ->leftJoin('c.metaDescription''metaDescription')
  1095.             ->andWhere('f.status > :f_status')
  1096.             ->andWhere('f.url = :factory')
  1097.             ->andWhere('c.url = :collection')
  1098.             ->setParameters([
  1099.                 'f_status' => BiConst::STATE_NOT_PUBLISHED,
  1100.                 'factory' => $factory,
  1101.                 'collection' => $collection,
  1102.             ])
  1103.             ->getQuery()
  1104.             ->setQueryCacheLifetime(TimeConstant::HOUR)
  1105.             ->useQueryCache(true);
  1106.         $item $query->getArrayResult();
  1107.         $res current($item);
  1108.         // закрываем некоторые фабрики для некоторых стран
  1109.         if ($res && in_array($res['factory']['id'], HideFactoryCountriesHelper::codes())) {
  1110.             $res['factory']['status'] = 3;
  1111.             $res['status'] = 3;
  1112.         }
  1113.         return $res;
  1114.     }
  1115.     /**
  1116.      * формирование запроса для выборки данных коллекции и связанных интерьеров для главной и для слайдера
  1117.      * @return QueryBuilder
  1118.      */
  1119.     public function createQuerySliderBaseCollection()
  1120.     {
  1121.         $q $this->createQueryBuilder('c');
  1122.         $q
  1123.             ->select('c, f, i, idea, applies, styles, textures, country, body, metaKeywords, metaDescription')
  1124.             ->leftJoin('c.factory''f')
  1125.             ->leftJoin('f.country''country')
  1126.             ->leftJoin('c.body''body')
  1127.             ->leftJoin('c.metaKeywords''metaKeywords')
  1128.             ->leftJoin('c.metaDescription''metaDescription');
  1129.         $where 'f.status > :f_status';
  1130.         $q
  1131.             ->andWhere($where)
  1132.             ->orderBy('i.isMain''DESC')
  1133.             ->setParameter('f_status'BiConst::STATE_NOT_PUBLISHED);
  1134.         return $q;
  1135.     }
  1136.     /**
  1137.      * @param $code
  1138.      * @return mixed
  1139.      * @throws NoResultException
  1140.      * @throws NonUniqueResultException
  1141.      */
  1142.     public function getCollectionByCode($code)
  1143.     {
  1144.         $q $this->createQueryBuilder('c')
  1145.             ->select('c,f,u')
  1146.             ->leftJoin('c.factory''f')
  1147.             ->leftJoin('f.user''u')
  1148.             ->andWhere('c.code = :code')
  1149.             ->setParameter('code'$code);
  1150.         return $q->getQuery()->getSingleResult();
  1151.     }
  1152.     /**
  1153.      * @param $codes
  1154.      * @return mixed
  1155.      */
  1156.     public function getCollectionByCodes($codes)
  1157.     {
  1158.         $q $this->createQueryBuilder('c')
  1159.             ->andWhere('c.code in (:code)')
  1160.             ->setParameter('code'$codes);
  1161.         return $q->getQuery()->getResult();
  1162.     }
  1163.     /**
  1164.      * @param null $fid
  1165.      * @param array $onlyIds
  1166.      * @return array
  1167.      */
  1168.     public function admGetForJsTree($fid null, array $onlyIds = [])
  1169.     {
  1170.         $q $this->createQueryBuilder('c');
  1171.         $q->select('c.id, c.name, f.name as fname')
  1172.             ->leftJoin('c.factory''f')
  1173.             ->andWhere('c.status = :statusPub')
  1174.             ->orWhere('c.status = :statusCheck')
  1175.             ->addOrderBy('c.name''ASC')
  1176.             ->setParameter('statusPub'BiConst::STATE_PUBLISHED)
  1177.             ->setParameter('statusCheck'BiConst::STATE_CHECKING);
  1178.         if ($onlyIds) {
  1179.             $onlyIds implode(','$onlyIds);
  1180.             $q->andWhere("c.id IN ({$onlyIds})");
  1181.         }
  1182.         if ($fid) {
  1183.             $q->andWhere('f.id = :fid')
  1184.                 ->setParameter('fid'$fid);
  1185.         }
  1186.         $items $q->getQuery()->getArrayResult();
  1187.         $res = [];
  1188.         foreach ($items as $i => $item) {
  1189.             $res[$item['id']] = $item;
  1190.         }
  1191.         // сортироуем по имени
  1192.         $resSort array_column($res'name');
  1193.         array_multisort($resSortSORT_ASC$res);
  1194.         return $res;
  1195.     }
  1196.     /**
  1197.      * @param $cid
  1198.      * @return Collection|null
  1199.      */
  1200.     public function getByIdForParseAttr($cid)
  1201.     {
  1202.         $q $this->createQueryBuilder('c')
  1203.             ->select('c,f')
  1204.             ->leftJoin('c.factory''f')
  1205.             ->andWhere('c.id = :id')
  1206.             ->setParameter('id'$cid);
  1207.         try {
  1208.             $item $q->getQuery()->getOneOrNullResult();
  1209.         } catch (NonUniqueResultException $e) {
  1210.             $item null;
  1211.         }
  1212.         return $item;
  1213.     }
  1214.     /**
  1215.      * Получаем список ID коллекция для парсига их свойств
  1216.      * @param bool $onlyNull
  1217.      * @return array
  1218.      */
  1219.     public function getIdsForParseAttr($onlyNull false)
  1220.     {
  1221.         $q $this->createQueryBuilder('c')->select('c.id');
  1222.         if ($onlyNull) {
  1223.             $q->andWhere('c.fids IS NULL');
  1224.         }
  1225.         $ids $q->getQuery()->getArrayResult();
  1226.         if ($ids) {
  1227.             $ids array_column($ids'id');
  1228.         }
  1229.         return $ids;
  1230.     }
  1231.     /**
  1232.      * @param int $id
  1233.      * @return mixed
  1234.      * @throws NoResultException
  1235.      * @throws NonUniqueResultException
  1236.      * @todo remove from bi
  1237.      */
  1238.     public function _getCollectionsForFeed($id)
  1239.     {
  1240.         $q $this->createQueryBuilder('c')
  1241.             ->select('c,f')
  1242.             ->leftJoin('c.factory''f')
  1243.             ->leftJoin('c.articles''articles')
  1244.             ->leftJoin('c.interiors''interiors')
  1245.             ->andWhere('c.id = :id')
  1246.             ->setParameter('id'$id);
  1247.         $r $q->getQuery();
  1248.         $item $r->getSingleResult();
  1249.         return $item;
  1250.     }
  1251.     /**
  1252.      * @param array $params
  1253.      * @return array
  1254.      * @todo remove from bi
  1255.      */
  1256.     public function _getItemsForFeed($params = [])
  1257.     {
  1258.         $id = isset($params['code']) ? $params['code'] : null;
  1259.         $brand = isset($params['brand']) ? $params['brand'] : null;
  1260.         $limit = isset($params['limit']) ? $params['limit'] : null;
  1261.         $q $this->createQueryBuilder('c')
  1262.             ->select('c.id,c.code,c.name, f.name fname, fl.leftMenu, fc.alias')
  1263.             ->leftJoin('c.factory''f')
  1264.             ->leftJoin('f.filter''fl')
  1265.             ->leftJoin('f.country''fc')
  1266.             ->andWhere('c.status = :status1')
  1267.             ->setParameter('status1'BiConst::STATE_PUBLISHED)
  1268.             ->andWhere('f.status = :status')
  1269.             ->setParameter('status'BiConst::STATE_PUBLISHED);
  1270.         if ($id) {
  1271.             if ($id == 'test') {
  1272.                 $limit $limit $limit 50;
  1273.                 $q
  1274.                     ->setMaxResults($limit);
  1275.             } else {
  1276.                 $q
  1277.                     ->andWhere('c.id = :id')
  1278.                     ->setParameter('id'$id);
  1279.             }
  1280.         }
  1281.         if ($brand) {
  1282.             $q
  1283.                 ->andWhere('f.id = :brand')
  1284.                 ->setParameter('brand'$brand);
  1285.         }
  1286.         $q->addOrderBy('f.name''ASC');
  1287.         $q->addOrderBy('c.name''ASC');
  1288.         $r $q->getQuery();
  1289.         return $r->getArrayResult();
  1290.     }
  1291.     /**
  1292.      * Получение имени для графика статистик в админке
  1293.      * @param array $fids
  1294.      * @return array
  1295.      */
  1296.     public function getNamesForStatChartAdmin(array $fids)
  1297.     {
  1298.         $fidsStr implode(','$fids);
  1299.         $sql "SELECT
  1300.                 c.id,
  1301.                 c.name AS `name`,
  1302.                 f.name AS `fname`
  1303.             FROM
  1304.                 collection c
  1305.             LEFT JOIN factory f ON c.factory = f.id
  1306.             WHERE c.id IN ({$fidsStr})
  1307.             ORDER BY c.name ";
  1308.         $items $this->_em->getConnection()->fetchAll($sql);
  1309.         $r = [];
  1310.         foreach ($items as $item) {
  1311.             $id $item['id'];
  1312.             $r[$id] = [
  1313.                 'name' => "{$item['name']} ({$item['fname']})",
  1314.                 'data' => [],
  1315.             ];
  1316.         }
  1317.         return $r;
  1318.     }
  1319.     /**
  1320.      * @param $params
  1321.      * @return float|int|mixed|string
  1322.      * @todo remove from bi
  1323.      */
  1324.     public function _getItemsForCalculationImages($params = [])
  1325.     {
  1326.         $id = isset($params['code']) ? $params['code'] : null;
  1327.         $q $this->createQueryBuilder('c')
  1328.             ->andWhere('c.status = :status1')
  1329.             ->setParameter('status1'BiConst::STATE_PUBLISHED);
  1330.         if ($id) {
  1331.             if ($id == 'test') {
  1332.                 $limit 5;
  1333.                 $q
  1334.                     ->setMaxResults($limit);
  1335.             } else {
  1336.                 $q
  1337.                     ->andWhere('c.id = :id')
  1338.                     ->setParameter('id'$id);
  1339.             }
  1340.         }
  1341.         $r $q->getQuery();
  1342.         return $r->getResult();
  1343.     }
  1344.     /**
  1345.      * @param $param
  1346.      * @return mixed
  1347.      * @todo remove from bi
  1348.      */
  1349.     public function _getCollectionsForJpegtran($param)
  1350.     {
  1351.         $q $this->createQueryBuilder('c');
  1352.         if ($param['ides'] != 'all') {
  1353.             $q->andWhere('c.id IN (' join(', '$param['ides']) . ')');
  1354.         } else {
  1355.             if ($param['brand']) {
  1356.                 $q
  1357.                     ->leftJoin('c.factory''f')
  1358.                     ->andWhere('f.id IN (' join(', '$param['brand']) . ')');
  1359.             }
  1360.         }
  1361.         if (!empty($param['states'])) {
  1362.             $q->andWhere('c.status IN (' join(', '$param['states']) . ')');
  1363.         }
  1364.         $r $q->getQuery();
  1365.         return $r->getResult();
  1366.     }
  1367.     /**
  1368.      * @param null $code
  1369.      * @return array
  1370.      * @todo remove from bi
  1371.      */
  1372.     public function _getItemsForRenameAdblock($code null)
  1373.     {
  1374.         $q $this->createQueryBuilder('c')
  1375.             ->select('c.id, c.name, f.name fname')
  1376.             ->leftJoin('c.factory''f')
  1377.             ->andWhere('c.status = :status1')
  1378.             ->setParameter('status1'BiConst::STATE_PUBLISHED)
  1379.             ->andWhere('f.suspended <> :suspended')
  1380.             ->setParameter('suspended'BiConst::STATE_PUBLISHED);
  1381.         if ($code) {
  1382.             if ($code == 'test') {
  1383.                 $limit 50;
  1384.                 $q
  1385.                     ->setMaxResults($limit);
  1386.             } else {
  1387.                 $q
  1388.                     ->andWhere('c.id = :id')
  1389.                     ->setParameter('id'$code);
  1390.             }
  1391.         }
  1392.         $r $q->getQuery();
  1393.         return $r->getArrayResult();
  1394.     }
  1395.     /**
  1396.      * Ищем коллекцию для проставления связи с коллекцией выставки
  1397.      * @param string $cName
  1398.      * @param int $bid
  1399.      * @return array|null
  1400.      */
  1401.     public function getCollByNameForExh(string $cNameint $bid)
  1402.     {
  1403.         $conn $this->_em->getConnection();
  1404.         $cName $conn->quote($cName);
  1405.         $sql "SELECT
  1406.                 `c`.id AS `id`,
  1407.                 `c`.name AS `name`,
  1408.                 `c`.name_full AS `nameFull`,
  1409.                 `c`.alternate_name AS `nameAlt`,
  1410.                 `brand`.id AS `brandId`,
  1411.                 `brand`.name AS `brandName`
  1412.             FROM
  1413.                 collection c
  1414.             LEFT JOIN factory `brand` ON `brand`.id = `c`.factory
  1415.             WHERE (`c`.`name` LIKE {$cName} OR  `c`.`name_full` LIKE {$cName}  OR  `c`.`alternate_name` LIKE {$cName}) AND `c`.factory = {$bid}
  1416.             ";
  1417.         $items $conn->fetchAll($sql);
  1418.         return $items $items[0] : null;
  1419.     }
  1420.     public function getCollectionsForSliderNative($id)
  1421.     {
  1422.         $rsm = new ResultSetMapping();
  1423.         $rsm->addEntityResult('WebBundle\Entity\Collection''c');
  1424.         $rsm->addFieldResult('c''id''id');
  1425.         $rsm->addFieldResult('c''name''name');
  1426.         $rsm->addFieldResult('c''alternate_name''alternateName');
  1427.         $rsm->addFieldResult('c''url''url');
  1428.         $rsm->addFieldResult('c''header''header');
  1429.         $rsm->addFieldResult('c''settings''settings');
  1430.         $rsm->addFieldResult('c''rating''rating');
  1431.         $rsm->addFieldResult('c''status''status');
  1432.         $rsm->addJoinedEntityResult('WebBundle\Entity\Factory''f''c''factory');
  1433.         $rsm->addFieldResult('f''f_id''id');
  1434.         $rsm->addFieldResult('f''f_name''name');
  1435.         $rsm->addFieldResult('f''f_url''url');
  1436.         $rsm->addFieldResult('f''f_stated_at''statedAt');
  1437.         $rsm->addFieldResult('f''f_status''status');
  1438.         $rsm->addJoinedEntityResult('WebBundle\Entity\FilterEntity''fl''f''filter');
  1439.         $rsm->addFieldResult('fl''fl_id''id');
  1440.         $rsm->addJoinedEntityResult('WebBundle\Entity\FilterParamEntity''flp''fl''param');
  1441.         $rsm->addFieldResult('flp''flp_id''id');
  1442.         $rsm->addFieldResult('flp''flp_code''code');
  1443.         $rsm->addJoinedEntityResult('WebBundle\Entity\FilterEntity''flc''fl''country');
  1444.         $rsm->addFieldResult('flc''flc_id''id');
  1445.         $rsm->addFieldResult('flc''flc_left_menu''leftMenu');
  1446.         $query $this->_em->createNativeQuery(
  1447.             "SELECT
  1448.               c.id,
  1449.               c.name,
  1450.               c.alternate_name,
  1451.               c.url,
  1452.               c.header,
  1453.               c.settings,
  1454.               c.rating,
  1455.               c.status,
  1456.               f.id AS f_id,
  1457.               f.name AS f_name,
  1458.               f.url AS f_url,
  1459.               f.stated_at AS f_stated_at,
  1460.               f.status AS f_status,
  1461.               fl.id AS fl_id,
  1462.               fl.country_id AS fl_country_id,
  1463.               flc.id AS flc_id,
  1464.               flc.left_menu AS flc_left_menu,
  1465.               flp.id AS flp_id,
  1466.               flp.code AS flp_code
  1467.             FROM
  1468.               collection c
  1469.             LEFT JOIN factory f ON f.id = c.factory
  1470.             LEFT JOIN filters fl ON fl.id = f.filter
  1471.             LEFT JOIN filters flc ON flc.id = fl.country_id
  1472.             LEFT JOIN filter_params flp ON flp.id = flc.param_id
  1473.             WHERE c.id ={$id} ",
  1474.             $rsm
  1475.         );
  1476.         $result $query->getArrayResult();
  1477.         return array_shift($result);
  1478.     }
  1479.     /**
  1480.      * @param int $cid
  1481.      * @return false|string
  1482.      * @throws DBALException
  1483.      */
  1484.     public function getNameForFilterHistorySearch(int $cid)
  1485.     {
  1486.         $sql "SELECT
  1487.                 c.name AS `name`
  1488.             FROM
  1489.                 collection c
  1490.             WHERE
  1491.                 c.id = '{$cid}'";
  1492.         $items $this->_em
  1493.             ->getConnection()
  1494.             ->executeQuery($sql)
  1495.             ->fetchColumn(0);
  1496.         return $items;
  1497.     }
  1498.     /**
  1499.      * Получение ID для сбора рекомендаций в админку для теста
  1500.      * @param string $fUrl
  1501.      * @param string $cUrl
  1502.      * @return int|null
  1503.      */
  1504.     public function getCollIdForNeyronAdmin(string $fUrlstring $cUrl)
  1505.     {
  1506.         $conn $this->_em->getConnection();
  1507.         $fUrl $str mb_strtolower($fUrl'UTF-8');
  1508.         $cUrl $str mb_strtolower($cUrl'UTF-8');
  1509.         $sql "SELECT
  1510.                 c.id
  1511.             FROM
  1512.                 collection c
  1513.             LEFT JOIN factory f ON f.id = c.factory
  1514.             WHERE c.url = '{$cUrl}' AND f.url = '{$fUrl}'
  1515.             ";
  1516.         $id $conn->fetchAll($sql);
  1517.         if ($id) {
  1518.             $id $id[0]['id'];
  1519.         } else {
  1520.             $id null;
  1521.         }
  1522.         return $id;
  1523.     }
  1524.     /**
  1525.      * Получение списка ID фильтров для сбора рекомендаций в админку для теста
  1526.      * @param array $cids
  1527.      * @return array
  1528.      */
  1529.     public function getCollFidsdForNeyronAdmin(array $cids)
  1530.     {
  1531.         $conn $this->_em->getConnection();
  1532.         $cids implode(', '$cids);
  1533.         $sql "SELECT
  1534.                 c.id,
  1535.                 c.fids
  1536.             FROM
  1537.                 collection c
  1538.             WHERE c.id IN ({$cids})
  1539.             ";
  1540.         $rows $conn->fetchAll($sql);
  1541.         $items = [];
  1542.         foreach ($rows as $row) {
  1543.             $items[$row['id']] = json_decode($row['fids']);
  1544.         }
  1545.         return $items;
  1546.     }
  1547.     /**
  1548.      * @param $params
  1549.      * @return float|int|mixed[]|string
  1550.      * @todo remove from bi
  1551.      */
  1552.     public function _getItemsForInteriorCyrilic($params = [])
  1553.     {
  1554.         $id = isset($params['code']) ? $params['code'] : null;
  1555.         $brand = isset($params['brand']) ? $params['brand'] : null;
  1556.         $limit = isset($params['limit']) ? $params['limit'] : null;
  1557.         $q $this->createQueryBuilder('c')
  1558.             ->select('c.id, c.name, c.url curl, f.name fname, f.url furl')
  1559.             ->leftJoin('c.factory''f')
  1560.             ->andWhere('c.status = :status1')
  1561.             ->setParameter('status1'BiConst::STATE_PUBLISHED)
  1562.             ->andWhere('f.suspended <> :suspended')
  1563.             ->setParameter('suspended'BiConst::STATE_PUBLISHED);
  1564.         if ($id) {
  1565.             if ($id == 'test') {
  1566.                 $limit $limit $limit 50;
  1567.                 $q
  1568.                     ->setMaxResults($limit);
  1569.             } else {
  1570.                 $q
  1571.                     ->andWhere('c.id = :id')
  1572.                     ->setParameter('id'$id);
  1573.             }
  1574.         }
  1575.         if ($brand) {
  1576.             $q
  1577.                 ->andWhere('f.id = :brand')
  1578.                 ->setParameter('brand'$brand);
  1579.         }
  1580.         $r $q->getQuery();
  1581.         return $r->getArrayResult();
  1582.     }
  1583.     /**
  1584.      * @param $params
  1585.      * @return array
  1586.      * @throws Exception
  1587.      * @todo remove from bi
  1588.      */
  1589.     public function _getCollectionsIDSForCheckList($params)
  1590.     {
  1591.         $page = isset($params['page']) ? $params['page'] : 1;
  1592.         $limit = isset($params['limit']) ? $params['limit'] : BiConst::SEARCH_RESULT_ON_PAGE;
  1593.         $offset $limit * ($page 1);
  1594.         $states = !empty($params['states']) ? $params['states'] : null;
  1595.         $checkId = isset($params['check_id']) ? $params['check_id'] : 'all';
  1596.         $isCheckAll $checkId == 'all';
  1597.         $suspended = !empty($params['suspended']) ? $params['suspended'] : null;
  1598.         $manager = isset($params['manager']) ? $params['manager'] : 'all';
  1599.         $brand = isset($params['brand']) ? $params['brand'] : 'all';
  1600.         $sqlWhereUser '';
  1601.         if ($manager == 'all') {
  1602.             $sqlWhereManager '';
  1603.         } else {
  1604.             $sqlWhereManager "AND u.id = '{$manager}'";
  1605.         }
  1606.         if ($brand == 'all') {
  1607.             $sqlWhereBrand '';
  1608.         } else {
  1609.             $sqlWhereBrand "AND f.unid = '{$brand}'";
  1610.         }
  1611.         if ($isCheckAll) {
  1612.             $user App::getCurUser();
  1613.             $sqlWhereCheckId '';
  1614.             if ($user->hasRole('ROLE_BM')) {
  1615.                 $sqlWhereManager "AND u.id = '{$user->getId()}'";
  1616.                 if ($suspended) {
  1617.                     $sqlWhereCheckId "AND chl.code IN ('has_suspended_article', 'has_suspended_collection')";
  1618.                 }
  1619.             }
  1620.         } else {
  1621.             $sqlWhereCheckId "AND chl.code = '{$checkId}'";
  1622.         }
  1623.         $sql "
  1624.             SELECT
  1625.                 c.id
  1626.             FROM
  1627.                 collection c
  1628.             LEFT JOIN `factory` f ON f.id = c.factory
  1629.             LEFT JOIN `user` u ON u.id = f.user_id
  1630.             LEFT JOIN `check_list` chl ON chl.collection = c.id AND chl.showed = 1 {$sqlWhereCheckId}
  1631.             WHERE c.status = {$states}
  1632.                 AND c.factory > '0'
  1633.                 {$sqlWhereManager}
  1634.                 {$sqlWhereUser}
  1635.                 {$sqlWhereBrand}
  1636.             GROUP BY c.id
  1637.             HAVING COUNT(DISTINCT chl.id) > 0
  1638.             ORDER BY u.alias, f.url, c.url";
  1639.         $idsAll ConnectionHelper::getInstance()->executeFetchAllSql($sqlPDO::FETCH_COLUMN);
  1640.         $all count($idsAll);
  1641.         $sql $sql "    LIMIT {$limit} OFFSET {$offset};";
  1642.         $ids ConnectionHelper::getInstance()->executeFetchAllSql($sqlPDO::FETCH_COLUMN);
  1643.         return [
  1644.             'ids' => $ids,
  1645.             'allItems' => $all,
  1646.         ];
  1647.     }
  1648.     /**
  1649.      * @param $code
  1650.      * @return float|int|mixed|string
  1651.      * @todo remove from bi
  1652.      */
  1653.     public function _getCollectionByDesigner($code null)
  1654.     {
  1655.         $q $this->createQueryBuilder('c')
  1656.             ->leftJoin('c.factory''f')
  1657.             ->orWhere('c.status = :status1')
  1658.             ->orWhere('c.status = :status4')
  1659.             ->setParameter('status1'BiConst::STATE_PUBLISHED)
  1660.             ->setParameter('status4'BiConst::STATE_PROCESSING);
  1661.         if ($code) {
  1662.             $q
  1663.                 ->andWhere('c.id = :id')
  1664.                 ->setParameter('id'$code);
  1665.         }
  1666.         $q
  1667.             ->addOrderBy('f.name''ASC')
  1668.             ->addOrderBy('c.name''ASC');
  1669.         $r $q->getQuery();
  1670.         return $r->getResult();
  1671.     }
  1672.     /**
  1673.      * @param array $params
  1674.      * @return array|int|string
  1675.      * @todo remove from bi
  1676.      */
  1677.     public function _getItemsMainInteriorCreate($params = [])
  1678.     {
  1679.         $id = isset($params['code']) ? $params['code'] : null;
  1680.         $brand = isset($params['brand']) ? $params['brand'] : null;
  1681.         $limit = isset($params['limit']) ? $params['limit'] : null;
  1682.         $q $this->createQueryBuilder('c')
  1683.             ->select('c.id, c.name, c.url curl, f.name fname, f.url furl')
  1684.             ->leftJoin('c.factory''f')
  1685.             ->andWhere('c.status = :status1')
  1686.             ->setParameter('status1'BiConst::STATE_PUBLISHED)
  1687.             ->andWhere('f.suspended <> :suspended')
  1688.             ->setParameter('suspended'BiConst::STATE_PUBLISHED);
  1689.         if ($id) {
  1690.             if ($id == 'test') {
  1691.                 $limit $limit $limit 50;
  1692.                 $q
  1693.                     ->setMaxResults($limit);
  1694.             } else {
  1695.                 $q
  1696.                     ->andWhere('c.id = :id')
  1697.                     ->setParameter('id'$id);
  1698.             }
  1699.         }
  1700.         if ($brand) {
  1701.             if (is_numeric($brand)) {
  1702.                 $q->andWhere('f.id =:brand');
  1703.             } else {
  1704.                 $q->andWhere('f.name =:brand');
  1705.             }
  1706.             $q->setParameter('brand'$brand);
  1707.         }
  1708.         $r $q->getQuery();
  1709.         $out $r->getArrayResult();
  1710.         return $out;
  1711.     }
  1712.     /**
  1713.      * @param $param
  1714.      * @return float|int|mixed|string
  1715.      * @todo remove from bi
  1716.      */
  1717.     public function _getCollectionsForRecrop($param)
  1718.     {
  1719.         $q $this->createQueryBuilder('c');
  1720.         if ($param['ides'] != 'all') {
  1721.             $q->andWhere('c.id IN (' join(', '$param['ides']) . ')');
  1722.         } else {
  1723.             if ($param['brand']) {
  1724.                 $q
  1725.                     ->leftJoin('c.factory''f')
  1726.                     ->andWhere('f.id IN (' join(', '$param['brand']) . ')');
  1727.             }
  1728.         }
  1729.         if (!empty($param['states'])) {
  1730.             $q->andWhere('c.status IN (' join(', '$param['states']) . ')');
  1731.         }
  1732.         $r $q->getQuery();
  1733.         return $r->getResult();
  1734.     }
  1735.     /**
  1736.      * Получение коллекций для выгрузки в Google Recommendations AI
  1737.      *
  1738.      * @param integer $limit
  1739.      * @param integer $offset
  1740.      * @return array
  1741.      */
  1742.     public function getCollectionsForGoogleRecommendationAi($limit 10$offset 0)
  1743.     {
  1744.         $builder $this->createQueryBuilder('c');
  1745.         $builder->select('c.id''c.name')
  1746.             ->where('c.status IN (1,2,3,4,7)')
  1747.             ->where('c.archive = 0')
  1748.             ->andWhere('c.url IS NOT NULL AND c.url <> \'\'')
  1749.             ->setMaxResults($limit)
  1750.             ->setFirstResult($offset);
  1751.         $query $builder->getQuery();
  1752.         $rows $query->getResult();
  1753.         return $rows;
  1754.     }
  1755.     /**
  1756.      * @return array|bool
  1757.      * @throws Exception
  1758.      * @todo remove from bi
  1759.      */
  1760.     public function _getModalTempateDescriptionInsert()
  1761.     {
  1762.         $sql "SELECT c.id, c.name, f.name fname,f.url furl FROM %s.collection c JOIN %s.factory f ON f.id=c.factory WHERE c.`status`=1 ORDER BY c.name;";
  1763.         $items ConnectionHelper::getInstance()->executeFetchAllSql($sql);
  1764.         return $items;
  1765.     }
  1766.     /**
  1767.      * @return float|int|mixed|string
  1768.      * @todo remove from bi
  1769.      */
  1770.     public function _getCollectionForAddEventDescription()
  1771.     {
  1772.         $q $this->createQueryBuilder('c')
  1773.             ->select('c,b')
  1774.             ->leftJoin('c.body''b')
  1775.             ->orWhere('b.ru like :simple')
  1776.             ->orWhere('b.ru like :multi')
  1777.             ->setParameter('simple''%В интерьерах также использована плитка из коллекци%')
  1778.             ->setParameter('multi''%В одном из интерьеров также использована плитка из коллекци%');
  1779.         $r $q->getQuery();
  1780.         $items $r->getResult();
  1781.         return $items;
  1782.     }
  1783.     /**
  1784.      * @param $furl
  1785.      * @param $curl
  1786.      * @return float|int|mixed|string|null
  1787.      * @throws NonUniqueResultException
  1788.      * @todo remove from bi
  1789.      */
  1790.     public function _getCollectionsByDescriptionCorrect($furl$curl)
  1791.     {
  1792.         $r $this->createQueryBuilder('c')
  1793.             ->select('c,f')
  1794.             ->leftJoin('c.factory''f')
  1795.             ->andWhere('f.url = :furl')
  1796.             ->andWhere('c.url = :curl')
  1797.             ->setParameter('furl'$furl)
  1798.             ->setParameter('curl'$curl)
  1799.             ->getQuery();
  1800.         return $r->getOneOrNullResult();
  1801.     }
  1802.     /**
  1803.      * @param $params
  1804.      * @return float|int|mixed|string
  1805.      * @todo remove from bi
  1806.      */
  1807.     public function _getItemsForConvertDesigner($params = [])
  1808.     {
  1809.         $id = isset($params['code']) ? $params['code'] : null;
  1810.         $brand = isset($params['brand']) ? $params['brand'] : null;
  1811.         $q $this->createQueryBuilder('c')
  1812.             ->leftJoin('c.factory''f')
  1813.             ->andWhere('LENGTH(c.author)>0');
  1814.         if ($id) {
  1815.             $q
  1816.                 ->andWhere('c.id = :id')
  1817.                 ->setParameter('id'$id);
  1818.         } elseif ($brand) {
  1819.             $q
  1820.                 ->andWhere('f.id = :brand')
  1821.                 ->setParameter('brand'$brand);
  1822.         }
  1823.         $q->addOrderBy('f.name''ASC');
  1824.         $q->addOrderBy('c.name''ASC');
  1825.         $r $q->getQuery();
  1826.         return $r->getResult();
  1827.     }
  1828.     public function getListForUpdate($full false)
  1829.     {
  1830.         $q $this
  1831.             ->createQueryBuilder('c')
  1832.             ->select('c.id, c.code, f.unid, c.status, c.url')
  1833.             ->leftJoin('c.factory''f')
  1834.             ->andWhere('c.status IN (:status_1, :status_4, :status_7)')
  1835.             ->setParameter('status_1'BiConst::STATE_PUBLISHED)
  1836.             ->setParameter('status_4'BiConst::STATE_PROCESSING)
  1837.             ->setParameter('status_7'BiConst::STATE_CHECKING);
  1838.         if (!App::isRole('ROLE_TEST')) {
  1839.             $q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
  1840.             $q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
  1841.         }
  1842.         $items $q
  1843.             ->getQuery()
  1844.             ->useQueryCache($full)
  1845.             ->getArrayResult();
  1846.         return $items;
  1847.     }
  1848.     /**
  1849.      * @param array $ids
  1850.      * @return array
  1851.      */
  1852.     public function getCollAuthorIds(array $ids)
  1853.     {
  1854.         $ids implode("','"$ids);
  1855.         $q $this
  1856.             ->createQueryBuilder('c')
  1857.             ->select('c.authorId')
  1858.             ->andWhere("c.id IN ('{$ids}')")
  1859.             ->andWhere('c.status IN (:status_1, :status_4, :status_7)')
  1860.             ->setParameter('status_1'BiConst::STATE_PUBLISHED)
  1861.             ->setParameter('status_4'BiConst::STATE_PROCESSING)
  1862.             ->setParameter('status_7'BiConst::STATE_CHECKING);
  1863.         $items $q->getQuery()->getArrayResult();
  1864.         $ids = [];
  1865.         if ($items) {
  1866.             foreach ($items as $item) {
  1867.                 if (is_array($item['authorId'])) {
  1868.                     $ids[] = $item['authorId'][0];
  1869.                 } else {
  1870.                     $ids[] = $item['authorId'];
  1871.                 }
  1872.             }
  1873.         }
  1874.         return $ids;
  1875.     }
  1876.     public function increaseViewByCollectionId(int $collId): void
  1877.     {
  1878.         try {
  1879.             $this
  1880.                 ->getEntityManager()
  1881.                 ->getConnection()
  1882.                 ->prepare('UPDATE `collection` SET `views` = `views` + \'1\' WHERE `id` = :id')
  1883.                 ->executeQuery(['id' => $collId]);
  1884.         } catch (DriverException DoctrineDBALException LockWaitTimeoutException $e) {
  1885.             return;
  1886.         }
  1887.     }
  1888.     private function getRating($id$actualData): int
  1889.     {
  1890.         /** @var Collection $collection */
  1891.         foreach ($actualData as $collection) {
  1892.             if ($collection->getId() === $id) {
  1893.                 return $collection->getRating();
  1894.             }
  1895.         }
  1896.         return 0;
  1897.     }
  1898.     public function save(Collection $ideabool $flush false): void
  1899.     {
  1900.         $this->getEntityManager()->persist($idea);
  1901.         if ($flush) {
  1902.             $this->flush();
  1903.         }
  1904.     }
  1905.     public function flush(): void
  1906.     {
  1907.         $this->getEntityManager()->flush();
  1908.     }
  1909.     public function getFilteredCollectionIds(array $params, array $articleIds): array
  1910.     {
  1911.         $qb $this->getEntityManager()->createQueryBuilder();
  1912.         $qb->select('c.id')
  1913.             ->from(Collection::class, 'c')
  1914.             ->innerJoin('c.articles''a')
  1915.             ->where('c.status = :status')
  1916.             ->setParameter('status'BiConst::STATE_PUBLISHED)
  1917.             ->distinct();
  1918.         $qb->andWhere($qb->expr()->in('a.id'':ids'))
  1919.             ->setParameter('ids'$articleIds);
  1920.         if (isset($params['manufacturer'])) {
  1921.             $qb->andWhere($qb->expr()->in('c.factory'':fids'))
  1922.                 ->setParameter('fids'$params['manufacturer']);
  1923.         }
  1924.         foreach ($params as $key => $value) {
  1925.             $this->buildQueryFromConfig($qb$key$value);
  1926.         }
  1927.         return $qb->getQuery()->getResult();
  1928.     }
  1929.     private function buildQueryFromConfig(QueryBuilder $qb$key, array $value): void
  1930.     {
  1931.         if (!isset(self::COLLECTION_QUERY_FILTER_MAPPING[$key])) {
  1932.             return;
  1933.         }
  1934.         $config self::COLLECTION_QUERY_FILTER_MAPPING[$key];
  1935.         $alias $config['alias'];
  1936.         $field $config['field'];
  1937.         if ($key === 'rewards') {
  1938.             $qb->andWhere($qb->expr()->isNotNull("$alias.$field"));
  1939.             return;
  1940.         }
  1941.         if (isset($config['join'])) {
  1942.             $path $config['join']['path'];
  1943.             if ($key === 'reviews') {
  1944.                 $qb->innerJoin($path$alias'WITH''c.id = ' $alias '.collection');
  1945.             } else {
  1946.                 $qb->innerJoin($path$alias);
  1947.             }
  1948.         }
  1949.         $qb->andWhere($qb->expr()->in("$alias.$field"":$key"))->setParameter($key$value);
  1950.     }
  1951. }