<?php
namespace WebBundle\Repository;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Exception as DriverException;
use Doctrine\DBAL\Exception as DoctrineDBALException;
use Doctrine\DBAL\Exception\LockWaitTimeoutException;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\QueryBuilder;
use Exception;
use FlexApp\Classes\CommentableEntityTypes;
use FlexApp\Constant\TimeConstant;
use FlexApp\Entity\CommentEntity;
use FlexApp\Repository\CommentRepository;
use FlexApp\Service\RedisCachePool;
use Import1CBundle\Helper\v3\BiConst;
use Import1CBundle\Helper\v3\ConnectionHelper;
use PDO;
use WebBundle\Entity\Collection;
use WebBundle\Entity\User;
use WebBundle\Helper\App;
use WebBundle\Helper\ArrHelper;
use WebBundle\Helper\HideFactoryCountriesHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\PathHelper;
class CollectionRepository extends ExtendEntityRepository
{
/**
* Получаем коллекции с учетом локали, где есть хотя бы один коммент
* @param $locale
* @return array
*/
public function getActivePagesArrays($locale): array
{
$query = $this->getEntityManager()->createQuery("
SELECT
DISTINCT coll.unid as portalThemeUnid
FROM WebBundle\Entity\Collection coll
JOIN FlexApp\Entity\CommentEntity comm
WITH COLLATE(coll.unid,utf8mb4_unicode_ci) = COLLATE(comm.commentableUnid,utf8mb4_unicode_ci)
AND comm.locale = :locale
");
$query->setParameter('locale', $locale);
$result = $query->getResult();
foreach ($result as &$row) {
$row['locale'] = $locale;
$row['type'] = CommentableEntityTypes::COLLECTION;
}
return $result;
}
/**
* @param string $alias
* @return QueryBuilder
*/
public function joinQuery($alias = 'c')
{
return $this->createQueryBuilder($alias)
->select("{$alias}, body, metaDescription, metaKeywords")
->leftJoin("{$alias}.body", 'body')
->leftJoin("{$alias}.metaDescription", 'metaDescription')
->leftJoin("{$alias}.metaKeywords", 'metaKeywords')
->leftJoin("{$alias}.factory", 'factory')
->leftJoin('factory.user', 'user');
}
public function getCollectionsProcess()
{
$q = $this->createQueryBuilder('c')
->select('c, f')
->innerJoin('c.factory', 'f')
->leftJoin('c.interiors', 'i')
->andWhere('c.status = :status')
->andWhere('f.status = :status')
->andWhere('i.status = 1')
->andWhere('i.file IS NOT NULL')
->andWhere('c.process IS NULL')
->groupBy('i.id')
->setParameter('status', BiConst::STATE_PUBLISHED);
return $q->getQuery()->getResult();
}
/**
* НЕ ИЗМЕНЯТЬ специальный запрос для API
* @param null $factoryId
* @return array|null
*/
public function getCollectionsArrayAPI($factoryId = null)
{
$q = $this->createQueryBuilder('c')
->select('c.id,c.name,c.alternateName,c.code')
->leftJoin('c.factory', 'f')
->andWhere('c.status = :status')
->setParameter('status', BiConst::STATE_PUBLISHED);
if (!empty($factoryId)) {
$q->andWhere('f.id = :factory OR f.unid = :factory')
->setParameter('factory', $factoryId);
}
return $q->getQuery()->getArrayResult();
}
/**
* @param null $factoryId
* @param null $status
* @return array
* @throws Exception
*/
public function getCollectionsStatusArrayAPI($factoryId = null, $status = null)
{
$q = $this->createQueryBuilder('c')
->select('c.id,c.name,c.alternateName,c.code')
->leftJoin('c.factory', 'f');
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
if (!empty($factoryId) and $factoryId != 'all') {
$q->andWhere('f.id = :factory OR f.unid = :factory')
->setParameter('factory', $factoryId);
}
$states = BiConst::listStateAll();
if ($status !== null and in_array($status, $states)) {
$q->andWhere('c.status = :status')
->setParameter('status', $status);
}
$r = $q->getQuery();
$result = $r->getArrayResult();
return $result;
}
/**
* @param $cId
* @return mixed
* @throws NonUniqueResultException
* @throws NoResultException
*/
public function collectionCountInteriors($cId)
{
return $this->createQueryBuilder('c')
->select('count(i.id)')
->leftJoin('c.interiors', 'i')
->where('i.status = 1')
->andWhere('c.id = :id')
->setParameter('id', $cId)
->getQuery()
->enableResultCache()
->getSingleScalarResult();
}
/**
* @return QueryBuilder
* @throws Exception
*/
private function queryForCommandHeader()
{
$q = $this->createQueryBuilder('c')
->select('c.id, m.id material, t.id type')
->leftJoin('c.factory', 'f')
->leftJoin('c.articles', 'a')
->leftJoin('a.type', 't')
->leftJoin('a.material', 'm')
->andWhere('f.status IN (1,2,3)')
->andWhere('f.unid IS NOT null')
->andWhere('c.status != 0')
->andWhere('a.delivery != 6 OR a.delivery = 6 AND (f.status IN (2,3) OR c.status IN (2,3))')
->orderBy('f.name');
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
return $q;
}
/**
* @param array $params
* @return array
* @throws Exception
*/
public function getCollectionsForCommandHeader($params = [])
{
$q = $this->queryForCommandHeader();
if (!empty($params['id'])) {
$q->andWhere('c.id = :id')
->setParameter('id', $params['id']);
}
$r = $q->getQuery()
->useQueryCache(true)
->enableResultCache(3600);
$res = [];
$items = $r->getArrayResult();
foreach ($items as $item) {
$res[$item['id']]['articles'][] = [
'type' => $item['type'],
'material' => $item['material'],
];
}
return $res;
}
/**
* @param $id
* @return null
* @throws Exception
*/
public function getCollForAlsoById($id)
{
$q = $this->createQueryBuilder('c')
->select('c, fc')
->leftJoin('c.factory', 'fc')
->andWhere('c.id = :id')
->setParameter('id', $id);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('fc.testAccess IS NULL OR fc.testAccess = 0');
}
$r = $q->getQuery()
->useQueryCache(true)
->enableResultCache(3600 * 24 * 30);
$result = $r->getResult();
$item = count($result) > 0 ? $result[0] : null;
return $item;
}
/**
* @param $id
* @return null
* @throws Exception
*/
public function getCollAuthor($id)
{
$q = $this->createQueryBuilder('c')
->select('c.author')
->andWhere('c.id = :id')
->setParameter('id', $id);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
}
$r = $q->getQuery()
->useQueryCache(true)
->enableResultCache(3600 * 24 * 30);
$result = $r->getArrayResult();
$item = count($result) > 0 ? $result[0]['author'] : null;
return $item;
}
/**
* @param null $c_name
* @param null $f_name
* @return array
* @throws Exception
*/
public function getCollectionsF($c_name = null, $f_name = null)
{
$q = $this->createQueryBuilder('c')
->select('c.url c_url, c.code c_code, c.name c_name, f.url f_url, f.id f_id')
->leftJoin('c.factory', 'f')
->leftJoin('c.interiors', 'i')
->andWhere('c.status = :c_status')
->andWhere('f.status = :f_status')
->andWhere('i.status < :i_status OR i.status is null')
->setParameter('c_status', BiConst::STATE_PUBLISHED)
->setParameter('f_status', BiConst::STATE_PUBLISHED)
->setParameter('i_status', BiConst::STATE_DISCONTINUED)
->groupBy('c.id');
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
if (!empty($c_name) && !empty($f_name)) {
$q->andWhere('c.name LIKE :c_name')
->andWhere('f.name LIKE :f_name')
->setParameter('c_name', $c_name)
->setParameter('f_name', $f_name);
}
$r = $q->getQuery()
->useQueryCache(true);
return $r->getArrayResult();
}
/**
* @param $code
* @return null
* @throws Exception
*/
public function getCollBM($code)
{
$q = $this->createQueryBuilder('c')
->select('c.code c_code, c.name c_name, c.url c_url, f.url f_url, f.name f_name, u.username')
->leftJoin('c.factory', 'f')
->leftJoin('f.user', 'u')
->andWhere('c.code=:code')
->setParameter('code', $code)
->setMaxResults(1);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
$r = $q->getQuery()->useQueryCache(false);
$items = $r->getArrayResult();
return empty($items[0]) ? null : $items[0];
}
/**
* @param $ides
* @param $limit
* @param string $sign
* @return array
* @throws Exception
*/
public function getCollectionAlsoViewedNative($ides, $limit, $sign = 'IN')
{
// на случай если в массиве один элемент чтобы работало FIELD
$ides = array_merge([0], $ides);
$rsm = new ResultSetMapping;
$rsm->addEntityResult('WebBundle\Entity\Collection', 'c');
$rsm->addFieldResult('c', 'id', 'id');
$rsm->addFieldResult('c', 'name', 'name');
$rsm->addFieldResult('c', 'alternate_name', 'alternateName');
$rsm->addFieldResult('c', 'url', 'url');
$rsm->addFieldResult('c', 'awards', 'awards');
$rsm->addFieldResult('c', 'publish_date', 'publishDate');
$rsm->addFieldResult('c', 'rating', 'rating');
$rsm->addJoinedEntityResult('WebBundle\Entity\Factory', 'f', 'c', 'factory');
$rsm->addFieldResult('f', 'f_id', 'id');
$rsm->addFieldResult('f', 'f_name', 'name');
$rsm->addFieldResult('f', 'f_alternate_name', 'alternateName');
$rsm->addFieldResult('f', 'f_url', 'url');
$rsm->addJoinedEntityResult('WebBundle\Entity\ListCountry', 'lc', 'f', 'country');
$rsm->addFieldResult('lc', 'lc_id', 'id');
$rsm->addFieldResult('lc', 'lc_alias', 'alias');
$rsm->addFieldResult('lc', 'lc_code', 'code');
$rsm->addJoinedEntityResult('WebBundle\Entity\Interior', 'i', 'c', 'interiors');
$rsm->addEntityResult('WebBundle\Entity\Interior', 'i');
$rsm->addFieldResult('i', 'i_id', 'id');
$ides = join(',', $ides);
$sort = $sign == 'IN' ? "FIELD({$ides})" : 'c.id';
$where = '';
if (!App::isRole('ROLE_TEST')) {
$where = ' AND c.test_access IS NULL AND f.test_access IS NULL AND (c.accessible IS NULL OR c.accessible = 0)';
}
$query = $this->_em->createNativeQuery(
"SELECT
c.id,
c.name,
c.alternate_name,
c.url,
c.awards,
c.publish_date,
c.rating,
f.id AS f_id,
f.name AS f_name,
f.alternate_name AS f_alternate_name,
f.url AS f_url,
lc.id AS lc_id,
lc.alias AS lc_alias,
lc.code AS lc_code,
i.id AS i_id
FROM
collection c
LEFT JOIN factory f ON f.id = c.factory
LEFT JOIN list_country lc ON lc.id = f.country
LEFT JOIN interior i ON c.id = i.collection
WHERE i.is_main = 1{$where} AND c.id {$sign} ({$ides}) AND c.status = 1 AND f.status = 1
GROUP BY c.id
ORDER BY {$sort} DESC, i.is_main DESC, i.is_head DESC LIMIT {$limit}",
$rsm
);
return $query->getArrayResult();
}
/**
* @param $id
* @return array
* @throws Exception
*/
public function getCollectionForInformer(int $id): array
{
$q = $this->createQueryBuilder('c')
->select('c,f,a,measure,measurementSize')
->leftJoin('c.factory', 'f')
->leftJoin('c.articles', 'a')
->leftJoin('a.measure', 'measure')
->leftJoin('a.measurementSize', 'measurementSize')
->andWhere('c.id = :id')
->setParameter('id', $id);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
}
$r = $q->getQuery()
->useQueryCache(true);
$items = $r->getArrayResult();
if (count($items) > 0) {
return $items[0];
}
return [];
}
/**
* @param $factoryUrl
* @param $collectionUrl
* @return array|mixed|null
* @throws Exception
*/
public function getSlideCollection($factoryUrl, $collectionUrl)
{
$q = $this->createQueryBuilder('c')
->addSelect('f, ct')
->innerJoin('c.factory', 'f')
->innerJoin('f.country', 'ct')
->andWhere('f.url = :factory')
->andWhere('c.url = :collection')
->andWhere('c.status IN (:cStatus)')
->setParameters([
'factory' => $factoryUrl,
'collection' => $collectionUrl,
'cStatus' => [
BiConst::STATE_PUBLISHED,
BiConst::STATE_DISCONTINUED,
BiConst::STATE_WORK_CONTINUED,
BiConst::STATE_CHECKING,
BiConst::STATE_PROCESSING,
],
]);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
$item = $q->setMaxResults(1)
->getQuery()
->enableResultCache(TimeConstant::HOUR)
->getArrayResult();
if (empty($item[0])) {
return null;
}
$res = $item[0];
// закрываем некоторые фабрики для некоторых стран
if (in_array($res['factory']['id'], HideFactoryCountriesHelper::codes())) {
$res['factory']['status'] = 3;
$res['status'] = 3;
}
if (!empty($res['status']) && $res['status'] > 3) {
$res['status'] = 3;
}
return $res;
}
/**
* @param array $param
* @return mixed
* @throws Exception
*/
public function getCollectionsForMenuFilters($param = [])
{
$q = $this->createQueryBuilder('c')
->select('c, f')
->leftJoin('c.factory', 'f')
->andWhere('c.factory != \'\'')
->andWhere('f.status = :f_status')
->andWhere('c.status = :c_status')
->setParameter('f_status', BiConst::STATE_PUBLISHED)
->setParameter('c_status', BiConst::STATE_PUBLISHED)
->orderBy('c.name, c.publishDate DESC, c.id');
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
if (!empty($param['factoryId'])) {
$q->andWhere('f.id IN (' . join(', ', $param['factoryId']) . ')');
}
if (!empty($param['id'])) {
$q->andWhere('c.id = :collId');
$q->setParameter('collId', $param['id']);
}
$r = $q->getQuery();
// todo для кеша места не хвататет, надо выборку уменьшить.
//$r->useQueryCache(true)->useResultCache(true, 60 * 60 * 4, $this->buildCacheName('getCollectionsForFilters', $param));
$items = $r->getResult();
return $items;
}
/**
* @param int $page
* @param int $limit
* @param string $orderBy
* @return array
* @throws Exception
*/
public function getCollectionIdes(int $page = 1, int $limit = 20, string $orderBy = 'c.publishDate DESC, c.id'): array
{
$q = $this->createQueryBuilder('c')
->select('c.id')
->leftJoin('c.factory', 'f')
->leftJoin('f.filter', 'b')// это сущность из базы фильтров
->andWhere('c.status = :status')
->andWhere('c.showMain = :showMain')
->andWhere('c.accessible != :accessible OR c.accessible is null')
->andWhere('f.filter IS NOT null')
->andWhere('f.status = :status')
->andWhere('c.factory != :factory')
->setParameters([
'status' => BiConst::STATE_PUBLISHED,
'showMain' => true,
'accessible' => true,
'factory' => ''
])
->orderBy($orderBy)
->setMaxResults($limit)
->setFirstResult($limit * $page - $limit);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
$res = $q->getQuery()
->enableResultCache(600)
->getArrayResult();
return $res ? array_column($res, 'id') : [];
}
/**
* @param array $param
* @param bool $wTest
* @return array
* @throws Exception
*/
public function getCollections(array $param = [], bool $wTest = false): array
{
$redisCachePool = App::getContainer()->get(RedisCachePool::class)->getPool();
$memKey = md5(json_encode($param) . $wTest . '2' . App::getCurLocale() . LocaleHelper::getCur() . LocaleHelper::getUserMeasure());
$cacheItem = $redisCachePool->getItem('getCollections.' . $memKey);
$cacheItem->expiresAfter(600);
$cacheCreatedAtItem = $redisCachePool->getItem('createdCollectionAt.' . $memKey);
$cacheCreatedAtItem->expiresAfter(600);
$cacheUpdatedAtItem = $redisCachePool->getItem('updateCollections');
$cacheUpdatedAtItem->expiresAfter(600);
$createdAt = $cacheCreatedAtItem->get() ?? false;
$updatedAt = $cacheUpdatedAtItem->get() ?? false;
$expired = $createdAt && $updatedAt && ($updatedAt > $createdAt);
if (!$cacheItem->isHit() || $expired) {
$q = $this->createQueryBuilder('c')
->innerJoin('c.factory', 'f')
->innerJoin('f.filter', 'b')// это сущность из базы фильтров
->innerJoin('f.country', 'ct')
->andWhere('f.filter IS NOT null')
->andWhere('c.factory != \'\'')
->andWhere('f.status = :f_status')
->setParameter('f_status', BiConst::STATE_PUBLISHED);
if (HideFactoryCountriesHelper::length() > 0) {
$q->andWhere('f.id NOT IN (:hide_factories)')
->setParameter('hide_factories',HideFactoryCountriesHelper::codes());
}
if (!App::isRole('ROLE_TEST') && !$wTest) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
if (isset($param['collectionId'])) {
$cid = $param['collectionId'];
if (is_array($cid)) {
$cid = implode(' ,', $cid);
$q->andWhere('c.status = :c_status and c.id IN (:collectionId)');
$q->setParameter('collectionId', $cid);
} else {
$q->andWhere('c.status = :c_status and c.id = :collectionId');
$q->setParameter('collectionId', $param['collectionId']);
}
$q->setParameter('c_status', BiConst::STATE_PUBLISHED);
} else {
$q->andWhere('c.status = :c_status')
->setParameter('c_status', BiConst::STATE_PUBLISHED);
}
if (!empty($param['leftCollectionCount']) && $param['leftCollectionCount']) {
$q->andWhere('c.status = :c_status');
$q->andWhere('f.status = :f_status');
$q->setParameter('c_status', BiConst::STATE_PUBLISHED)
->setParameter('f_status', BiConst::STATE_PUBLISHED);
}
if (!empty($param['onlyId'])) {
$q->select('c.id');
} elseif (empty($param['onlyCF'])) {
$q->select('c,f,ct,i,id')
->leftJoin('c.interiors', 'i')
->leftJoin('i.ideas', 'id')
->groupBy('c.id');
} else {
$q->select('c.id,c.url,c.code,c.name,c.alternateName,c.nameFull,f.id fId,f.url fUrl,f.unid fUnid');
if (!empty($param['locale'])) {
$q->leftJoin('b.url', 'burl');
$q->leftJoin('b.page', 'bpage');
$q->addSELECT("b.id brandId, f.url brandUrl, f.name brandName");
}
}
if (!empty($param['factoryId'])) {
$q->andWhere('f.id IN (' . join(', ', $param['factoryId']) . ')');
}
if (!empty($param['order'])) {
$q->orderBy($param['order']);
} else {
$q->orderBy('c.publishDate DESC, c.id');
}
if (!empty($param['ides'])) {
$q->andWhere('c.id IN (' . join(', ', $param['ides']) . ')');
}
if (!empty($param['noIdes'])) {
$q->andWhere('c.id NOT IN (' . join(', ', $param['noIdes']) . ')');
}
if (!empty($param['limit'])) {
$q->setMaxResults($param['limit']);
}
if (!empty($param['start_with'])) {
$q->setFirstResult($param['start_with']);
}
if (!empty($param['archive'])) {
$q->andWhere('c.archive = ' . $param['archive']);
}
if (!empty($param['code'])) {
$code = ArrHelper::get($param, 'code');
$code = is_array($code) ? $code[0] : $code;
foreach ($code as $i => $item) {
$code[$i] = "'{$item}'";
}
$code = implode(', ', $code);
$q->andWhere("c.code in ({$code})");
}
if (empty($param['noReviewCount'])) {
// специальные подзапросы для отзывов по коллекциям
$q->addSELECT('(SELECT COUNT(prc.star) FROM WebBundle\Entity\ProductReviewsCache prc Where prc.sku = c.code) prc_count');
$q->addSELECT('(SELECT SUM(prc2.star) FROM WebBundle\Entity\ProductReviewsCache prc2 Where prc2.sku = c.code) prc_vote');
}
$r = $q->getQuery()->useQueryCache(true);
$items = $r->getArrayResult();
foreach ($items as $key => $item) {
if (!empty($item[0])) {
$items[$key] = array_merge($item[0], $item);
unset($items[$key][0]);
}
}
$cacheItem->set($items);
$cacheCreatedAtItem->set(time());
$redisCachePool->save($cacheItem);
}
$collections = $cacheItem->get();
if (isset($collections[0]['rating'])) {
$ids = [];
foreach ($collections as $collection) {
$ids[] = $collection['id'] ?? 0;
}
//Делаем один дополнительный sql запрос на получение пачки коллекций
$actualData = $this->findBy(['id' => $ids]);
foreach ($collections as &$collection) {
$collection['rating'] = $this->getRating($collection['id'], $actualData);
}
}
return $collections;
}
public function getListForMenu(array $param): array
{
$status = BiConst::STATE_PUBLISHED . ', ' . BiConst::STATE_WORK_CONTINUED;
$whereCid = '';
if (!empty($param['collectionId'])) {
$cid = $param['collectionId'];
if (is_array($cid)) {
$cid = implode(' ,', $cid);
}
$whereCid = "AND c.id IN ({$cid})";
}
$whereFid = '';
if (!empty($param['factoryId'])) {
$fid = implode(' ,', $param['factoryId']);
$whereCid = "AND b.id IN ({$fid})";
}
// доработал запрос чтобы не попадали коллекции у которых нет выборки для каталога
// https://te.remote.team/#/discus/E82653AE-437D-D61C-AE0D-F985799FE15E/
$sql = "SELECT
c.id AS `id`,
c.status AS `status`,
c.url AS `slug`,
c.name AS `name`,
c.name_full AS `nameFull`,
b.id AS `b.id`,
b.name AS `b.name`,
b.url AS `b.slug`
FROM
collection c
INNER JOIN factory b ON b.id = c.factory
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
WHERE c.factory IS NOT NULL
AND c.factory != ''
AND c.url IS NOT NULL
AND c.url != ''
AND b.url IS NOT NULL
AND b.url != ''
AND b.filter IS NOT null
AND b.status IN ({$status})
AND c.status IN ({$status})
{$whereCid} {$whereFid}
GROUP BY c.id
ORDER BY c.name, b.name
";
$rows = $this
->_em
->getConnection()
->fetchAllAssociative($sql);
foreach ($rows as $i => $row) {
$name = $row['nameFull'] ? $row['nameFull'] : $row['name'];
$item = [
'fId' => intval($row['b.id']),
'id' => intval($row['id']),
'status' => intval($row['status']),
'slug' => $row['slug'],
'name' => html_entity_decode($name),
'factory' => [
'id' => intval($row['b.id']),
'slug' => $row['b.slug'],
'name' => html_entity_decode($row['b.name']),
],
];
$rows[$i] = $item;
}
return $rows;
}
/**
* @param array $param
* @return int
* @throws Exception
*/
public function countCollections($param = [])
{
$q = $this->createQueryBuilder('c')
->select('COUNT(c.id)')
->leftJoin('c.factory', 'f')
->leftJoin('c.articles', 'a')
->andWhere('c.factory != \'\'')
->andWhere('f.id != 99')
->andWhere('f.status = :f_status')
->andWhere('c.status = :c_status')
->andWhere('c.archive != 1')
->andWhere('a.priceEuro IS NOT null')
->setParameter('c_status', BiConst::STATE_PUBLISHED)
->setParameter('f_status', BiConst::STATE_PUBLISHED)
->orderBy('c.name, c.publishDate')
->groupBy('c.id');
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
if (!empty($param['factoryId'])) {
$param['factoryId'] = is_array($param['factoryId']) ? $param['factoryId'] : [$param['factoryId']];
$q->andWhere('f.id IN (' . join(', ', $param['factoryId']) . ')');
}
$r = $q->getQuery()->useQueryCache(true);
$items = count($r->getArrayResult());
return $items;
}
/**
* @param $factoryUnid
* @return array|null
*/
public function getCollectionsByFactoryUnid($factoryUnid)
{
$r = $this->createQueryBuilder('c')
->select('c,f')
->leftJoin('c.factory', 'f')
->andWhere('f.unid = :unid')
->setParameters(['unid' => $factoryUnid])
->getQuery();
return $r->getResult();
}
/**
* получить коллекции для установки тем и участников из админки
* @param null $ids
* @param null $limit
* @return array|null
*/
public function getCollectionsParticipant($ids = null, $limit = null)
{
$q = $this
->createQueryBuilder('c')
->andWhere('c.status =:c_status')
->setParameter('c_status', BiConst::STATE_PUBLISHED);
if ($ids) {
$ids = preg_replace('#[\s]+#i', '', trim($ids));
$IDS = explode(',', $ids);
$q->andWhere('c.id in (:ids)')
->setParameter('ids', $IDS);
}
if ($limit) {
$q->setMaxResults($limit);
}
$r = $q->getQuery();
return $r->getResult();
}
/**
* @param int $p
* @param int $l
* @param null $id
* @return array|null
*/
public function getCollCheck($p, $l = 10000, $id = null)
{
$offset = $l * $p - $l;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('WebBundle\Entity\Factory', 'f');
$rsm->addFieldResult('f', 'f_id', 'id');
$rsm->addFieldResult('f', 'f_url', 'url');
$rsm->addJoinedEntityResult('WebBundle\Entity\User', 'u', 'f', 'user');
$rsm->addFieldResult('u', 'u_id', 'id');
$rsm->addFieldResult('u', 'username', 'username');
$rsm->addJoinedEntityResult('WebBundle\Entity\Article', 'a', 'c', 'articles');
$rsm->addFieldResult('a', 'id', 'id');
$rsm->addFieldResult('a', 'file', 'file');
$rsm->addJoinedEntityResult('WebBundle\Entity\Collection', 'c', 'f', 'collection');
$rsm->addFieldResult('c', 'c_id', 'id');
$rsm->addFieldResult('c', 'c_url', 'url');
$rsm->addJoinedEntityResult('WebBundle\Entity\Interior', 'i', 'c', 'interiors');
$rsm->addFieldResult('i', 'i_id', 'id');
$rsm->addFieldResult('i', 'i_name', 'name');
$rsm->addFieldResult('i', 'i_file', 'file');
$ID = $id != null ? ('c.id=' . $id . ' AND ') : '';
$query = $this->_em->createNativeQuery(
'SELECT
f.id AS f_id,
f.url AS f_url,
u.id AS u_id,
u.username,
c.id AS c_id,
c.url AS c_url,
a.id,
a.file,
i.id AS i_id,
i.name AS i_name,
i.file AS i_file
FROM factory f
LEFT JOIN user u ON f.user_id = u.id
LEFT JOIN collection c ON c.factory = f.id
LEFT JOIN article a ON a.collection = c.id
LEFT JOIN interior i ON i.collection = c.id
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 . ';',
$rsm
);
$result = $query->getArrayResult();
return $result;
}
/**
* @return int|mixed
* @throws NoResultException
* @throws NonUniqueResultException
*/
public function countAllCollection()
{
$q = $this->createQueryBuilder('q');
$q->select('count(q.id)')
->andWhere('q.status = :status')
->setParameter('status', BiConst::STATE_PUBLISHED);
$count = $q->getQuery()->getSingleScalarResult();
return $count;
}
/**
* Получаем рейтинги для коллекций отдельно, чтобы не чистить из-за них кеш
* @param array $id
* @return array|null
*/
public function getRatings(array $id)
{
if (count($id) == 0) {
return [];
}
if (is_array($id)) {
$id = implode(', ', $id);
$id = "($id)";
}
$q = $this->createQueryBuilder('c')
->select('c.id, c.rating')
->andWhere("c.id IN {$id}");
$r = $q->getQuery()->useQueryCache(true);
$items = $r->getArrayResult();
$res = [];
foreach ($items as $item) {
$res[$item['id']] = $item['rating'];
}
return $res;
}
/**
* todo remove from bi
* @return array|null
*/
public function _getOutputLastCollectionsInteriorImg()
{
$limit = 55;
$q = $this
->createQueryBuilder('c')
->andWhere('(SELECT count(i.id) FROM WebBundle\Entity\Interior i Where c.id=i.collection) > :count')
->setParameter('count', 5)
->orderBy('c.rating', 'desc')
->setMaxResults($limit)
->getQuery();
$items = $q->getResult();
$oui = [];
/** @var Collection $item */
foreach ($items as $k => $item) {
foreach ($item->getInteriors() as $key => $interior) {
if ($key < 3) {
$oui[] = [
'collection' => $item,
'interior' => $interior,
];
} else {
break;
}
}
}
return $oui;
}
/**
* Список БМов, которые задействованы в коллекциях
* @return array
* @throws Exception
*/
public function getListActiveBM()
{
$q = $this->createQueryBuilder('c')
->select('DISTINCT(user) AS uid, user.alias, user.username')
->leftJoin('c.factory', 'factory')
->leftJoin('factory.user', 'user')
->andWhere('c.factory is not null')
->andWhere('factory.status != 2')
->andWhere('factory.status != 3')
->andWhere('factory.status != 0')
->getQuery();
$list = [];
$oServiceUser = App::getContainer()->get('adm.service.users');
foreach ($q->getArrayResult() as $item) {
if (!empty($item['uid'])) {
$name = $item['alias'] ? $item['alias'] : $item['username'];
$list[$item['uid']] = $oServiceUser->buildEasyName($name);
}
}
return $list;
}
/**
* @return array
*/
public function getCollForVideo()
{
$q = $this->createQueryBuilder('c')
->select('c, b')
->leftJoin('c.body', 'b')
->andWhere('b.en LIKE \'%youtube%\'')
->getQuery();
return $q->getResult();
}
/**
* todo remove from bi
* получить набор коллекций для загрузки оброаботанных дизайнером изображений
* @param Collection|null $collection
* @return array|null
*/
public function _getCollectionsByCollection(Collection $collection = null)
{
$q = $this->createQueryBuilder('c')
->andWhere('c.status = :status1 or c.status = :status4')
->setParameter('status1', BiConst::STATE_PUBLISHED)
->setParameter('status4', BiConst::STATE_PROCESSING);
if ($collection) {
$id = $collection->getId();
$q
->andWhere('c.id = :id')
->setParameter('id', $id);
}
$r = $q->getQuery()
->useQueryCache(true)
->enableResultCache(3600 * 24 * 30);
return $r->getResult();
}
/**
* todo remove from bi
* @param User $user
* @return array|null
*/
public function _getCollectionsForBm(User $user)
{
$q = $this->createQueryBuilder('c')
->leftJoin('c.factory', 'f')
->leftJoin('f.user', 'u');
if ($user->hasRole('ROLE_BM')) {
$q
->andWhere('u.id = :user')
->setParameter('user', $user->getId());
}
$r = $q
->andWhere('f.status = :fstatus')
->andWhere('c.status = :cstatus1 or c.status = :cstatus4')
->setParameter('fstatus', BiConst::STATE_PUBLISHED)
->setParameter('cstatus1', BiConst::STATE_PUBLISHED)
->setParameter('cstatus4', BiConst::STATE_PROCESSING)
->orderBy('f.url, c.url')
->getQuery();
return $r->getResult();
}
/**
* Получение списка для проверки на наличие кириллических символов
* @return array
*/
public function getCollectionsAdmForCheckCyrillic()
{
$q = $this->createQueryBuilder('c')
->select('c, body')
->leftJoin('c.body', 'body')
->andWhere('c.status = :status')
->setParameter('status', BiConst::STATE_PUBLISHED);
return $q->getQuery()->getArrayResult();
}
/**
* Получение списка блогов с которыми связана коллекция
* @param $collectionId
* @param string $lc
* @return array
* @throws Exception
*/
public function getPublications($collectionId, $lc)
{
// получаем полную локаль, для формирования ссылки
$lcFull = $lc;
if ($lcFull != ($cc = App::getCurCountry())) {
$lcFull = "$lc-$cc";
}
$unid = 'unid';
$q = $this->createQueryBuilder('c')
->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")
->leftJoin('c.publications', 'p')
->leftJoin('p.url', 'url')
->leftJoin('p.title', 'title')
->leftJoin('p.body', 'body')
->leftJoin('p.preview', 'pr')
->andWhere('p.enable = true OR p.id IS NULL')
->andWhere('c.id = :id')
->setParameter('id', $collectionId);
$res = [
'publications' => [],
];
/** @var CommentRepository $repoComment */
$repoComment = App::getRepository(CommentEntity::class);
foreach ($q->getQuery()->getArrayResult() as $row) {
if (empty($res['id'])) {
$res['id'] = $row['cId'];
}
if (empty($res['code'])) {
$res['code'] = $row['cCode'];
}
if (empty($res['unid'])) {
$res['unid'] = $row['unid'];
}
if (!empty($row['pUrl']) && !empty($row['pTitle'])) {
$res['publications'][] = [
'link' => App::generateUrl('app_publication_single', ['id' => $row['pUrl'], '_locale' => $lcFull]),
'title' => $row['pTitle'],
'body' => $row['pBody'],
'publishDate' => $row['publishDate'],
'view' => $row['view'],
'preview' => PathHelper::pathGenerate(
'publication',
[
'id' => $row['pId'],
'preview' => $row['preview'],
]
),
'commentCnt' => !empty($row['pUnid'])
? $repoComment->getCountPublicationsByUnid($lc, $row['pUnid'])
: 0
];
}
}
return $res;
}
/**
* Установка парамтеров к запросу для выборки коллекции на главной
* @param $factory
* @param $collection
* @return mixed|null
*/
public function getMainBaseCollectionLight($factory, $collection)
{
$query = $this->createQueryBuilder('c')
->select('c, f, country, body, metaKeywords, metaDescription')
->leftJoin('c.factory', 'f')
->leftJoin('f.country', 'country')
->leftJoin('c.body', 'body')
->leftJoin('c.metaKeywords', 'metaKeywords')
->leftJoin('c.metaDescription', 'metaDescription')
->andWhere('f.status > :f_status')
->andWhere('f.url = :factory')
->andWhere('c.url = :collection')
->setParameters([
'f_status' => BiConst::STATE_NOT_PUBLISHED,
'factory' => $factory,
'collection' => $collection,
])
->getQuery()
->setQueryCacheLifetime(TimeConstant::HOUR)
->useQueryCache(true);
$item = $query->getArrayResult();
$res = current($item);
// закрываем некоторые фабрики для некоторых стран
if ($res && in_array($res['factory']['id'], HideFactoryCountriesHelper::codes())) {
$res['factory']['status'] = 3;
$res['status'] = 3;
}
return $res;
}
/**
* формирование запроса для выборки данных коллекции и связанных интерьеров для главной и для слайдера
* @return QueryBuilder
*/
public function createQuerySliderBaseCollection()
{
$q = $this->createQueryBuilder('c');
$q
->select('c, f, i, idea, applies, styles, textures, country, body, metaKeywords, metaDescription')
->leftJoin('c.factory', 'f')
->leftJoin('f.country', 'country')
->leftJoin('c.body', 'body')
->leftJoin('c.metaKeywords', 'metaKeywords')
->leftJoin('c.metaDescription', 'metaDescription');
$where = 'f.status > :f_status';
$q
->andWhere($where)
->orderBy('i.isMain', 'DESC')
->setParameter('f_status', BiConst::STATE_NOT_PUBLISHED);
return $q;
}
/**
* @param $code
* @return mixed
* @throws NoResultException
* @throws NonUniqueResultException
*/
public function getCollectionByCode($code)
{
$q = $this->createQueryBuilder('c')
->select('c,f,u')
->leftJoin('c.factory', 'f')
->leftJoin('f.user', 'u')
->andWhere('c.code = :code')
->setParameter('code', $code);
return $q->getQuery()->getSingleResult();
}
/**
* @param $codes
* @return mixed
*/
public function getCollectionByCodes($codes)
{
$q = $this->createQueryBuilder('c')
->andWhere('c.code in (:code)')
->setParameter('code', $codes);
return $q->getQuery()->getResult();
}
/**
* @param null $fid
* @param array $onlyIds
* @return array
*/
public function admGetForJsTree($fid = null, array $onlyIds = [])
{
$q = $this->createQueryBuilder('c');
$q->select('c.id, c.name, f.name as fname')
->leftJoin('c.factory', 'f')
->andWhere('c.status = :statusPub')
->orWhere('c.status = :statusCheck')
->addOrderBy('c.name', 'ASC')
->setParameter('statusPub', BiConst::STATE_PUBLISHED)
->setParameter('statusCheck', BiConst::STATE_CHECKING);
if ($onlyIds) {
$onlyIds = implode(',', $onlyIds);
$q->andWhere("c.id IN ({$onlyIds})");
}
if ($fid) {
$q->andWhere('f.id = :fid')
->setParameter('fid', $fid);
}
$items = $q->getQuery()->getArrayResult();
$res = [];
foreach ($items as $i => $item) {
$res[$item['id']] = $item;
}
// сортироуем по имени
$resSort = array_column($res, 'name');
array_multisort($resSort, SORT_ASC, $res);
return $res;
}
/**
* @param $cid
* @return Collection|null
*/
public function getByIdForParseAttr($cid)
{
$q = $this->createQueryBuilder('c')
->select('c,f')
->leftJoin('c.factory', 'f')
->andWhere('c.id = :id')
->setParameter('id', $cid);
try {
$item = $q->getQuery()->getOneOrNullResult();
} catch (NonUniqueResultException $e) {
$item = null;
}
return $item;
}
/**
* Получаем список ID коллекция для парсига их свойств
* @param bool $onlyNull
* @return array
*/
public function getIdsForParseAttr($onlyNull = false)
{
$q = $this->createQueryBuilder('c')->select('c.id');
if ($onlyNull) {
$q->andWhere('c.fids IS NULL');
}
$ids = $q->getQuery()->getArrayResult();
if ($ids) {
$ids = array_column($ids, 'id');
}
return $ids;
}
/**
* @param int $id
* @return mixed
* @throws NoResultException
* @throws NonUniqueResultException
* @todo remove from bi
*/
public function _getCollectionsForFeed($id)
{
$q = $this->createQueryBuilder('c')
->select('c,f')
->leftJoin('c.factory', 'f')
->leftJoin('c.articles', 'articles')
->leftJoin('c.interiors', 'interiors')
->andWhere('c.id = :id')
->setParameter('id', $id);
$r = $q->getQuery();
$item = $r->getSingleResult();
return $item;
}
/**
* @param array $params
* @return array
* @todo remove from bi
*/
public function _getItemsForFeed($params = [])
{
$id = isset($params['code']) ? $params['code'] : null;
$brand = isset($params['brand']) ? $params['brand'] : null;
$limit = isset($params['limit']) ? $params['limit'] : null;
$q = $this->createQueryBuilder('c')
->select('c.id,c.code,c.name, f.name fname, fl.leftMenu, fc.alias')
->leftJoin('c.factory', 'f')
->leftJoin('f.filter', 'fl')
->leftJoin('f.country', 'fc')
->andWhere('c.status = :status1')
->setParameter('status1', BiConst::STATE_PUBLISHED)
->andWhere('f.status = :status')
->setParameter('status', BiConst::STATE_PUBLISHED);
if ($id) {
if ($id == 'test') {
$limit = $limit ? $limit : 50;
$q
->setMaxResults($limit);
} else {
$q
->andWhere('c.id = :id')
->setParameter('id', $id);
}
}
if ($brand) {
$q
->andWhere('f.id = :brand')
->setParameter('brand', $brand);
}
$q->addOrderBy('f.name', 'ASC');
$q->addOrderBy('c.name', 'ASC');
$r = $q->getQuery();
return $r->getArrayResult();
}
/**
* Получение имени для графика статистик в админке
* @param array $fids
* @return array
*/
public function getNamesForStatChartAdmin(array $fids)
{
$fidsStr = implode(',', $fids);
$sql = "SELECT
c.id,
c.name AS `name`,
f.name AS `fname`
FROM
collection c
LEFT JOIN factory f ON c.factory = f.id
WHERE c.id IN ({$fidsStr})
ORDER BY c.name ";
$items = $this->_em->getConnection()->fetchAll($sql);
$r = [];
foreach ($items as $item) {
$id = $item['id'];
$r[$id] = [
'name' => "{$item['name']} ({$item['fname']})",
'data' => [],
];
}
return $r;
}
/**
* @param $params
* @return float|int|mixed|string
* @todo remove from bi
*/
public function _getItemsForCalculationImages($params = [])
{
$id = isset($params['code']) ? $params['code'] : null;
$q = $this->createQueryBuilder('c')
->andWhere('c.status = :status1')
->setParameter('status1', BiConst::STATE_PUBLISHED);
if ($id) {
if ($id == 'test') {
$limit = 5;
$q
->setMaxResults($limit);
} else {
$q
->andWhere('c.id = :id')
->setParameter('id', $id);
}
}
$r = $q->getQuery();
return $r->getResult();
}
/**
* @param $param
* @return mixed
* @todo remove from bi
*/
public function _getCollectionsForJpegtran($param)
{
$q = $this->createQueryBuilder('c');
if ($param['ides'] != 'all') {
$q->andWhere('c.id IN (' . join(', ', $param['ides']) . ')');
} else {
if ($param['brand']) {
$q
->leftJoin('c.factory', 'f')
->andWhere('f.id IN (' . join(', ', $param['brand']) . ')');
}
}
if (!empty($param['states'])) {
$q->andWhere('c.status IN (' . join(', ', $param['states']) . ')');
}
$r = $q->getQuery();
return $r->getResult();
}
/**
* @param null $code
* @return array
* @todo remove from bi
*/
public function _getItemsForRenameAdblock($code = null)
{
$q = $this->createQueryBuilder('c')
->select('c.id, c.name, f.name fname')
->leftJoin('c.factory', 'f')
->andWhere('c.status = :status1')
->setParameter('status1', BiConst::STATE_PUBLISHED)
->andWhere('f.suspended <> :suspended')
->setParameter('suspended', BiConst::STATE_PUBLISHED);
if ($code) {
if ($code == 'test') {
$limit = 50;
$q
->setMaxResults($limit);
} else {
$q
->andWhere('c.id = :id')
->setParameter('id', $code);
}
}
$r = $q->getQuery();
return $r->getArrayResult();
}
/**
* Ищем коллекцию для проставления связи с коллекцией выставки
* @param string $cName
* @param int $bid
* @return array|null
*/
public function getCollByNameForExh(string $cName, int $bid)
{
$conn = $this->_em->getConnection();
$cName = $conn->quote($cName);
$sql = "SELECT
`c`.id AS `id`,
`c`.name AS `name`,
`c`.name_full AS `nameFull`,
`c`.alternate_name AS `nameAlt`,
`brand`.id AS `brandId`,
`brand`.name AS `brandName`
FROM
collection c
LEFT JOIN factory `brand` ON `brand`.id = `c`.factory
WHERE (`c`.`name` LIKE {$cName} OR `c`.`name_full` LIKE {$cName} OR `c`.`alternate_name` LIKE {$cName}) AND `c`.factory = {$bid}
";
$items = $conn->fetchAll($sql);
return $items ? $items[0] : null;
}
public function getCollectionsForSliderNative($id)
{
$rsm = new ResultSetMapping;
$rsm->addEntityResult('WebBundle\Entity\Collection', 'c');
$rsm->addFieldResult('c', 'id', 'id');
$rsm->addFieldResult('c', 'name', 'name');
$rsm->addFieldResult('c', 'alternate_name', 'alternateName');
$rsm->addFieldResult('c', 'url', 'url');
$rsm->addFieldResult('c', 'header', 'header');
$rsm->addFieldResult('c', 'settings', 'settings');
$rsm->addFieldResult('c', 'rating', 'rating');
$rsm->addFieldResult('c', 'status', 'status');
$rsm->addJoinedEntityResult('WebBundle\Entity\Factory', 'f', 'c', 'factory');
$rsm->addFieldResult('f', 'f_id', 'id');
$rsm->addFieldResult('f', 'f_name', 'name');
$rsm->addFieldResult('f', 'f_url', 'url');
$rsm->addFieldResult('f', 'f_stated_at', 'statedAt');
$rsm->addFieldResult('f', 'f_status', 'status');
$rsm->addJoinedEntityResult('WebBundle\Entity\FilterEntity', 'fl', 'f', 'filter');
$rsm->addFieldResult('fl', 'fl_id', 'id');
$rsm->addJoinedEntityResult('WebBundle\Entity\FilterParamEntity', 'flp', 'fl', 'param');
$rsm->addFieldResult('flp', 'flp_id', 'id');
$rsm->addFieldResult('flp', 'flp_code', 'code');
$rsm->addJoinedEntityResult('WebBundle\Entity\FilterEntity', 'flc', 'fl', 'country');
$rsm->addFieldResult('flc', 'flc_id', 'id');
$rsm->addFieldResult('flc', 'flc_left_menu', 'leftMenu');
$query = $this->_em->createNativeQuery(
"SELECT
c.id,
c.name,
c.alternate_name,
c.url,
c.header,
c.settings,
c.rating,
c.status,
f.id AS f_id,
f.name AS f_name,
f.url AS f_url,
f.stated_at AS f_stated_at,
f.status AS f_status,
fl.id AS fl_id,
fl.country_id AS fl_country_id,
flc.id AS flc_id,
flc.left_menu AS flc_left_menu,
flp.id AS flp_id,
flp.code AS flp_code
FROM
collection c
LEFT JOIN factory f ON f.id = c.factory
LEFT JOIN filters fl ON fl.id = f.filter
LEFT JOIN filters flc ON flc.id = fl.country_id
LEFT JOIN filter_params flp ON flp.id = flc.param_id
WHERE c.id ={$id} ",
$rsm
);
$result = $query->getArrayResult();
return array_shift($result);
}
/**
* @param int $cid
* @return false|string
* @throws DBALException
*/
public function getNameForFilterHistorySearch(int $cid)
{
$sql = "SELECT
c.name AS `name`
FROM
collection c
WHERE
c.id = '{$cid}'";
$items = $this->_em
->getConnection()
->executeQuery($sql)
->fetchColumn(0);
return $items;
}
/**
* Получение ID для сбора рекомендаций в админку для теста
* @param string $fUrl
* @param string $cUrl
* @return int|null
*/
public function getCollIdForNeyronAdmin(string $fUrl, string $cUrl)
{
$conn = $this->_em->getConnection();
$fUrl = $str = mb_strtolower($fUrl, 'UTF-8');
$cUrl = $str = mb_strtolower($cUrl, 'UTF-8');
$sql = "SELECT
c.id
FROM
collection c
LEFT JOIN factory f ON f.id = c.factory
WHERE c.url = '{$cUrl}' AND f.url = '{$fUrl}'
";
$id = $conn->fetchAll($sql);
if ($id) {
$id = $id[0]['id'];
} else {
$id = null;
}
return $id;
}
/**
* Получение списка ID фильтров для сбора рекомендаций в админку для теста
* @param array $cids
* @return array
*/
public function getCollFidsdForNeyronAdmin(array $cids)
{
$conn = $this->_em->getConnection();
$cids = implode(', ', $cids);
$sql = "SELECT
c.id,
c.fids
FROM
collection c
WHERE c.id IN ({$cids})
";
$rows = $conn->fetchAll($sql);
$items = [];
foreach ($rows as $row) {
$items[$row['id']] = json_decode($row['fids']);
}
return $items;
}
/**
* @param $params
* @return float|int|mixed[]|string
* @todo remove from bi
*/
public function _getItemsForInteriorCyrilic($params = [])
{
$id = isset($params['code']) ? $params['code'] : null;
$brand = isset($params['brand']) ? $params['brand'] : null;
$limit = isset($params['limit']) ? $params['limit'] : null;
$q = $this->createQueryBuilder('c')
->select('c.id, c.name, c.url curl, f.name fname, f.url furl')
->leftJoin('c.factory', 'f')
->andWhere('c.status = :status1')
->setParameter('status1', BiConst::STATE_PUBLISHED)
->andWhere('f.suspended <> :suspended')
->setParameter('suspended', BiConst::STATE_PUBLISHED);
if ($id) {
if ($id == 'test') {
$limit = $limit ? $limit : 50;
$q
->setMaxResults($limit);
} else {
$q
->andWhere('c.id = :id')
->setParameter('id', $id);
}
}
if ($brand) {
$q
->andWhere('f.id = :brand')
->setParameter('brand', $brand);
}
$r = $q->getQuery();
return $r->getArrayResult();
}
/**
* @param $params
* @return array
* @throws Exception
* @todo remove from bi
*/
public function _getCollectionsIDSForCheckList($params)
{
$page = isset($params['page']) ? $params['page'] : 1;
$limit = isset($params['limit']) ? $params['limit'] : BiConst::SEARCH_RESULT_ON_PAGE;
$offset = $limit * ($page - 1);
$states = !empty($params['states']) ? $params['states'] : null;
$checkId = isset($params['check_id']) ? $params['check_id'] : 'all';
$isCheckAll = $checkId == 'all';
$suspended = !empty($params['suspended']) ? $params['suspended'] : null;
$manager = isset($params['manager']) ? $params['manager'] : 'all';
$brand = isset($params['brand']) ? $params['brand'] : 'all';
$sqlWhereUser = '';
if ($manager == 'all') {
$sqlWhereManager = '';
} else {
$sqlWhereManager = "AND u.id = '{$manager}'";
}
if ($brand == 'all') {
$sqlWhereBrand = '';
} else {
$sqlWhereBrand = "AND f.unid = '{$brand}'";
}
if ($isCheckAll) {
$user = App::getCurUser();
$sqlWhereCheckId = '';
if ($user->hasRole('ROLE_BM')) {
$sqlWhereManager = "AND u.id = '{$user->getId()}'";
if ($suspended) {
$sqlWhereCheckId = "AND chl.code IN ('has_suspended_article', 'has_suspended_collection')";
}
}
} else {
$sqlWhereCheckId = "AND chl.code = '{$checkId}'";
}
$sql = "
SELECT
c.id
FROM
collection c
LEFT JOIN `factory` f ON f.id = c.factory
LEFT JOIN `user` u ON u.id = f.user_id
LEFT JOIN `check_list` chl ON chl.collection = c.id AND chl.showed = 1 {$sqlWhereCheckId}
WHERE c.status = {$states}
AND c.factory > '0'
{$sqlWhereManager}
{$sqlWhereUser}
{$sqlWhereBrand}
GROUP BY c.id
HAVING COUNT(DISTINCT chl.id) > 0
ORDER BY u.alias, f.url, c.url";
$idsAll = ConnectionHelper::getInstance()->executeFetchAllSql($sql, PDO::FETCH_COLUMN);
$all = count($idsAll);
$sql = $sql . " LIMIT {$limit} OFFSET {$offset};";
$ids = ConnectionHelper::getInstance()->executeFetchAllSql($sql, PDO::FETCH_COLUMN);
return [
'ids' => $ids,
'allItems' => $all,
];
}
/**
* @param $code
* @return float|int|mixed|string
* @todo remove from bi
*/
public function _getCollectionByDesigner($code = null)
{
$q = $this->createQueryBuilder('c')
->leftJoin('c.factory', 'f')
->orWhere('c.status = :status1')
->orWhere('c.status = :status4')
->setParameter('status1', BiConst::STATE_PUBLISHED)
->setParameter('status4', BiConst::STATE_PROCESSING);
if ($code) {
$q
->andWhere('c.id = :id')
->setParameter('id', $code);
}
$q
->addOrderBy('f.name', 'ASC')
->addOrderBy('c.name', 'ASC');
$r = $q->getQuery();
return $r->getResult();
}
/**
* @param array $params
* @return array|int|string
* @todo remove from bi
*/
public function _getItemsMainInteriorCreate($params = [])
{
$id = isset($params['code']) ? $params['code'] : null;
$brand = isset($params['brand']) ? $params['brand'] : null;
$limit = isset($params['limit']) ? $params['limit'] : null;
$q = $this->createQueryBuilder('c')
->select('c.id, c.name, c.url curl, f.name fname, f.url furl')
->leftJoin('c.factory', 'f')
->andWhere('c.status = :status1')
->setParameter('status1', BiConst::STATE_PUBLISHED)
->andWhere('f.suspended <> :suspended')
->setParameter('suspended', BiConst::STATE_PUBLISHED);
if ($id) {
if ($id == 'test') {
$limit = $limit ? $limit : 50;
$q
->setMaxResults($limit);
} else {
$q
->andWhere('c.id = :id')
->setParameter('id', $id);
}
}
if ($brand) {
if (is_numeric($brand)) {
$q->andWhere('f.id =:brand');
} else {
$q->andWhere('f.name =:brand');
}
$q->setParameter('brand', $brand);
}
$r = $q->getQuery();
$out = $r->getArrayResult();
return $out;
}
/**
* @param $param
* @return float|int|mixed|string
* @todo remove from bi
*/
public function _getCollectionsForRecrop($param)
{
$q = $this->createQueryBuilder('c');
if ($param['ides'] != 'all') {
$q->andWhere('c.id IN (' . join(', ', $param['ides']) . ')');
} else {
if ($param['brand']) {
$q
->leftJoin('c.factory', 'f')
->andWhere('f.id IN (' . join(', ', $param['brand']) . ')');
}
}
if (!empty($param['states'])) {
$q->andWhere('c.status IN (' . join(', ', $param['states']) . ')');
}
$r = $q->getQuery();
return $r->getResult();
}
/**
* Получение коллекций для выгрузки в Google Recommendations AI
*
* @param integer $limit
* @param integer $offset
* @return array
*/
public function getCollectionsForGoogleRecommendationAi($limit = 10, $offset = 0)
{
$builder = $this->createQueryBuilder('c');
$builder->select('c.id', 'c.name')
->where('c.status IN (1,2,3,4,7)')
->where('c.archive = 0')
->andWhere('c.url IS NOT NULL AND c.url <> \'\'')
->setMaxResults($limit)
->setFirstResult($offset);
$query = $builder->getQuery();
$rows = $query->getResult();
return $rows;
}
/**
* @return array|bool
* @throws Exception
* @todo remove from bi
*/
public function _getModalTempateDescriptionInsert()
{
$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;";
$items = ConnectionHelper::getInstance()->executeFetchAllSql($sql);
return $items;
}
/**
* @return float|int|mixed|string
* @todo remove from bi
*/
public function _getCollectionForAddEventDescription()
{
$q = $this->createQueryBuilder('c')
->select('c,b')
->leftJoin('c.body', 'b')
->orWhere('b.ru like :simple')
->orWhere('b.ru like :multi')
->setParameter('simple', '%В интерьерах также использована плитка из коллекци%')
->setParameter('multi', '%В одном из интерьеров также использована плитка из коллекци%');
$r = $q->getQuery();
$items = $r->getResult();
return $items;
}
/**
* @param $furl
* @param $curl
* @return float|int|mixed|string|null
* @throws NonUniqueResultException
* @todo remove from bi
*/
public function _getCollectionsByDescriptionCorrect($furl, $curl)
{
$r = $this->createQueryBuilder('c')
->select('c,f')
->leftJoin('c.factory', 'f')
->andWhere('f.url = :furl')
->andWhere('c.url = :curl')
->setParameter('furl', $furl)
->setParameter('curl', $curl)
->getQuery();
return $r->getOneOrNullResult();
}
/**
* @param $params
* @return float|int|mixed|string
* @todo remove from bi
*/
public function _getItemsForConvertDesigner($params = [])
{
$id = isset($params['code']) ? $params['code'] : null;
$brand = isset($params['brand']) ? $params['brand'] : null;
$q = $this->createQueryBuilder('c')
->leftJoin('c.factory', 'f')
->andWhere('LENGTH(c.author)>0');
if ($id) {
$q
->andWhere('c.id = :id')
->setParameter('id', $id);
} elseif ($brand) {
$q
->andWhere('f.id = :brand')
->setParameter('brand', $brand);
}
$q->addOrderBy('f.name', 'ASC');
$q->addOrderBy('c.name', 'ASC');
$r = $q->getQuery();
return $r->getResult();
}
public function getListForUpdate($full = false)
{
$q = $this
->createQueryBuilder('c')
->select('c.id, c.code, f.unid, c.status, c.url')
->leftJoin('c.factory', 'f')
->andWhere('c.status IN (:status_1, :status_4, :status_7)')
->setParameter('status_1', BiConst::STATE_PUBLISHED)
->setParameter('status_4', BiConst::STATE_PROCESSING)
->setParameter('status_7', BiConst::STATE_CHECKING);
if (!App::isRole('ROLE_TEST')) {
$q->andWhere('c.testAccess IS NULL OR c.testAccess = 0');
$q->andWhere('f.testAccess IS NULL OR f.testAccess = 0');
}
$items = $q
->getQuery()
->useQueryCache($full)
->getArrayResult();
return $items;
}
/**
* @param array $ids
* @return array
*/
public function getCollAuthorIds(array $ids)
{
$ids = implode("','", $ids);
$q = $this
->createQueryBuilder('c')
->select('c.authorId')
->andWhere("c.id IN ('{$ids}')")
->andWhere('c.status IN (:status_1, :status_4, :status_7)')
->setParameter('status_1', BiConst::STATE_PUBLISHED)
->setParameter('status_4', BiConst::STATE_PROCESSING)
->setParameter('status_7', BiConst::STATE_CHECKING);
$items = $q->getQuery()->getArrayResult();
$ids = [];
if ($items) {
foreach ($items as $item) {
if (is_array($item['authorId'])) {
$ids[] = $item['authorId'][0];
} else {
$ids[] = $item['authorId'];
}
}
}
return $ids;
}
public function increaseViewByCollectionId(int $collId): void
{
try {
$this
->getEntityManager()
->getConnection()
->prepare('UPDATE `collection` SET `views` = `views` + \'1\' WHERE `id` = :id')
->executeQuery(['id' => $collId]);
} catch (DriverException|DoctrineDBALException|LockWaitTimeoutException $e) {
return;
}
}
private function getRating($id, $actualData): int
{
/** @var Collection $collection */
foreach ($actualData as $collection) {
if ($collection->getId() === $id) {
return $collection->getRating();
}
}
return 0;
}
public function save(Collection $idea, bool $flush = false): void
{
$this->getEntityManager()->persist($idea);
if ($flush) {
$this->flush();
}
}
public function flush(): void
{
$this->getEntityManager()->flush();
}
}