src/Repository/ProfileRepository.php line 1147

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