src/Repository/ProfileRepository.php line 187

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