src/Repository/ProfileRepository.php line 1026

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