src/Repository/ProfileRepository.php line 986

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