src/WebBundle/Repository/CollectionRepository.php line 721

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