src/Repository/ProfileRepository.php line 1125

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by simpson <simpsonwork@gmail.com>
  4.  * Date: 2019-03-19
  5.  * Time: 22:23
  6.  */
  7. namespace App\Repository;
  8. use App\Entity\Account\Advertiser;
  9. use App\Entity\Location\City;
  10. use App\Entity\Location\MapCoordinate;
  11. use App\Entity\Profile\Genders;
  12. use App\Entity\Profile\Photo;
  13. use App\Entity\Profile\Profile;
  14. use App\Entity\Sales\Profile\AdBoardPlacement;
  15. use App\Entity\Sales\Profile\AdBoardPlacementType;
  16. use App\Entity\Sales\Profile\PlacementHiding;
  17. use App\Entity\Sales\Profile\TopPlacement;
  18. use App\Entity\Saloon\Saloon;
  19. use App\Entity\User;
  20. use App\Repository\ReadModel\CityReadModel;
  21. use App\Repository\ReadModel\ProfileApartmentPricingReadModel;
  22. use App\Repository\ReadModel\ProfileListingReadModel;
  23. use App\Repository\ReadModel\ProfileMapReadModel;
  24. use App\Repository\ReadModel\ProfilePersonParametersReadModel;
  25. use App\Repository\ReadModel\ProfilePlacementHidingDetailReadModel;
  26. use App\Repository\ReadModel\ProfilePlacementPriceDetailReadModel;
  27. use App\Repository\ReadModel\ProfileTakeOutPricingReadModel;
  28. use App\Repository\ReadModel\ProvidedServiceReadModel;
  29. use App\Repository\ReadModel\StationLineReadModel;
  30. use App\Repository\ReadModel\StationReadModel;
  31. use App\Service\Features;
  32. use App\Service\Map\MapClusterMinPriceDql;
  33. use App\Specification\Profile\ProfileIdINOrderedByINValues;
  34. use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  35. use Doctrine\DBAL\Connection;
  36. use Doctrine\ORM\AbstractQuery;
  37. use Doctrine\Persistence\ManagerRegistry;
  38. use Doctrine\DBAL\Statement;
  39. use Doctrine\ORM\QueryBuilder;
  40. use Happyr\DoctrineSpecification\Filter\Filter;
  41. use Happyr\DoctrineSpecification\Query\QueryModifier;
  42. use Porpaginas\Doctrine\ORM\ORMQueryResult;
  43. class ProfileRepository extends ServiceEntityRepository
  44. {
  45.     use SpecificationTrait;
  46.     use EntityIteratorTrait;
  47.     private Features $features;
  48.     private DistrictRepository $districts;
  49.     public function __construct(ManagerRegistry $registry, Features $features, DistrictRepository $districts)
  50.     {
  51.         parent::__construct($registry, Profile::class);
  52.         $this->features = $features;
  53.         $this->districts = $districts;
  54.     }
  55.     /**
  56.      * Возвращает итератор по данным, необходимым для генерации файлов sitemap, в виде массивов с
  57.      * следующими ключами:
  58.      *  - id
  59.      *  - uri
  60.      *  - updatedAt
  61.      *  - city_uri
  62.      *
  63.      * @return iterable<array{id: int, uri: string, updatedAt: \DateTimeImmutable, city_uri: string}>
  64.      */
  65.     public function sitemapItemsIterator(): iterable
  66.     {
  67.         $qb = $this->createQueryBuilder('profile')
  68.             ->select('profile.id, profile.uriIdentity AS uri, profile.updatedAt, city.uriIdentity AS city_uri')
  69.             ->join('profile.city', 'city')
  70.             ->andWhere('profile.deletedAt IS NULL');
  71.         $this->addModerationFilterToQb($qb, 'profile');
  72.         return $qb->getQuery()->toIterable([], AbstractQuery::HYDRATE_ARRAY);
  73.     }
  74.     protected function addModerationFilterToQb(QueryBuilder $qb, string $dqlAlias): void
  75.     {
  76.         if ($this->features->hard_moderation()) {
  77.             $qb->leftJoin(sprintf('%s.owner', $dqlAlias), 'owner');
  78.             $qb->andWhere(
  79.                 $qb->expr()->orX(
  80.                     sprintf('%s.moderationStatus = :status_passed', $dqlAlias),
  81.                     $qb->expr()->andX(
  82.                         sprintf('%s.moderationStatus = :status_waiting', $dqlAlias),
  83.                         'owner.trusted = true'
  84.                     )
  85.                 )
  86.             );
  87.             $qb->setParameter('status_passed', Profile::MODERATION_STATUS_APPROVED);
  88.             $qb->setParameter('status_waiting', Profile::MODERATION_STATUS_WAITING);
  89.         } else {
  90.             $qb->andWhere(sprintf('%s.moderationStatus IN (:statuses)', $dqlAlias));
  91.             $qb->setParameter('statuses', [Profile::MODERATION_STATUS_NOT_PASSED, Profile::MODERATION_STATUS_WAITING, Profile::MODERATION_STATUS_APPROVED]);
  92.         }
  93.     }
  94.     /**
  95.      * Число анкет для sitemap-фида. Условие совпадает с {@see findVisibleForSitemapShard()}
  96.      * и с {@see \App\Service\Sitemap\SitemapProfileVisibility}.
  97.      */
  98.     public function countVisibleForSitemap(): int
  99.     {
  100.         return (int) $this->createVisibleForSitemapQueryBuilder()
  101.             ->select('COUNT(profile.id)')
  102.             ->getQuery()
  103.             ->getSingleScalarResult();
  104.     }
  105.     /**
  106.      * Шард анкет для sitemap-фида. Порядок детерминирован: ORDER BY profile.id ASC.
  107.      *
  108.      * Анкета входит в фид, если одновременно:
  109.      * - deleteMode = 0 (любой deleteMode > 0 исключает, даже при deletedAt IS NULL);
  110.      * - deletedAt IS NULL (soft-delete исключает независимо от даты; grace-period не учитывается);
  111.      * - модерация как в {@see addModerationFilterToQb()} — эквивалент
  112.      *   ModerationService::isProfileEligibleToShowByModeration().
  113.      *   MODERATION_STATUS_REJECTED не входит, хотя ProfilePreviewController его показывает;
  114.      * - нет PlacementHiding (скрытые не входят, независимо от features->free_profiles());
  115.      * - активна: есть AdBoardPlacement или TopPlacement с placedAt <= now <= expiresAt
  116.      *   (как Profile::isActive()).
  117.      *
  118.      * @return list<array{id: int, uriIdentity: string, masseur: bool, updatedAt: \DateTimeInterface|null, city: string}>
  119.      */
  120.     public function findVisibleForSitemapShard(int $offset, int $limit): array
  121.     {
  122.         return $this->createVisibleForSitemapQueryBuilder()
  123.             ->select('profile.id AS id')
  124.             ->addSelect('profile.uriIdentity AS uriIdentity')
  125.             ->addSelect('profile.masseur AS masseur')
  126.             ->addSelect('profile.updatedAt AS updatedAt')
  127.             ->addSelect('c.uriIdentity AS city')
  128.             ->orderBy('profile.id', 'ASC')
  129.             ->setFirstResult($offset)
  130.             ->setMaxResults($limit)
  131.             ->getQuery()
  132.             ->getArrayResult();
  133.     }
  134.     /**
  135.      * Общий WHERE sitemap-фида анкет. Не отключает not_deleted_profile_filter:
  136.      * явное deletedAt IS NULL совпадает с этим фильтром.
  137.      */
  138.     private function createVisibleForSitemapQueryBuilder(): QueryBuilder
  139.     {
  140.         $qb = $this->createQueryBuilder('profile')
  141.             ->join('profile.city', 'c')
  142.             ->andWhere('profile.deleteMode = 0')
  143.             ->andWhere('profile.deletedAt IS NULL');
  144.         $this->addModerationFilterToQb($qb, 'profile');
  145.         $em = $qb->getEntityManager();
  146.         $hidden = new QueryBuilder($em);
  147.         $hidden->select('sitemap_profile_hiding');
  148.         $hidden->from(PlacementHiding::class, 'sitemap_profile_hiding');
  149.         $hidden->andWhere('sitemap_profile_hiding.profile = profile');
  150.         $adBoard = new QueryBuilder($em);
  151.         $adBoard->select('sitemap_profile_adboard');
  152.         $adBoard->from(AdBoardPlacement::class, 'sitemap_profile_adboard');
  153.         $adBoard->andWhere('sitemap_profile_adboard.profile = profile');
  154.         $top = new QueryBuilder($em);
  155.         $top->select('sitemap_profile_top');
  156.         $top->from(TopPlacement::class, 'sitemap_profile_top');
  157.         $top->andWhere('sitemap_profile_top.profile = profile');
  158.         $top->andWhere('sitemap_profile_top.placedAt <= :sitemap_now');
  159.         $top->andWhere('sitemap_profile_top.expiresAt >= :sitemap_now');
  160.         $qb->andWhere($qb->expr()->not($qb->expr()->exists($hidden->getDQL())));
  161.         $qb->andWhere($qb->expr()->orX(
  162.             $qb->expr()->exists($adBoard->getDQL()),
  163.             $qb->expr()->exists($top->getDQL()),
  164.         ));
  165.         $qb->setParameter('sitemap_now', new \DateTimeImmutable());
  166.         return $qb;
  167.     }
  168.     public function ofUriIdentityWithinCity(string $uriIdentity, City $city): ?Profile
  169.     {
  170.         return $this->findOneBy([
  171.             'uriIdentity' => $uriIdentity,
  172.             'city' => $city,
  173.         ]);
  174.     }
  175.     /**
  176.      * Метод проверки уникальности анкет по URI не должен использовать никаких фильтров, кроме URI и города,
  177.      * поэтому QueryBuilder не используется
  178.      * @see https://redminez.net/issues/27310
  179.      */
  180.     public function isUniqueUriIdentityExistWithinCity(string $uriIdentity, City $city): bool
  181.     {
  182.         $connection = $this->_em->getConnection();
  183.         $stmt = $connection->executeQuery('SELECT COUNT(id) FROM profiles WHERE uri_identity = ? AND city_id = ?', [$uriIdentity, $city->getId()]);
  184.         $count = $stmt->fetchOne();
  185.         return $count > 0;
  186.     }
  187.     public function countByCity(): array
  188.     {
  189.         $qb = $this->createQueryBuilder('profile')
  190.             ->select('IDENTITY(profile.city), COUNT(profile.id)')
  191.             ->groupBy('profile.city');
  192.         $this->addFemaleGenderFilterToQb($qb, 'profile');
  193.         $this->addModerationFilterToQb($qb, 'profile');
  194.         //$this->excludeHavingPlacementHiding($qb, 'profile');
  195.         $this->havingAdBoardPlacement($qb, 'profile');
  196.         $query = $qb->getQuery()
  197.             ->useResultCache(true)
  198.             ->setResultCacheLifetime(120);
  199.         $rawResult = $query->getScalarResult();
  200.         $indexedResult = [];
  201.         foreach ($rawResult as $row) {
  202.             $indexedResult[$row[1]] = $row[2];
  203.         }
  204.         return $indexedResult;
  205.     }
  206.     protected function addFemaleGenderFilterToQb(QueryBuilder $qb, string $alias): void
  207.     {
  208.         $this->addGenderFilterToQb($qb, $alias, [Genders::FEMALE]);
  209.     }
  210.     protected function addGenderFilterToQb(QueryBuilder $qb, string $alias, array $genders = [Genders::FEMALE]): void
  211.     {
  212.         $qb->andWhere(sprintf('%s.personParameters.gender IN (:genders)', $alias));
  213.         $qb->setParameter('genders', $genders);
  214.     }
  215.     private function havingAdBoardPlacement(QueryBuilder $qb, string $alias): void
  216.     {
  217.         $qb->join(sprintf('%s.adBoardPlacement', $alias), 'adboard_placement');
  218.     }
  219.     public function countByStations(): array
  220.     {
  221.         $qb = $this->createQueryBuilder('profiles')
  222.             ->select('stations.id, COUNT(profiles.id) as cnt')
  223.             ->join('profiles.stations', 'stations')
  224.             //это условие сильно затормжаживает запрос, но оно и не нужно при условии, что чужих(от других городов) станций у анкеты нет
  225.             //->where('profiles.city = stations.city')
  226.             ->groupBy('stations.id');
  227.         $this->addFemaleGenderFilterToQb($qb, 'profiles');
  228.         $this->addModerationFilterToQb($qb, 'profiles');
  229.         //$this->excludeHavingPlacementHiding($qb, 'profiles');
  230.         $this->havingAdBoardPlacement($qb, 'profiles');
  231.         $query = $qb->getQuery()
  232.             ->useResultCache(true)
  233.             ->setResultCacheLifetime(120);
  234.         $rawResult = $query->getScalarResult();
  235.         $indexedResult = [];
  236.         foreach ($rawResult as $row) {
  237.             $indexedResult[$row['id']] = $row['cnt'];
  238.         }
  239.         return $indexedResult;
  240.     }
  241.     public function countByDistricts(): array
  242.     {
  243.         $qb = $this->createQueryBuilder('profiles')
  244.             ->select('districts.id, COUNT(profiles.id) as cnt')
  245.             ->join('profiles.stations', 'stations')
  246.             ->join('stations.district', 'districts')
  247.             ->groupBy('districts.id');
  248.         $this->addFemaleGenderFilterToQb($qb, 'profiles');
  249.         $this->addModerationFilterToQb($qb, 'profiles');
  250.         //$this->excludeHavingPlacementHiding($qb, 'profiles');
  251.         $this->havingAdBoardPlacement($qb, 'profiles');
  252.         $query = $qb->getQuery()
  253.             ->useResultCache(true)
  254.             ->setResultCacheLifetime(120);
  255.         $rawResult = $query->getScalarResult();
  256.         $indexedResult = [];
  257.         foreach ($rawResult as $row) {
  258.             $indexedResult[$row['id']] = $row['cnt'];
  259.         }
  260.         return $indexedResult;
  261.     }
  262.     public function countByCounties(): array
  263.     {
  264.         $qb = $this->createQueryBuilder('profiles')
  265.             ->select('counties.id, COUNT(profiles.id) as cnt')
  266.             ->join('profiles.stations', 'stations')
  267.             ->join('stations.district', 'districts')
  268.             ->join('districts.county', 'counties')
  269.             ->groupBy('counties.id');
  270.         $this->addFemaleGenderFilterToQb($qb, 'profiles');
  271.         $this->addModerationFilterToQb($qb, 'profiles');
  272.         //$this->excludeHavingPlacementHiding($qb, 'profiles');
  273.         $this->havingAdBoardPlacement($qb, 'profiles');
  274.         $query = $qb->getQuery()
  275.             ->useResultCache(true)
  276.             ->setResultCacheLifetime(120);
  277.         $rawResult = $query->getScalarResult();
  278.         $indexedResult = [];
  279.         foreach ($rawResult as $row) {
  280.             $indexedResult[$row['id']] = $row['cnt'];
  281.         }
  282.         return $indexedResult;
  283.     }
  284.     /**
  285.      * @param array|int[] $ids
  286.      * @return Profile[]
  287.      */
  288.     public function findByIds(array $ids): array
  289.     {
  290.         return $this->createQueryBuilder('profile')
  291.             ->andWhere('profile.id IN (:ids)')
  292.             ->setParameter('ids', $ids)
  293.             ->orderBy('FIELD(profile.id,:ids2)')
  294.             ->setParameter('ids2', $ids)
  295.             ->getQuery()
  296.             ->getResult();
  297.     }
  298.     public function findByIdsIterate(array $ids): iterable
  299.     {
  300.         $qb = $this->createQueryBuilder('profile')
  301.             ->andWhere('profile.id IN (:ids)')
  302.             ->setParameter('ids', $ids)
  303.             ->orderBy('FIELD(profile.id,:ids2)')
  304.             ->setParameter('ids2', $ids);
  305.         return $this->iterateQueryBuilder($qb);
  306.     }
  307.     /**
  308.      * Список анкет указанного типа (массажистки или нет), привязанных к аккаунту
  309.      */
  310.     public function ofOwnerAndTypePaged(User $owner, bool $masseurs): ORMQueryResult
  311.     {
  312.         $qb = $this->createQueryBuilder('profile')
  313.             ->andWhere('profile.owner = :owner')
  314.             ->setParameter('owner', $owner)
  315.             ->andWhere('profile.masseur = :is_masseur')
  316.             ->setParameter('is_masseur', $masseurs);
  317.         return new ORMQueryResult($qb);
  318.     }
  319.     /**
  320.      * Список активных анкет, привязанных к аккаунту
  321.      */
  322.     public function activeAndOwnedBy(User $owner): ORMQueryResult
  323.     {
  324.         $qb = $this->createQueryBuilder('profile')
  325.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  326.             ->andWhere('profile.owner = :owner')
  327.             ->setParameter('owner', $owner);
  328.         return new ORMQueryResult($qb);
  329.     }
  330.     /**
  331.      * Список активных или скрытых анкет, привязанных к аккаунту
  332.      *
  333.      * @return Profile[]|ORMQueryResult
  334.      */
  335.     public function activeOrHiddenAndOwnedBy(User $owner): ORMQueryResult
  336.     {
  337.         $qb = $this->createQueryBuilder('profile')
  338.             ->leftJoin('profile.adBoardPlacement', 'profile_adboard_placement')
  339.             ->leftJoin('profile.placementHiding', 'placement_hiding')
  340.             ->andWhere('profile_adboard_placement IS NOT NULL OR placement_hiding IS NOT NULL')
  341.             ->andWhere('profile.owner = :owner')
  342.             ->setParameter('owner', $owner);
  343.         return new ORMQueryResult($qb);
  344.     }
  345.     public function activePaidAdBoardPlacementAndOwnedBy(User $owner): ORMQueryResult
  346.     {
  347.         $qb = $this->createQueryBuilder('profile')
  348.             ->addSelect('profile_adboard_placement', 'placement_price', 'city', 'owner')
  349.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  350.             ->leftJoin('profile_adboard_placement.placementPrice', 'placement_price')
  351.             ->join('profile.city', 'city')
  352.             ->join('profile.owner', 'owner')
  353.             ->andWhere('profile_adboard_placement.type <> :free_placement_type')
  354.             ->andWhere('profile.owner = :owner')
  355.             ->setParameter('free_placement_type', AdBoardPlacementType::FREE)
  356.             ->setParameter('owner', $owner);
  357.         return new ORMQueryResult($qb);
  358.     }
  359.     public function paidAdBoardPlacementChargeRowsOfOwner(User $owner): array
  360.     {
  361.         $qb = $this->createQueryBuilder('profile')
  362.             ->select([
  363.                 'profile.id AS profile_id',
  364.                 'profile.approved AS approved',
  365.                 'profile.masseur AS is_masseur',
  366.                 'profile.personParameters.gender AS gender',
  367.                 'profile_adboard_placement.type AS placement_type',
  368.                 'profile_adboard_placement.planManaged AS plan_managed',
  369.                 'placement_price.id AS placement_price_id',
  370.                 'placement_price.priceAmount AS price_amount',
  371.                 'placement_price.duration AS duration',
  372.                 'placement_price.currency AS currency',
  373.                 'placement_price.dynamicPriceMatrix AS dynamic_price_matrix',
  374.                 'city.id AS city_id',
  375.                 'city.cityPriceCategory AS city_price_category',
  376.                 'city.timezone AS timezone',
  377.                 'owner.currencyCode AS owner_currency',
  378.             ])
  379.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  380.             ->leftJoin('profile_adboard_placement.placementPrice', 'placement_price')
  381.             ->join('profile.city', 'city')
  382.             ->join('profile.owner', 'owner')
  383.             ->andWhere('profile_adboard_placement.type <> :free_placement_type')
  384.             ->andWhere('profile.owner = :owner')
  385.             ->setParameter('free_placement_type', AdBoardPlacementType::FREE)
  386.             ->setParameter('owner', $owner);
  387.         return $qb->getQuery()->getArrayResult();
  388.     }
  389.     public function currentChargeableAndOwnedBy(User $owner): ORMQueryResult
  390.     {
  391.         $qb = $this->createQueryBuilder('profile')
  392.             ->addSelect('profile_adboard_placement', 'placement_price', 'placement_hiding', 'city', 'owner')
  393.             ->leftJoin('profile.adBoardPlacement', 'profile_adboard_placement')
  394.             ->leftJoin('profile_adboard_placement.placementPrice', 'placement_price')
  395.             ->leftJoin('profile.placementHiding', 'placement_hiding')
  396.             ->join('profile.city', 'city')
  397.             ->join('profile.owner', 'owner')
  398.             ->andWhere('(profile_adboard_placement IS NOT NULL AND profile_adboard_placement.type <> :free_placement_type) OR placement_hiding IS NOT NULL')
  399.             ->andWhere('profile.owner = :owner')
  400.             ->setParameter('free_placement_type', AdBoardPlacementType::FREE)
  401.             ->setParameter('owner', $owner);
  402.         return new ORMQueryResult($qb);
  403.     }
  404.     public function countFreeUnapprovedLimited(): int
  405.     {
  406.         $qb = $this->createQueryBuilder('profile')
  407.             ->select('count(profile)')
  408.             ->join('profile.adBoardPlacement', 'placement')
  409.             ->andWhere('placement.type = :placement_type')
  410.             ->setParameter('placement_type', AdBoardPlacementType::FREE)
  411.             ->leftJoin('profile.placementHiding', 'hiding')
  412.             ->andWhere('hiding IS NULL')
  413.             ->andWhere('profile.approved = false');
  414.         return (int)$qb->getQuery()->getSingleScalarResult();
  415.     }
  416.     public function iterateFreeUnapprovedLimited(int $limit): iterable
  417.     {
  418.         $qb = $this->createQueryBuilder('profile')
  419.             ->join('profile.adBoardPlacement', 'placement')
  420.             ->andWhere('placement.type = :placement_type')
  421.             ->setParameter('placement_type', AdBoardPlacementType::FREE)
  422.             ->leftJoin('profile.placementHiding', 'hiding')
  423.             ->andWhere('hiding IS NULL')
  424.             ->andWhere('profile.approved = false')
  425.             ->setMaxResults($limit);
  426.         return $this->iterateQueryBuilder($qb);
  427.     }
  428.     /**
  429.      * Число активных анкет, привязанных к аккаунту
  430.      */
  431.     public function countActiveOfOwner(User $owner, ?bool $isMasseur = false): int
  432.     {
  433.         $qb = $this->createQueryBuilder('profile')
  434.             ->select('COUNT(profile.id)')
  435.             ->join('profile.adBoardPlacement', 'profile_adboard_placement')
  436.             ->andWhere('profile.owner = :owner')
  437.             ->setParameter('owner', $owner);
  438.         if ($this->features->hard_moderation()) {
  439.             $qb->leftJoin('profile.owner', 'owner');
  440.             $qb->andWhere(
  441.                 $qb->expr()->orX(
  442.                     'profile.moderationStatus = :status_passed',
  443.                     $qb->expr()->andX(
  444.                         'profile.moderationStatus = :status_waiting',
  445.                         'owner.trusted = true'
  446.                     )
  447.                 )
  448.             );
  449.             $qb->setParameter('status_passed', Profile::MODERATION_STATUS_APPROVED);
  450.             $qb->setParameter('status_waiting', Profile::MODERATION_STATUS_WAITING);
  451.         } else {
  452.             $qb->andWhere('profile.moderationStatus IN (:statuses)')
  453.                 ->setParameter('statuses', [Profile::MODERATION_STATUS_NOT_PASSED, Profile::MODERATION_STATUS_WAITING, Profile::MODERATION_STATUS_APPROVED]);
  454.         }
  455.         if (null !== $isMasseur) {
  456.             $qb->andWhere('profile.masseur = :is_masseur')
  457.                 ->setParameter('is_masseur', $isMasseur);
  458.         }
  459.         return (int)$qb->getQuery()->getSingleScalarResult();
  460.     }
  461.     /**
  462.      * Число всех анкет, привязанных к аккаунту
  463.      */
  464.     public function countAllOfOwnerNotDeleted(User $owner, ?bool $isMasseur = false): int
  465.     {
  466.         $qb = $this->createQueryBuilder('profile')
  467.             ->select('COUNT(profile.id)')
  468.             ->andWhere('profile.owner = :owner')
  469.             ->setParameter('owner', $owner)
  470.             //потому что используется в т.ч. на тех страницах, где отключен фильтр вывода "только неудаленных"
  471.             ->andWhere('profile.deletedAt IS NULL');
  472.         if (null !== $isMasseur) {
  473.             $qb->andWhere('profile.masseur = :is_masseur')
  474.                 ->setParameter('is_masseur', $isMasseur);
  475.         }
  476.         return (int)$qb->getQuery()->getSingleScalarResult();
  477.     }
  478.     public function findPreviewByOwner(Advertiser $owner, int $limit): array
  479.     {
  480.         return $this->createQueryBuilder('profile')
  481.             ->addSelect('city')
  482.             ->join('profile.city', 'city')
  483.             ->andWhere('profile.owner = :owner')
  484.             ->andWhere('profile.deletedAt IS NULL')
  485.             ->setParameter('owner', $owner)
  486.             ->orderBy('profile.id', 'DESC')
  487.             ->setMaxResults($limit)
  488.             ->getQuery()
  489.             ->getResult();
  490.     }
  491.     public function getTimezonesListByUser(User $owner): array
  492.     {
  493.         $q = $this->_em->createQuery(sprintf("
  494.                 SELECT c
  495.                 FROM %s c
  496.                 WHERE c.id IN (
  497.                     SELECT DISTINCT(c2.id) 
  498.                     FROM %s p
  499.                     JOIN p.city c2
  500.                     WHERE p.owner = :user
  501.                 )
  502.             ", $this->_em->getClassMetadata(City::class)->name, $this->_em->getClassMetadata(Profile::class)->name))
  503.             ->setParameter('user', $owner);
  504.         return $q->getResult();
  505.     }
  506.     /**
  507.      * Список анкет, привязанных к аккаунту
  508.      *
  509.      * @return Profile[]
  510.      */
  511.     public function ofOwner(User $owner): array
  512.     {
  513.         $qb = $this->createQueryBuilder('profile')
  514.             ->andWhere('profile.owner = :owner')
  515.             ->setParameter('owner', $owner);
  516.         return $qb->getQuery()->getResult();
  517.     }
  518.     public function ofOwnerPaged(User $owner, array $genders = [Genders::FEMALE]): ORMQueryResult
  519.     {
  520.         $qb = $this->createQueryBuilder('profile')
  521.             ->andWhere('profile.owner = :owner')
  522.             ->setParameter('owner', $owner)
  523.             ->andWhere('profile.personParameters.gender IN (:genders)')
  524.             ->setParameter('genders', $genders);
  525.         return new ORMQueryResult($qb);
  526.     }
  527.     public function searchLinkableToSaloonByOwner(User $owner, ?string $query, int $limit = 20): array
  528.     {
  529.         $qb = $this->createQueryBuilder('profile')
  530.             ->andWhere('profile.owner = :owner')
  531.             ->setParameter('owner', $owner)
  532.             ->orderBy('profile.id', 'DESC')
  533.             ->setMaxResults($limit)
  534.         ;
  535.         if ($query) {
  536.             $qb
  537.                 ->andWhere('LOWER(JSON_UNQUOTE(JSON_EXTRACT(profile.name, :json_path))) LIKE :query')
  538.                 ->setParameter('json_path', '$.ru')
  539.                 ->setParameter('query', '%' . addcslashes(mb_strtolower(trim($query)), '%_') . '%')
  540.             ;
  541.         }
  542.         return $qb->getQuery()->getResult();
  543.     }
  544.     public function findLinkableToSaloonByOwnerAndIds(User $owner, array $ids): array
  545.     {
  546.         $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
  547.         if (empty($ids)) {
  548.             return [];
  549.         }
  550.         return $this->createQueryBuilder('profile')
  551.             ->andWhere('profile.owner = :owner')
  552.             ->andWhere('profile.id IN (:ids)')
  553.             ->setParameter('owner', $owner)
  554.             ->setParameter('ids', $ids)
  555.             ->getQuery()
  556.             ->getResult()
  557.         ;
  558.     }
  559.     public function findPublicProfilesBySaloon(Saloon $saloon, int $limit = 6, int $offset = 0): array
  560.     {
  561.         $profiles = $this->createPublicProfilesBySaloonQueryBuilder($saloon)
  562.             ->addSelect('placement')
  563.             ->orderBy('profile.id', 'DESC')
  564.             ->setMaxResults($limit)
  565.             ->setFirstResult($offset)
  566.             ->getQuery()
  567.             ->getResult()
  568.         ;
  569.         $this->loadPublicProfilePreviewRelations($profiles);
  570.         return $profiles;
  571.     }
  572.     public function countPublicProfilesBySaloon(Saloon $saloon): int
  573.     {
  574.         return (int)$this->createPublicProfilesBySaloonQueryBuilder($saloon)
  575.             ->select('COUNT(DISTINCT profile.id)')
  576.             ->getQuery()
  577.             ->getSingleScalarResult()
  578.         ;
  579.     }
  580.     public function findPublicProfilesBySaloonCircular(Saloon $saloon, int $limit, int $offset, int $total): array
  581.     {
  582.         if ($total <= 0 || $limit <= 0) {
  583.             return [];
  584.         }
  585.         $offset %= $total;
  586.         $firstChunkLimit = min($limit, $total - $offset);
  587.         $profiles = $this->findPublicProfilesBySaloon($saloon, $firstChunkLimit, $offset);
  588.         if (count($profiles) < $limit && $offset > 0) {
  589.             $profiles = array_merge(
  590.                 $profiles,
  591.                 $this->findPublicProfilesBySaloon($saloon, $limit - count($profiles), 0)
  592.             );
  593.         }
  594.         return $profiles;
  595.     }
  596.     public function findPublicProfilesBySaloonRotatedByPlacementStatus(Saloon $saloon, int $limit, int $offset, int $rotationSeed): array
  597.     {
  598.         if ($limit <= 0) {
  599.             return [];
  600.         }
  601.         $profiles = $this->createPublicProfilesBySaloonQueryBuilder($saloon)
  602.             ->addSelect('placement')
  603.             ->orderBy('placement.type', 'DESC')
  604.             ->addOrderBy('placement.placedAt', 'DESC')
  605.             ->addOrderBy('profile.id', 'DESC')
  606.             ->getQuery()
  607.             ->getResult()
  608.         ;
  609.         $profiles = array_slice($this->rotateProfilesWithinPlacementTypes($profiles, $rotationSeed), $offset, $limit);
  610.         $this->loadPublicProfilePreviewRelations($profiles);
  611.         return $profiles;
  612.     }
  613.     private function rotateProfilesWithinPlacementTypes(array $profiles, int $rotationSeed): array
  614.     {
  615.         $profilesByPlacementType = [];
  616.         foreach ($profiles as $profile) {
  617.             $profilesByPlacementType[$this->getProfilePlacementPriority($profile)][] = $profile;
  618.         }
  619.         krsort($profilesByPlacementType, SORT_NUMERIC);
  620.         $rotatedProfiles = [];
  621.         foreach ($profilesByPlacementType as $profilesGroup) {
  622.             $profilesGroupCount = count($profilesGroup);
  623.             $groupOffset = $profilesGroupCount > 0 ? $rotationSeed % $profilesGroupCount : 0;
  624.             if (0 === $groupOffset) {
  625.                 $rotatedProfiles = array_merge($rotatedProfiles, $profilesGroup);
  626.                 continue;
  627.             }
  628.             $rotatedProfiles = array_merge(
  629.                 $rotatedProfiles,
  630.                 array_slice($profilesGroup, $groupOffset),
  631.                 array_slice($profilesGroup, 0, $groupOffset)
  632.             );
  633.         }
  634.         return $rotatedProfiles;
  635.     }
  636.     private function getProfilePlacementPriority(Profile $profile): int
  637.     {
  638.         $placement = $profile->getAdBoardPlacement();
  639.         return $placement instanceof AdBoardPlacement ? $placement->getType()->getValue() : 0;
  640.     }
  641.     private function createPublicProfilesBySaloonQueryBuilder(Saloon $saloon): QueryBuilder
  642.     {
  643.         return $this->createQueryBuilder('profile')
  644.             ->leftJoin('profile.adBoardPlacement', 'placement')
  645.             ->leftJoin('profile.placementHiding', 'placement_hiding')
  646.             ->andWhere('profile.saloon = :saloon')
  647.             ->andWhere('profile.moderationStatus = :moderation_status')
  648.             ->andWhere('placement_hiding IS NULL')
  649.             ->setParameter('saloon', $saloon)
  650.             ->setParameter('moderation_status', Profile::MODERATION_STATUS_APPROVED)
  651.         ;
  652.     }
  653.     private function loadPublicProfilePreviewRelations(array $profiles): void
  654.     {
  655.         if (empty($profiles)) {
  656.             return;
  657.         }
  658.         $this->createQueryBuilder('profile')
  659.             ->leftJoin('profile.city', 'city')
  660.             ->leftJoin('profile.stations', 'station')
  661.             ->leftJoin('profile.avatar', 'avatar')
  662.             ->leftJoin('profile.photos', 'photo')
  663.             ->addSelect('city')
  664.             ->addSelect('station')
  665.             ->addSelect('avatar')
  666.             ->addSelect('photo')
  667.             ->andWhere('profile IN (:profiles)')
  668.             ->setParameter('profiles', $profiles)
  669.             ->getQuery()
  670.             ->getResult()
  671.         ;
  672.     }
  673.     public function ofOwnerAndMasseurTypeWithPlacementFilterAndNameFilterIterateAll(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): \Generator
  674.     {
  675.         $query = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur)->getQuery();
  676.         foreach ($query->iterate() as $row) {
  677.             yield $row[0];
  678.         }
  679.     }
  680.     private function queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): QueryBuilder
  681.     {
  682.         $qb = $this->createQueryBuilder('profile')
  683.             ->andWhere('profile.owner = :owner')
  684.             ->setParameter('owner', $owner);
  685.         switch ($placementTypeFilter) {
  686.             case 'paid':
  687.                 $qb->join('profile.adBoardPlacement', 'placement')
  688.                     ->andWhere('placement.type != :placement_type')
  689.                     ->setParameter('placement_type', AdBoardPlacementType::FREE);
  690.                 break;
  691.             case 'free':
  692.                 $qb->join('profile.adBoardPlacement', 'placement')
  693.                     ->andWhere('placement.type = :placement_type')
  694.                     ->setParameter('placement_type', AdBoardPlacementType::FREE);
  695.                 break;
  696.             case 'ultra-vip':
  697.                 $qb->join('profile.adBoardPlacement', 'placement')
  698.                     ->andWhere('placement.type = :placement_type')
  699.                     ->setParameter('placement_type', AdBoardPlacementType::ULTRA_VIP);
  700.                 break;
  701.             case 'vip':
  702.                 $qb->join('profile.adBoardPlacement', 'placement')
  703.                     ->andWhere('placement.type = :placement_type')
  704.                     ->setParameter('placement_type', AdBoardPlacementType::VIP);
  705.                 break;
  706.             case 'standard':
  707.                 $qb->join('profile.adBoardPlacement', 'placement')
  708.                     ->andWhere('placement.type = :placement_type')
  709.                     ->setParameter('placement_type', AdBoardPlacementType::STANDARD);
  710.                 break;
  711.             case 'hidden':
  712.                 $qb->join('profile.placementHiding', 'placement_hiding');
  713.                 break;
  714.             case 'all':
  715.             default:
  716.                 break;
  717.         }
  718.         if ($nameFilter) {
  719.             $nameExpr = $qb->expr()->orX(
  720.                 'LOWER(JSON_UNQUOTE(JSON_EXTRACT(profile.name, :jsonPath))) LIKE :name_filter',
  721.                 \sprintf("REGEXP_REPLACE(profile.phoneNumber, '-| ', '') LIKE :name_filter"),
  722.                 'LOWER(profile.phoneNumber) LIKE :name_filter',
  723.                 \sprintf("REGEXP_REPLACE(profile.phoneNumber, '\+7', '8') LIKE :name_filter"),
  724.             );
  725.             $qb->setParameter('jsonPath', '$.ru');
  726.             $qb->setParameter('name_filter', '%' . addcslashes(mb_strtolower(str_replace(['(', ')', ' ', '-'], '', $nameFilter)), '%_') . '%');
  727.             $qb->andWhere($nameExpr);
  728.         }
  729.         if (null !== $isMasseur) {
  730.             $qb->andWhere('profile.masseur = :is_masseur')
  731.                 ->setParameter('is_masseur', $isMasseur);
  732.         }
  733.         return $qb;
  734.     }
  735.     public function ofOwnerAndMasseurTypeWithPlacementFilterAndNameFilterPaged(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): ORMQueryResult
  736.     {
  737.         $qb = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur);
  738.         //сортируем анкеты по статусу UltraVip->Vip->Standard->Free->Hidden
  739.         $aliases = $qb->getAllAliases();
  740.         if (false == in_array('placement', $aliases))
  741.             $qb->leftJoin('profile.adBoardPlacement', 'placement');
  742.         if (false == in_array('placement_hiding', $aliases))
  743.             $qb->leftJoin('profile.placementHiding', 'placement_hiding');
  744.         $qb->addSelect('IF(placement_hiding.id IS NULL, 0, 1) as HIDDEN is_hidden');
  745.         $qb->addOrderBy('placement.type', 'DESC');
  746.         $qb->addOrderBy('placement.placedAt', 'DESC');
  747.         $qb->addOrderBy('is_hidden', 'ASC');
  748.         return new ORMQueryResult($qb);
  749.     }
  750.     public function idsOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): array
  751.     {
  752.         $qb = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur);
  753.         $qb->select('profile.id');
  754.         return $qb->getQuery()->getResult('column_hydrator');
  755.     }
  756.     public function countOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $owner, string $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur = null): int
  757.     {
  758.         $qb = $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner, $placementTypeFilter, $nameFilter, $isMasseur);
  759.         $qb->select('count(profile.id)')
  760.             ->setMaxResults(1);
  761.         return (int)$qb->getQuery()->getSingleScalarResult();
  762.     }
  763.     /**
  764.      * @deprecated
  765.      */
  766.     public function hydrateProfileRow(array $row): ProfileListingReadModel
  767.     {
  768.         $profile = new ProfileListingReadModel();
  769.         $profile->id = $row['id'];
  770.         $profile->city = $row['city'];
  771.         $profile->uriIdentity = $row['uriIdentity'];
  772.         $profile->name = $row['name'];
  773.         $profile->description = $row['description'];
  774.         $profile->phoneNumber = $row['phoneNumber'];
  775.         $profile->isMasseur = $row['masseur'];
  776.         $profile->approved = $row['approved'];
  777.         $now = new \DateTimeImmutable('now');
  778.         $hasRunningTopPlacement = false;
  779.         foreach ($row['topPlacements'] as $topPlacement) {
  780.             if ($topPlacement['placedAt'] <= $now && $now <= $topPlacement['expiresAt'])
  781.                 $hasRunningTopPlacement = true;
  782.         }
  783.         $profile->active = null !== $row['adBoardPlacement'] || $hasRunningTopPlacement;
  784.         $profile->hidden = null != $row['placementHiding'];
  785.         $profile->personParameters = new ProfilePersonParametersReadModel();
  786.         $profile->personParameters->age = $row['personParameters.age'];
  787.         $profile->personParameters->height = $row['personParameters.height'];
  788.         $profile->personParameters->weight = $row['personParameters.weight'];
  789.         $profile->personParameters->breastSize = $row['personParameters.breastSize'];
  790.         $profile->personParameters->bodyType = $row['personParameters.bodyType'];
  791.         $profile->personParameters->hairColor = $row['personParameters.hairColor'];
  792.         $profile->personParameters->privateHaircut = $row['personParameters.privateHaircut'];
  793.         $profile->personParameters->nationality = $row['personParameters.nationality'];
  794.         $profile->personParameters->appearance = $row['personParameters.appearance'];
  795.         $profile->personParameters->hasTattoo = $row['personParameters.hasTattoo'];
  796.         $profile->personParameters->hasPiercing = $row['personParameters.hasPiercing'];
  797.         $profile->stations = $row['stations'];
  798.         $profile->avatar = $row['avatar'];
  799.         foreach ($row['photos'] as $photo)
  800.             if ($photo['main'])
  801.                 $profile->mainPhoto = $photo;
  802.         $profile->mainPhoto = null;
  803.         $profile->photos = [];
  804.         $profile->selfies = [];
  805.         foreach ($row['photos'] as $photo) {
  806.             if ($photo['main'])
  807.                 $profile->mainPhoto = $photo;
  808.             if ($photo['type'] == Photo::TYPE_PHOTO)
  809.                 $profile->photos[] = $photo;
  810.             if ($photo['type'] == Photo::TYPE_SELFIE)
  811.                 $profile->selfies[] = $photo;
  812.         }
  813.         $profile->videos = $row['videos'];
  814.         $profile->comments = $row['comments'];
  815.         $profile->apartmentsPricing = new ProfileApartmentPricingReadModel();
  816.         $profile->apartmentsPricing->oneHourPrice = $row['apartmentsPricing.oneHourPrice'];
  817.         $profile->apartmentsPricing->twoHoursPrice = $row['apartmentsPricing.twoHoursPrice'];
  818.         $profile->apartmentsPricing->nightPrice = $row['apartmentsPricing.nightPrice'];
  819.         $profile->takeOutPricing = new ProfileTakeOutPricingReadModel();
  820.         $profile->takeOutPricing->oneHourPrice = $row['takeOutPricing.oneHourPrice'];
  821.         $profile->takeOutPricing->twoHoursPrice = $row['takeOutPricing.twoHoursPrice'];
  822.         $profile->takeOutPricing->nightPrice = $row['takeOutPricing.nightPrice'];
  823.         return $profile;
  824.     }
  825.     public function deletedByPeriod(\DateTimeInterface $start, \DateTimeInterface $end): array
  826.     {
  827.         $qb = $this->createQueryBuilder('profile')
  828.             ->join('profile.city', 'city')
  829.             ->select('profile.uriIdentity _profile')
  830.             ->addSelect('city.uriIdentity _city')
  831.             ->andWhere('profile.deletedAt >= :start')
  832.             ->andWhere('profile.deletedAt <= :end')
  833.             ->setParameter('start', $start)
  834.             ->setParameter('end', $end);
  835.         return $qb->getQuery()->getResult();
  836.     }
  837.     public function listForMapMatchingSpec(Filter|QueryModifier $specification, int $coordinatesRoundPrecision = 3): array
  838.     {
  839.         $this->getEntityManager()->getConnection()->executeQuery("
  840.             SET SESSION group_concat_max_len = 100000;
  841.         ");
  842.         /** @var QueryBuilder $qb */
  843.         $qb = $this->createQueryBuilder($dqlAlias = 'p');
  844.         $qb->select(sprintf('GROUP_CONCAT(p.id), CONCAT(ROUND(MIN(p.mapCoordinate.latitude),5),\',\',ROUND(MIN(p.mapCoordinate.longitude),5)), count(p.id), CONCAT(ROUND(p.mapCoordinate.latitude,%1$s),\',\',ROUND(p.mapCoordinate.longitude,%1$s)) as coords, GROUP_CONCAT(p.masseur)', $coordinatesRoundPrecision));
  845.         $qb->groupBy('coords');
  846.         $specification->modify($qb, $dqlAlias);
  847.         $qb->andWhere($specification->getFilter($qb, $dqlAlias));
  848.         return $qb->getQuery()->getResult();
  849.     }
  850.     /**
  851.      * Clustered map points for JSON API mode=map.
  852.      * Representative point is the centroid (AVG), not MIN as in listForMapMatchingSpec().
  853.      */
  854.     public function listMapClustersMatchingSpec(Filter|QueryModifier $specification, int $coordinatesRoundPrecision): array
  855.     {
  856.         $this->getEntityManager()->getConnection()->executeQuery("
  857.             SET SESSION group_concat_max_len = 100000;
  858.         ");
  859.         $precision = (int) $coordinatesRoundPrecision;
  860.         /** @var QueryBuilder $qb */
  861.         $qb = $this->createQueryBuilder($dqlAlias = 'p');
  862.         $qb->select(sprintf(
  863.             '%s, '
  864.             . 'GROUP_CONCAT(p.id ORDER BY p.id) AS ids, '
  865.             . 'COUNT(p.id) AS cnt, '
  866.             . 'ROUND(AVG(p.mapCoordinate.latitude), 5) AS lat, '
  867.             . 'ROUND(AVG(p.mapCoordinate.longitude), 5) AS lng, '
  868.             . 'CONCAT(ROUND(p.mapCoordinate.latitude, %2$d), \',\', ROUND(p.mapCoordinate.longitude, %2$d)) AS coords, '
  869.             . 'GROUP_CONCAT(p.masseur ORDER BY p.id) AS masseurFlags',
  870.             MapClusterMinPriceDql::clusterMinPriceSelect($dqlAlias),
  871.             $precision
  872.         ));
  873.         $qb->groupBy('coords');
  874.         $specification->modify($qb, $dqlAlias);
  875.         $qb->andWhere($specification->getFilter($qb, $dqlAlias));
  876.         return $qb->getQuery()->getResult();
  877.     }
  878.     public function fetchListingByIds(ProfileIdINOrderedByINValues $specification): array
  879.     {
  880.         $ids = implode(',', $specification->getIds());
  881.         $mediaType = $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO;
  882.         $mediaIsMain = $this->features->crop_avatar() ? 0 : 1;
  883.         $sql = "
  884.             SELECT 
  885.                 p.*, JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  886.                     as `name`, 
  887.                 JSON_UNQUOTE(JSON_EXTRACT(p.description, '$.ru')) 
  888.                     as `description`,
  889.                 (SELECT path FROM profile_media_files pmf_avatar WHERE p.id = pmf_avatar.profile_id AND pmf_avatar.type = '{$mediaType}' AND pmf_avatar.is_main = {$mediaIsMain} LIMIT 1) 
  890.                     as `avatar_path`,
  891.                 (SELECT type FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  892.                     as `adboard_placement_type`,
  893.                 (SELECT position FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  894.                     as `adboard_placement_position`,
  895.                 c.id 
  896.                     as `city_id`, 
  897.                 JSON_UNQUOTE(JSON_EXTRACT(c.name, '$.ru')) 
  898.                     as `city_name`, 
  899.                 c.uri_identity 
  900.                     as `city_uri_identity`,
  901.                 c.country_code 
  902.                     as `city_country_code`,
  903.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  904.                     as `has_top_placement`,
  905.                 EXISTS(SELECT * FROM placement_hidings ph WHERE p.id = ph.profile_id AND ph.entity_type = 'profile') 
  906.                     as `has_placement_hiding`,
  907.                 (SELECT COUNT(*) FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  908.                     as `comments_count`,
  909.                 (SELECT COUNT(*) FROM profile_media_files pmf_photo WHERE p.id = pmf_photo.profile_id AND pmf_photo.type = 'photo') 
  910.                     as `photos_count`,
  911.                 (SELECT COUNT(*) FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  912.                     as `videos_count`,
  913.                 (SELECT COUNT(*) FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  914.                     as `selfies_count`,
  915.                 p.primary_station_id 
  916.             FROM profiles `p`
  917.             JOIN cities `c` ON c.id = p.city_id 
  918.             WHERE p.id IN ($ids)
  919.             ORDER BY FIELD(p.id,$ids)";
  920.         $connection = $this->getEntityManager()->getConnection();
  921.         $result = $connection->executeQuery($sql);
  922.         $profiles = $result->fetchAllAssociative();
  923.         $sql = "SELECT 
  924.                     cs.id 
  925.                         as `id`,
  926.                     JSON_UNQUOTE(JSON_EXTRACT(cs.name, '$.ru')) 
  927.                         as `name`, 
  928.                     cs.uri_identity 
  929.                         as `uriIdentity`, 
  930.                     ps.profile_id
  931.                         as `profile_id`,
  932.                     csl.name
  933.                         as `line_name`,
  934.                     csl.color
  935.                         as `line_color`,
  936.                     cs.county_id, cs.district_id
  937.                 FROM profile_stations ps
  938.                 JOIN city_stations cs ON ps.station_id = cs.id 
  939.                 LEFT JOIN city_subway_station_lines cssl ON cssl.station_id = cs.id
  940.                 LEFT JOIN city_subway_lines csl ON csl.id = cssl.line_id
  941.                 WHERE ps.profile_id IN ($ids)";
  942.         $result = $connection->executeQuery($sql);
  943.         $stations = $result->fetchAllAssociative();
  944.         $districtIds = array_unique(array_column($stations, 'district_id'));
  945.         $districts = $this->districts->ofIds($districtIds);
  946.         $sql = "SELECT 
  947.                     s.id 
  948.                         as `id`,
  949.                     JSON_UNQUOTE(JSON_EXTRACT(s.name, '$.ru')) 
  950.                         as `name`, 
  951.                     s.group 
  952.                         as `group`, 
  953.                     s.uri_identity 
  954.                         as `uriIdentity`,
  955.                     pps.profile_id
  956.                         as `profile_id`,
  957.                     pps.service_condition
  958.                         as `condition`,
  959.                     pps.extra_charge
  960.                         as `extra_charge`,
  961.                     pps.comment
  962.                         as `comment`
  963.                 FROM profile_provided_services pps
  964.                 JOIN services s ON pps.service_id = s.id 
  965.                 WHERE pps.profile_id IN ($ids)
  966.                 ORDER BY s.group ASC, s.sort ASC, s.id ASC";
  967.         $result = $connection->executeQuery($sql);
  968.         $providedServices = $result->fetchAllAssociative();
  969.         $profileNameUris = $this->fetchCanonicalNameUris($ids);
  970.         $result = array_map(function ($profile) use ($stations, $districts, $providedServices, $profileNameUris): ProfileListingReadModel {
  971.             return $this->hydrateProfileRow2($profile, $stations, $districts, $providedServices, $profileNameUris);
  972.         }, $profiles);
  973.         return $result;
  974.     }
  975.     public function hydrateProfileRow2(array $row, array $stations, array $districts, array $services, array $profileNameUris = []): ProfileListingReadModel
  976.     {
  977.         $profile = new ProfileListingReadModel();
  978.         $profile->id = $row['id'];
  979.         $profile->moderationStatus = $row['moderation_status'];
  980.         $profile->city = new CityReadModel();
  981.         $profile->city->id = $row['city_id'];
  982.         $profile->city->name = $row['city_name'];
  983.         $profile->city->uriIdentity = $row['city_uri_identity'];
  984.         $profile->city->countryCode = $row['city_country_code'];
  985.         $profile->uriIdentity = $row['uri_identity'];
  986.         $profile->name = $row['name'];
  987.         $profile->canonicalNameUris = $profileNameUris[$profile->id] ?? [];
  988.         $profile->description = $row['description'];
  989.         $profile->phoneNumber = $row['phone_number'];
  990.         $profile->isMasseur = (bool)$row['is_masseur'];
  991.         $profile->approved = (bool)$row['is_approved'];
  992.         $profile->isUltraVip = $row['adboard_placement_type'] == AdBoardPlacement::POSITION_GROUP_ULTRA_VIP;
  993.         $profile->isVip = $row['adboard_placement_type'] == AdBoardPlacement::POSITION_GROUP_VIP;
  994.         $profile->isStandard = false !== array_search(
  995.                 $row['adboard_placement_type'],
  996.                 [
  997.                     AdBoardPlacement::POSITION_GROUP_STANDARD_APPROVED, AdBoardPlacement::POSITION_GROUP_STANDARD,
  998.                     AdBoardPlacement::POSITION_GROUP_WITHOUT_OWNER_APPROVED, AdBoardPlacement::POSITION_GROUP_WITHOUT_OWNER
  999.                 ]
  1000.             );
  1001.         $profile->position = $row['adboard_placement_position'];
  1002.         $profile->active = null !== $row['adboard_placement_type'] || $row['has_top_placement'];
  1003.         $profile->hidden = $row['has_placement_hiding'] == true;
  1004.         $profile->personParameters = new ProfilePersonParametersReadModel();
  1005.         $profile->personParameters->age = $row['person_age'];
  1006.         $profile->personParameters->height = $row['person_height'];
  1007.         $profile->personParameters->weight = $row['person_weight'];
  1008.         $profile->personParameters->breastSize = $row['person_breast_size'];
  1009.         $profile->personParameters->bodyType = $row['person_body_type'];
  1010.         $profile->personParameters->hairColor = $row['person_hair_color'];
  1011.         $profile->personParameters->privateHaircut = $row['person_private_haircut'];
  1012.         $profile->personParameters->nationality = $row['person_nationality'];
  1013.         $profile->personParameters->appearance = $row['person_appearance'];
  1014.         $profile->personParameters->hasTattoo = $row['person_has_tattoo'];
  1015.         $profile->personParameters->hasPiercing = $row['person_has_piercing'];
  1016.         $profile->stations = [];
  1017.         $profile->districts = [];
  1018.         $profile->counties = [];
  1019.         foreach ($stations as $station) {
  1020.             if ($profile->id !== $station['profile_id'])
  1021.                 continue;
  1022.             $profileStation = $profile->stations[$station['id']] ?? new StationReadModel($station['id'], $station['uriIdentity'], $station['name'], []);
  1023.             if (null !== $station['line_name']) {
  1024.                 $profileStation->lines[] = new StationLineReadModel($station['line_name'], $station['line_color']);
  1025.             }
  1026.             $profile->stations[$station['id']] = $profileStation;
  1027.             if (array_key_exists($station['district_id'] ?? 0, $districts) && !array_key_exists($station['district_id'], $profile->districts)) {
  1028.                 $profile->districts[$station['district_id']] = $districts[$station['district_id']];
  1029.             }
  1030.         }
  1031.         $primaryId = (int)$row['primary_station_id'];
  1032.         if (!empty($profile->stations)) {
  1033.             uasort($profile->stations, function (StationReadModel $a, StationReadModel $b) use ($primaryId) {
  1034.                 $aPrimary = $a->id === $primaryId;
  1035.                 $bPrimary = $b->id === $primaryId;
  1036.                 if ($aPrimary !== $bPrimary) {
  1037.                     return $aPrimary ? -1 : 1;
  1038.                 }
  1039.                 return strnatcasecmp($a->name, $b->name);
  1040.             });
  1041.         }
  1042.         if ($primaryId) {
  1043.             $profile->primaryStation = $profile->stations[$primaryId] ?? null;
  1044.         }
  1045.         $profile->providedServices = [];
  1046.         foreach ($services as $service) {
  1047.             if ($profile->id !== $service['profile_id'])
  1048.                 continue;
  1049.             $providedService = $profile->providedServices[$service['id']] ?? new ProvidedServiceReadModel(
  1050.                 $service['id'], $service['name'], $service['group'], $service['uriIdentity'],
  1051.                 $service['condition'], $service['extra_charge'], $service['comment']
  1052.             );
  1053.             $profile->providedServices[$service['id']] = $providedService;
  1054.         }
  1055.         $profile->selfies = $row['selfies_count'] ?? 0;
  1056.         $profile->videos = $row['videos_count'] ?? 0;
  1057.         $profile->photos = $row['photos_count'] ?? 0;
  1058.         $avatar = [
  1059.             'path' => $row['avatar_path'] ?? '',
  1060.             'type' => $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO
  1061.         ];
  1062.         if ($this->features->crop_avatar()) {
  1063.             $profile->avatar = $avatar;
  1064.         } else {
  1065.             $profile->mainPhoto = $avatar;
  1066.         }
  1067.         $profile->comments = $row['comments_count'] ?? 0;
  1068.         $profile->apartmentsPricing = new ProfileApartmentPricingReadModel();
  1069.         $profile->apartmentsPricing->oneHourPrice = $row['apartments_one_hour_price'];
  1070.         $profile->apartmentsPricing->twoHoursPrice = $row['apartments_two_hours_price'];
  1071.         $profile->apartmentsPricing->nightPrice = $row['apartments_night_price'];
  1072.         $profile->takeOutPricing = new ProfileTakeOutPricingReadModel();
  1073.         $profile->takeOutPricing->oneHourPrice = $row['take_out_one_hour_price'];
  1074.         $profile->takeOutPricing->twoHoursPrice = $row['take_out_two_hours_price'];
  1075.         $profile->takeOutPricing->nightPrice = $row['take_out_night_price'];
  1076.         $profile->takeOutPricing->locations = $row['take_out_locations'] ? array_map('intval', explode(',', $row['take_out_locations'])) : [];
  1077.         $profile->seo = $row['seo'] ? json_decode($row['seo'], true) : null;
  1078.         return $profile;
  1079.     }
  1080.     public function fetchMapProfilesByIds(ProfileIdINOrderedByINValues $specification): array
  1081.     {
  1082.         $ids = implode(',', $specification->getIds());
  1083.         $mediaType = $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO;
  1084.         $mediaIsMain = $this->features->crop_avatar() ? 0 : 1;
  1085.         $sql = "
  1086.             SELECT 
  1087.                 p.id, p.uri_identity, p.map_latitude, p.map_longitude, p.phone_number, p.is_masseur, p.is_approved,
  1088.                 p.person_age, p.person_breast_size, p.person_height, p.person_weight, pap.type as placement_type, p.primary_station_id,
  1089.                 JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  1090.                     as `name`,
  1091.                 (SELECT path FROM profile_media_files pmf_avatar WHERE p.id = pmf_avatar.profile_id AND pmf_avatar.type = '{$mediaType}' AND pmf_avatar.is_main = {$mediaIsMain} LIMIT 1) 
  1092.                     as `avatar_path`,
  1093.                 p.apartments_one_hour_price, p.apartments_two_hours_price, p.apartments_night_price, p.take_out_one_hour_price, p.take_out_two_hours_price, p.take_out_night_price,
  1094.                 GROUP_CONCAT(ps.station_id) as `stations`,
  1095.                 GROUP_CONCAT(pps.service_id) as `services`,
  1096.                 EXISTS(SELECT * FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  1097.                     as `has_comments`,
  1098.                 EXISTS(SELECT * FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  1099.                     as `has_videos`,
  1100.                 EXISTS(SELECT * FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  1101.                     as `has_selfies`,
  1102.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  1103.                     as `has_top_placement`
  1104.             FROM profiles `p`
  1105.             LEFT JOIN profile_stations ps ON ps.profile_id = p.id
  1106.             LEFT JOIN profile_provided_services pps ON pps.profile_id = p.id
  1107.             LEFT JOIN profile_adboard_placements pap ON pap.profile_id = p.id
  1108.             WHERE p.id IN ($ids)
  1109.             GROUP BY p.id
  1110.             "; // AND p.map_latitude IS NOT NULL AND p.map_longitude IS NOT NULL; ORDER BY FIELD(p.id,$ids)
  1111.         $result = $this->getEntityManager()->getConnection()->executeQuery($sql);
  1112.         $profiles = $result->fetchAllAssociative();
  1113.         $result = array_map(function ($profile): ProfileMapReadModel {
  1114.             return $this->hydrateMapProfileRow($profile);
  1115.         }, $profiles);
  1116.         return $result;
  1117.     }
  1118.     public function hydrateMapProfileRow(array $row): ProfileMapReadModel
  1119.     {
  1120.         $profile = new ProfileMapReadModel();
  1121.         $profile->id = $row['id'];
  1122.         $profile->uriIdentity = $row['uri_identity'];
  1123.         $profile->name = $row['name'];
  1124.         $profile->phoneNumber = $row['phone_number'];
  1125.         $profile->avatar = ['path' => $row['avatar_path'] ?? '', 'type' => $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO];
  1126.         $profile->mapLatitude = $row['map_latitude'];
  1127.         $profile->mapLongitude = $row['map_longitude'];
  1128.         $profile->age = $row['person_age'];
  1129.         $profile->breastSize = $row['person_breast_size'];
  1130.         $profile->height = $row['person_height'];
  1131.         $profile->weight = $row['person_weight'];
  1132.         $profile->isMasseur = $row['is_masseur'];
  1133.         $profile->isApproved = $row['is_approved'];
  1134.         $profile->hasComments = $row['has_comments'];
  1135.         $profile->hasSelfies = $row['has_selfies'];
  1136.         $profile->hasVideos = $row['has_videos'];
  1137.         $profile->apartmentOneHourPrice = $row['apartments_one_hour_price'];
  1138.         $profile->apartmentTwoHoursPrice = $row['apartments_two_hours_price'];
  1139.         $profile->apartmentNightPrice = $row['apartments_night_price'];
  1140.         $profile->takeOutOneHourPrice = $row['take_out_one_hour_price'];
  1141.         $profile->takeOutTwoHoursPrice = $row['take_out_two_hours_price'];
  1142.         $profile->takeOutNightPrice = $row['take_out_night_price'];
  1143.         $profile->station = $row['primary_station_id'] ?? ($row['stations'] ? explode(',', $row['stations'])[0] : null);
  1144.         $profile->services = $row['services'] ? array_unique(explode(',', $row['services'])) : [];
  1145.         $profile->isPaid = $row['placement_type'] >= AdBoardPlacement::POSITION_GROUP_STANDARD || $row['has_top_placement'] !== null;
  1146. //        $prices = [ $row['apartments_one_hour_price'], $row['apartments_two_hours_price'], $row['apartments_night_price'],
  1147. //            $row['take_out_one_hour_price'], $row['take_out_two_hours_price'], $row['take_out_night_price'] ];
  1148. //        $prices = array_filter($prices, function($item) {
  1149. //            return $item != null;
  1150. //        });
  1151. //        $profile->price = count($prices) ? min($prices) : null;
  1152.         return $profile;
  1153.     }
  1154.     public function fetchAccountProfileListByIds(ProfileIdINOrderedByINValues $specification): array
  1155.     {
  1156.         $ids = implode(',', $specification->getIds());
  1157.         $mediaType = $this->features->crop_avatar() ? Photo::TYPE_AVATAR : Photo::TYPE_PHOTO;
  1158.         $mediaIsMain = $this->features->crop_avatar() ? 0 : 1;
  1159.         $sql = "
  1160.             SELECT 
  1161.                 p.*, JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  1162.                     as `name`, 
  1163.                 JSON_UNQUOTE(JSON_EXTRACT(p.description, '$.ru')) 
  1164.                     as `description`,
  1165.                 (SELECT path FROM profile_media_files pmf_avatar WHERE p.id = pmf_avatar.profile_id AND pmf_avatar.type = '{$mediaType}' AND pmf_avatar.is_main = {$mediaIsMain} LIMIT 1) 
  1166.                     as `avatar_path`,
  1167.                 (SELECT type FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  1168.                     as `adboard_placement_type`,
  1169.                 c.id 
  1170.                     as `city_id`, 
  1171.                 JSON_UNQUOTE(JSON_EXTRACT(c.name, '$.ru')) 
  1172.                     as `city_name`, 
  1173.                 c.uri_identity 
  1174.                     as `city_uri_identity`,
  1175.                 c.country_code 
  1176.                     as `city_country_code`,
  1177.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  1178.                     as `has_top_placement`,
  1179.                 EXISTS(SELECT * FROM placement_hidings ph WHERE p.id = ph.profile_id AND ph.entity_type = 'profile') 
  1180.                     as `has_placement_hiding`,
  1181.                 (SELECT COUNT(*) FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  1182.                     as `comments_count`,
  1183.                 (SELECT COUNT(*) FROM profile_media_files pmf_photo WHERE p.id = pmf_photo.profile_id AND pmf_photo.type = 'photo') 
  1184.                     as `photos_count`,
  1185.                 (SELECT COUNT(*) FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  1186.                     as `videos_count`,
  1187.                 (SELECT COUNT(*) FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  1188.                     as `selfies_count`,
  1189.                 p.primary_station_id 
  1190.             FROM profiles `p`
  1191.             JOIN cities `c` ON c.id = p.city_id 
  1192.             WHERE p.id IN ($ids)
  1193.             ORDER BY FIELD(p.id,$ids)";
  1194.         $connection = $this->getEntityManager()->getConnection();
  1195.         $result = $connection->executeQuery($sql);
  1196.         $profiles = $result->fetchAllAssociative();
  1197.         $sql = "SELECT 
  1198.                     JSON_UNQUOTE(JSON_EXTRACT(cs.name, '$.ru')) 
  1199.                         as `name`, 
  1200.                     cs.uri_identity 
  1201.                         as `uriIdentity`, 
  1202.                     ps.profile_id
  1203.                         as `profile_id`,
  1204.                     cs.district_id, cs.county_id
  1205.                 FROM profile_stations ps
  1206.                 JOIN city_stations cs ON ps.station_id = cs.id                 
  1207.                 WHERE ps.profile_id IN ($ids)";
  1208.         $result = $connection->executeQuery($sql);
  1209.         $stations = $result->fetchAllAssociative();
  1210.         $districtIds = array_unique(array_column($stations, 'district_id'));
  1211.         $districts = $this->districts->ofIds($districtIds);
  1212.         $sql = "SELECT 
  1213.                     s.id 
  1214.                         as `id`,
  1215.                     JSON_UNQUOTE(JSON_EXTRACT(s.name, '$.ru')) 
  1216.                         as `name`, 
  1217.                     s.group 
  1218.                         as `group`, 
  1219.                     s.uri_identity 
  1220.                         as `uriIdentity`,
  1221.                     pps.profile_id
  1222.                         as `profile_id`,
  1223.                     pps.service_condition
  1224.                         as `condition`,
  1225.                     pps.extra_charge
  1226.                         as `extra_charge`,
  1227.                     pps.comment
  1228.                         as `comment`
  1229.                 FROM profile_provided_services pps
  1230.                 JOIN services s ON pps.service_id = s.id 
  1231.                 WHERE pps.profile_id IN ($ids)
  1232.                 ORDER BY s.group ASC, s.sort ASC, s.id ASC";
  1233.         $result = $connection->executeQuery($sql);
  1234.         $providedServices = $result->fetchAllAssociative();
  1235.         $profileNameUris = $this->fetchCanonicalNameUris($ids);
  1236.         $result = array_map(function ($profile) use ($stations, $districts, $providedServices, $profileNameUris): ProfileListingReadModel {
  1237.             return $this->hydrateProfileRow2($profile, $stations, $districts, $providedServices, $profileNameUris);
  1238.         }, $profiles);
  1239.         return $result;
  1240.     }
  1241.     private function fetchCanonicalNameUris(string $ids): array
  1242.     {
  1243.         $rows = $this->getEntityManager()->getConnection()->fetchAllAssociative(
  1244.             "SELECT ppn.profile_id, pn.uri_identity
  1245.              FROM profile_profile_names ppn
  1246.              JOIN profile_names pn ON pn.id = ppn.profile_name_id
  1247.              WHERE ppn.profile_id IN ($ids)
  1248.              ORDER BY pn.canonical_name ASC"
  1249.         );
  1250.         $result = [];
  1251.         foreach ($rows as $row) {
  1252.             $profileId = (int)$row['profile_id'];
  1253.             $result[$profileId] ??= [];
  1254.             $result[$profileId][] = $row['uri_identity'];
  1255.         }
  1256.         return $result;
  1257.     }
  1258.     public function getCommentedProfilesPaged(User $owner): ORMQueryResult
  1259.     {
  1260.         $qb = $this->createQueryBuilder('profile')
  1261.             ->join('profile.comments', 'comment')
  1262.             ->andWhere('profile.owner = :owner')
  1263.             ->setParameter('owner', $owner)
  1264.             ->orderBy('comment.createdAt', 'DESC');
  1265.         return new ORMQueryResult($qb);
  1266.     }
  1267.     /**
  1268.      * @return ProfilePlacementPriceDetailReadModel[]
  1269.      */
  1270.     public function fetchOfOwnerPlacedPriceDetails(User $owner): array
  1271.     {
  1272.         $sql = "
  1273.             SELECT 
  1274.                 p.id, p.is_approved, psp.price_amount
  1275.             FROM profiles `p`
  1276.             JOIN profile_adboard_placements pap ON pap.profile_id = p.id AND pap.placement_price_id IS NOT NULL
  1277.             JOIN paid_service_prices psp ON pap.placement_price_id = psp.id
  1278.             WHERE p.user_id = {$owner->getId()}
  1279.         ";
  1280.         $result = $this->getEntityManager()->getConnection()->executeQuery($sql);
  1281.         $profiles = $result->fetchAllAssociative();
  1282.         return array_map(function (array $row): ProfilePlacementPriceDetailReadModel {
  1283.             return new ProfilePlacementPriceDetailReadModel(
  1284.                 $row['id'], $row['is_approved'], $row['price_amount'] / 24
  1285.             );
  1286.         }, $profiles);
  1287.     }
  1288.     /**
  1289.      * @return ProfilePlacementHidingDetailReadModel[]
  1290.      */
  1291.     public function fetchOfOwnerHiddenDetails(User $owner): array
  1292.     {
  1293.         $sql = "
  1294.             SELECT 
  1295.                 p.id, p.is_approved
  1296.             FROM profiles `p`
  1297.             JOIN placement_hidings ph ON ph.profile_id = p.id
  1298.             WHERE p.user_id = {$owner->getId()}
  1299.         ";
  1300.         $result = $this->getEntityManager()->getConnection()->executeQuery($sql);
  1301.         $profiles = $result->fetchAllAssociative();
  1302.         return array_map(function (array $row): ProfilePlacementHidingDetailReadModel {
  1303.             return new ProfilePlacementHidingDetailReadModel(
  1304.                 $row['id'], $row['is_approved'], true
  1305.             );
  1306.         }, $profiles);
  1307.     }
  1308.     protected function modifyListingQueryBuilder(QueryBuilder $qb, string $alias): void
  1309.     {
  1310.         $qb
  1311.             ->addSelect('city')
  1312.             ->addSelect('station')
  1313.             ->addSelect('photo')
  1314.             ->addSelect('video')
  1315.             ->addSelect('comment')
  1316.             ->addSelect('avatar')
  1317.             ->join(sprintf('%s.city', $alias), 'city');
  1318.         if (!in_array('station', $qb->getAllAliases()))
  1319.             $qb->leftJoin(sprintf('%s.stations', $alias), 'station');
  1320.         if (!in_array('photo', $qb->getAllAliases()))
  1321.             $qb->leftJoin(sprintf('%s.photos', $alias), 'photo');
  1322.         if (!in_array('video', $qb->getAllAliases()))
  1323.             $qb->leftJoin(sprintf('%s.videos', $alias), 'video');
  1324.         if (!in_array('avatar', $qb->getAllAliases()))
  1325.             $qb->leftJoin(sprintf('%s.avatar', $alias), 'avatar');
  1326.         if (!in_array('comment', $qb->getAllAliases()))
  1327.             $qb->leftJoin(sprintf('%s.comments', $alias), 'comment');
  1328.         $this->addFemaleGenderFilterToQb($qb, $alias);
  1329.         //TODO убрать, если все ок
  1330.         //$this->excludeHavingPlacementHiding($qb, $alias);
  1331.         if (!in_array('profile_adboard_placement', $qb->getAllAliases())) {
  1332.             $qb
  1333.                 ->leftJoin(sprintf('%s.adBoardPlacement', $alias), 'profile_adboard_placement');
  1334.         }
  1335.         $qb->addSelect('profile_adboard_placement');
  1336.         if (!in_array('profile_top_placement', $qb->getAllAliases())) {
  1337.             $qb
  1338.                 ->leftJoin(sprintf('%s.topPlacements', $alias), 'profile_top_placement');
  1339.         }
  1340.         $qb->addSelect('profile_top_placement');
  1341.         //if($this->features->free_profiles()) {
  1342.         if (!in_array('placement_hiding', $qb->getAllAliases())) {
  1343.             $qb
  1344.                 ->leftJoin(sprintf('%s.placementHiding', $alias), 'placement_hiding');
  1345.         }
  1346.         $qb->addSelect('placement_hiding');
  1347.         //}
  1348.     }
  1349.     protected function addActiveFilterToQb(QueryBuilder $qb, string $dqlAlias)
  1350.     {
  1351.         if (!in_array('profile_adboard_placement', $qb->getAllAliases())) {
  1352.             $qb
  1353.                 ->join(sprintf('%s.adBoardPlacement', $dqlAlias), 'profile_adboard_placement');
  1354.         }
  1355.     }
  1356.     private function excludeHavingPlacementHiding(QueryBuilder $qb, $alias): void
  1357.     {
  1358.         if ($this->features->free_profiles()) {
  1359. //            if (!in_array('placement_hiding', $qb->getAllAliases())) {
  1360. //                $qb
  1361. //                    ->leftJoin(sprintf('%s.placementHiding', $alias), 'placement_hiding')
  1362. //                    ->andWhere(sprintf('placement_hiding IS NULL'))
  1363. //                ;
  1364. //        }
  1365.             $sub = new QueryBuilder($qb->getEntityManager());
  1366.             $sub->select("exclude_hidden_placement_hiding");
  1367.             $sub->from($qb->getEntityManager()->getClassMetadata(PlacementHiding::class)->name, "exclude_hidden_placement_hiding");
  1368.             $sub->andWhere(sprintf('exclude_hidden_placement_hiding.profile = %s', $alias));
  1369.             $qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
  1370.         }
  1371.     }
  1372. }