src/Repository/ProfileRepository.php line 1019

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