src/Repository/ProfileRepository.php line 735

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.             ->leftJoin('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 new ORMQueryResult($qb);
  263.     }
  264.     public function countFreeUnapprovedLimited(): int
  265.     {
  266.         $qb $this->createQueryBuilder('profile')
  267.             ->select('count(profile)')
  268.             ->join('profile.adBoardPlacement''placement')
  269.             ->andWhere('placement.type = :placement_type')
  270.             ->setParameter('placement_type'AdBoardPlacementType::FREE)
  271.             ->leftJoin('profile.placementHiding''hiding')
  272.             ->andWhere('hiding IS NULL')
  273.             ->andWhere('profile.approved = false');
  274.         return (int)$qb->getQuery()->getSingleScalarResult();
  275.     }
  276.     public function iterateFreeUnapprovedLimited(int $limit): iterable
  277.     {
  278.         $qb $this->createQueryBuilder('profile')
  279.             ->join('profile.adBoardPlacement''placement')
  280.             ->andWhere('placement.type = :placement_type')
  281.             ->setParameter('placement_type'AdBoardPlacementType::FREE)
  282.             ->leftJoin('profile.placementHiding''hiding')
  283.             ->andWhere('hiding IS NULL')
  284.             ->andWhere('profile.approved = false')
  285.             ->setMaxResults($limit);
  286.         return $this->iterateQueryBuilder($qb);
  287.     }
  288.     /**
  289.      * Число активных анкет, привязанных к аккаунту
  290.      */
  291.     public function countActiveOfOwner(User $owner, ?bool $isMasseur false): int
  292.     {
  293.         $qb $this->createQueryBuilder('profile')
  294.             ->select('COUNT(profile.id)')
  295.             ->join('profile.adBoardPlacement''profile_adboard_placement')
  296.             ->andWhere('profile.owner = :owner')
  297.             ->setParameter('owner'$owner);
  298.         if ($this->features->hard_moderation()) {
  299.             $qb->leftJoin('profile.owner''owner');
  300.             $qb->andWhere(
  301.                 $qb->expr()->orX(
  302.                     'profile.moderationStatus = :status_passed',
  303.                     $qb->expr()->andX(
  304.                         'profile.moderationStatus = :status_waiting',
  305.                         'owner.trusted = true'
  306.                     )
  307.                 )
  308.             );
  309.             $qb->setParameter('status_passed'Profile::MODERATION_STATUS_APPROVED);
  310.             $qb->setParameter('status_waiting'Profile::MODERATION_STATUS_WAITING);
  311.         } else {
  312.             $qb->andWhere('profile.moderationStatus IN (:statuses)')
  313.                 ->setParameter('statuses', [Profile::MODERATION_STATUS_NOT_PASSEDProfile::MODERATION_STATUS_WAITINGProfile::MODERATION_STATUS_APPROVED]);
  314.         }
  315.         if (null !== $isMasseur) {
  316.             $qb->andWhere('profile.masseur = :is_masseur')
  317.                 ->setParameter('is_masseur'$isMasseur);
  318.         }
  319.         return (int)$qb->getQuery()->getSingleScalarResult();
  320.     }
  321.     /**
  322.      * Число всех анкет, привязанных к аккаунту
  323.      */
  324.     public function countAllOfOwnerNotDeleted(User $owner, ?bool $isMasseur false): int
  325.     {
  326.         $qb $this->createQueryBuilder('profile')
  327.             ->select('COUNT(profile.id)')
  328.             ->andWhere('profile.owner = :owner')
  329.             ->setParameter('owner'$owner)
  330.             //потому что используется в т.ч. на тех страницах, где отключен фильтр вывода "только неудаленных"
  331.             ->andWhere('profile.deletedAt IS NULL');
  332.         if (null !== $isMasseur) {
  333.             $qb->andWhere('profile.masseur = :is_masseur')
  334.                 ->setParameter('is_masseur'$isMasseur);
  335.         }
  336.         return (int)$qb->getQuery()->getSingleScalarResult();
  337.     }
  338.     public function getTimezonesListByUser(User $owner): array
  339.     {
  340.         $q $this->_em->createQuery(sprintf("
  341.                 SELECT c
  342.                 FROM %s c
  343.                 WHERE c.id IN (
  344.                     SELECT DISTINCT(c2.id) 
  345.                     FROM %s p
  346.                     JOIN p.city c2
  347.                     WHERE p.owner = :user
  348.                 )
  349.             "$this->_em->getClassMetadata(City::class)->name$this->_em->getClassMetadata(Profile::class)->name))
  350.             ->setParameter('user'$owner);
  351.         return $q->getResult();
  352.     }
  353.     /**
  354.      * Список анкет, привязанных к аккаунту
  355.      *
  356.      * @return Profile[]
  357.      */
  358.     public function ofOwner(User $owner): array
  359.     {
  360.         $qb $this->createQueryBuilder('profile')
  361.             ->andWhere('profile.owner = :owner')
  362.             ->setParameter('owner'$owner);
  363.         return $qb->getQuery()->getResult();
  364.     }
  365.     public function ofOwnerPaged(User $owner, array $genders = [Genders::FEMALE]): ORMQueryResult
  366.     {
  367.         $qb $this->createQueryBuilder('profile')
  368.             ->andWhere('profile.owner = :owner')
  369.             ->setParameter('owner'$owner)
  370.             ->andWhere('profile.personParameters.gender IN (:genders)')
  371.             ->setParameter('genders'$genders);
  372.         return new ORMQueryResult($qb);
  373.     }
  374.     public function ofOwnerAndMasseurTypeWithPlacementFilterAndNameFilterIterateAll(User $ownerstring $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur null): \Generator
  375.     {
  376.         $query $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner$placementTypeFilter$nameFilter$isMasseur)->getQuery();
  377.         foreach ($query->iterate() as $row) {
  378.             yield $row[0];
  379.         }
  380.     }
  381.     private function queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $ownerstring $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur null): QueryBuilder
  382.     {
  383.         $qb $this->createQueryBuilder('profile')
  384.             ->andWhere('profile.owner = :owner')
  385.             ->setParameter('owner'$owner);
  386.         switch ($placementTypeFilter) {
  387.             case 'paid':
  388.                 $qb->join('profile.adBoardPlacement''placement')
  389.                     ->andWhere('placement.type != :placement_type')
  390.                     ->setParameter('placement_type'AdBoardPlacementType::FREE);
  391.                 break;
  392.             case 'free':
  393.                 $qb->join('profile.adBoardPlacement''placement')
  394.                     ->andWhere('placement.type = :placement_type')
  395.                     ->setParameter('placement_type'AdBoardPlacementType::FREE);
  396.                 break;
  397.             case 'ultra-vip':
  398.                 $qb->join('profile.adBoardPlacement''placement')
  399.                     ->andWhere('placement.type = :placement_type')
  400.                     ->setParameter('placement_type'AdBoardPlacementType::ULTRA_VIP);
  401.                 break;
  402.             case 'vip':
  403.                 $qb->join('profile.adBoardPlacement''placement')
  404.                     ->andWhere('placement.type = :placement_type')
  405.                     ->setParameter('placement_type'AdBoardPlacementType::VIP);
  406.                 break;
  407.             case 'standard':
  408.                 $qb->join('profile.adBoardPlacement''placement')
  409.                     ->andWhere('placement.type = :placement_type')
  410.                     ->setParameter('placement_type'AdBoardPlacementType::STANDARD);
  411.                 break;
  412.             case 'hidden':
  413.                 $qb->join('profile.placementHiding''placement_hiding');
  414.                 break;
  415.             case 'all':
  416.             default:
  417.                 break;
  418.         }
  419.         if ($nameFilter) {
  420.             $nameExpr $qb->expr()->orX(
  421.                 'LOWER(JSON_UNQUOTE(JSON_EXTRACT(profile.name, :jsonPath))) LIKE :name_filter',
  422.                 \sprintf("REGEXP_REPLACE(profile.phoneNumber, '-| ', '') LIKE :name_filter"),
  423.                 'LOWER(profile.phoneNumber) LIKE :name_filter',
  424.                 \sprintf("REGEXP_REPLACE(profile.phoneNumber, '\+7', '8') LIKE :name_filter"),
  425.             );
  426.             $qb->setParameter('jsonPath''$.ru');
  427.             $qb->setParameter('name_filter''%' addcslashes(mb_strtolower(str_replace(['('')'' ''-'], ''$nameFilter)), '%_') . '%');
  428.             $qb->andWhere($nameExpr);
  429.         }
  430.         if (null !== $isMasseur) {
  431.             $qb->andWhere('profile.masseur = :is_masseur')
  432.                 ->setParameter('is_masseur'$isMasseur);
  433.         }
  434.         return $qb;
  435.     }
  436.     public function ofOwnerAndMasseurTypeWithPlacementFilterAndNameFilterPaged(User $ownerstring $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur null): ORMQueryResult
  437.     {
  438.         $qb $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner$placementTypeFilter$nameFilter$isMasseur);
  439.         //сортируем анкеты по статусу UltraVip->Vip->Standard->Free->Hidden
  440.         $aliases $qb->getAllAliases();
  441.         if (false == in_array('placement'$aliases))
  442.             $qb->leftJoin('profile.adBoardPlacement''placement');
  443.         if (false == in_array('placement_hiding'$aliases))
  444.             $qb->leftJoin('profile.placementHiding''placement_hiding');
  445.         $qb->addSelect('IF(placement_hiding.id IS NULL, 0, 1) as HIDDEN is_hidden');
  446.         $qb->addOrderBy('placement.type''DESC');
  447.         $qb->addOrderBy('placement.placedAt''DESC');
  448.         $qb->addOrderBy('is_hidden''ASC');
  449.         return new ORMQueryResult($qb);
  450.     }
  451.     public function idsOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $ownerstring $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur null): array
  452.     {
  453.         $qb $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner$placementTypeFilter$nameFilter$isMasseur);
  454.         $qb->select('profile.id');
  455.         return $qb->getQuery()->getResult('column_hydrator');
  456.     }
  457.     public function countOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter(User $ownerstring $placementTypeFilter, ?string $nameFilter, ?bool $isMasseur null): int
  458.     {
  459.         $qb $this->queryBuilderOfOwnerAndMasseurTypeWithPlacementFilterAndNameFilter($owner$placementTypeFilter$nameFilter$isMasseur);
  460.         $qb->select('count(profile.id)')
  461.             ->setMaxResults(1);
  462.         return (int)$qb->getQuery()->getSingleScalarResult();
  463.     }
  464.     /**
  465.      * @deprecated
  466.      */
  467.     public function hydrateProfileRow(array $row): ProfileListingReadModel
  468.     {
  469.         $profile = new ProfileListingReadModel();
  470.         $profile->id $row['id'];
  471.         $profile->city $row['city'];
  472.         $profile->uriIdentity $row['uriIdentity'];
  473.         $profile->name $row['name'];
  474.         $profile->description $row['description'];
  475.         $profile->phoneNumber $row['phoneNumber'];
  476.         $profile->approved $row['approved'];
  477.         $now = new \DateTimeImmutable('now');
  478.         $hasRunningTopPlacement false;
  479.         foreach ($row['topPlacements'] as $topPlacement) {
  480.             if ($topPlacement['placedAt'] <= $now && $now <= $topPlacement['expiresAt'])
  481.                 $hasRunningTopPlacement true;
  482.         }
  483.         $profile->active null !== $row['adBoardPlacement'] || $hasRunningTopPlacement;
  484.         $profile->hidden null != $row['placementHiding'];
  485.         $profile->personParameters = new ProfilePersonParametersReadModel();
  486.         $profile->personParameters->age $row['personParameters.age'];
  487.         $profile->personParameters->height $row['personParameters.height'];
  488.         $profile->personParameters->weight $row['personParameters.weight'];
  489.         $profile->personParameters->breastSize $row['personParameters.breastSize'];
  490.         $profile->personParameters->bodyType $row['personParameters.bodyType'];
  491.         $profile->personParameters->hairColor $row['personParameters.hairColor'];
  492.         $profile->personParameters->privateHaircut $row['personParameters.privateHaircut'];
  493.         $profile->personParameters->nationality $row['personParameters.nationality'];
  494.         $profile->personParameters->hasTattoo $row['personParameters.hasTattoo'];
  495.         $profile->personParameters->hasPiercing $row['personParameters.hasPiercing'];
  496.         $profile->stations $row['stations'];
  497.         $profile->avatar $row['avatar'];
  498.         foreach ($row['photos'] as $photo)
  499.             if ($photo['main'])
  500.                 $profile->mainPhoto $photo;
  501.         $profile->mainPhoto null;
  502.         $profile->photos = [];
  503.         $profile->selfies = [];
  504.         foreach ($row['photos'] as $photo) {
  505.             if ($photo['main'])
  506.                 $profile->mainPhoto $photo;
  507.             if ($photo['type'] == Photo::TYPE_PHOTO)
  508.                 $profile->photos[] = $photo;
  509.             if ($photo['type'] == Photo::TYPE_SELFIE)
  510.                 $profile->selfies[] = $photo;
  511.         }
  512.         $profile->videos $row['videos'];
  513.         $profile->comments $row['comments'];
  514.         $profile->apartmentsPricing = new ProfileApartmentPricingReadModel();
  515.         $profile->apartmentsPricing->oneHourPrice $row['apartmentsPricing.oneHourPrice'];
  516.         $profile->apartmentsPricing->twoHoursPrice $row['apartmentsPricing.twoHoursPrice'];
  517.         $profile->apartmentsPricing->nightPrice $row['apartmentsPricing.nightPrice'];
  518.         $profile->takeOutPricing = new ProfileTakeOutPricingReadModel();
  519.         $profile->takeOutPricing->oneHourPrice $row['takeOutPricing.oneHourPrice'];
  520.         $profile->takeOutPricing->twoHoursPrice $row['takeOutPricing.twoHoursPrice'];
  521.         $profile->takeOutPricing->nightPrice $row['takeOutPricing.nightPrice'];
  522.         return $profile;
  523.     }
  524.     public function deletedByPeriod(\DateTimeInterface $start\DateTimeInterface $end): array
  525.     {
  526.         $qb $this->createQueryBuilder('profile')
  527.             ->join('profile.city''city')
  528.             ->select('profile.uriIdentity _profile')
  529.             ->addSelect('city.uriIdentity _city')
  530.             ->andWhere('profile.deletedAt >= :start')
  531.             ->andWhere('profile.deletedAt <= :end')
  532.             ->setParameter('start'$start)
  533.             ->setParameter('end'$end);
  534.         return $qb->getQuery()->getResult();
  535.     }
  536.     public function listForMapMatchingSpec(Filter|QueryModifier $specificationint $coordinatesRoundPrecision 3): array
  537.     {
  538.         $this->getEntityManager()->getConnection()->executeQuery("
  539.             SET SESSION group_concat_max_len = 100000;
  540.         ");
  541.         /** @var QueryBuilder $qb */
  542.         $qb $this->createQueryBuilder($dqlAlias 'p');
  543.         $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));
  544.         $qb->groupBy('coords');
  545.         $specification->modify($qb$dqlAlias);
  546.         $qb->andWhere($specification->getFilter($qb$dqlAlias));
  547.         return $qb->getQuery()->getResult();
  548.     }
  549.     public function fetchListingByIds(ProfileIdINOrderedByINValues $specification): array
  550.     {
  551.         $ids implode(','$specification->getIds());
  552.         $mediaType $this->features->crop_avatar() ? Photo::TYPE_AVATAR Photo::TYPE_PHOTO;
  553.         $mediaIsMain $this->features->crop_avatar() ? 1;
  554.         $sql "
  555.             SELECT 
  556.                 p.*, JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  557.                     as `name`, 
  558.                 JSON_UNQUOTE(JSON_EXTRACT(p.description, '$.ru')) 
  559.                     as `description`,
  560.                 (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) 
  561.                     as `avatar_path`,
  562.                 (SELECT type FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  563.                     as `adboard_placement_type`,
  564.                 (SELECT position FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  565.                     as `adboard_placement_position`,
  566.                 c.id 
  567.                     as `city_id`, 
  568.                 JSON_UNQUOTE(JSON_EXTRACT(c.name, '$.ru')) 
  569.                     as `city_name`, 
  570.                 c.uri_identity 
  571.                     as `city_uri_identity`,
  572.                 c.country_code 
  573.                     as `city_country_code`,
  574.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  575.                     as `has_top_placement`,
  576.                 EXISTS(SELECT * FROM placement_hidings ph WHERE p.id = ph.profile_id AND ph.entity_type = 'profile') 
  577.                     as `has_placement_hiding`,
  578.                 EXISTS(SELECT * FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  579.                     as `has_comments`,
  580.                 EXISTS(SELECT * FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  581.                     as `has_videos`,
  582.                 EXISTS(SELECT * FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  583.                     as `has_selfies`
  584.             FROM profiles `p`
  585.             JOIN cities `c` ON c.id = p.city_id 
  586.             WHERE p.id IN ($ids)
  587.             ORDER BY FIELD(p.id,$ids)";
  588.         $connection $this->getEntityManager()->getConnection();
  589.         $result $connection->executeQuery($sql);
  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.         $result $connection->executeQuery($sql);
  610.         $stations $result->fetchAllAssociative();
  611.         $sql "SELECT 
  612.                     s.id 
  613.                         as `id`,
  614.                     JSON_UNQUOTE(JSON_EXTRACT(s.name, '$.ru')) 
  615.                         as `name`, 
  616.                     s.group 
  617.                         as `group`, 
  618.                     s.uri_identity 
  619.                         as `uriIdentity`,
  620.                     pps.profile_id
  621.                         as `profile_id`,
  622.                     pps.service_condition
  623.                         as `condition`,
  624.                     pps.extra_charge
  625.                         as `extra_charge`,
  626.                     pps.comment
  627.                         as `comment`
  628.                 FROM profile_provided_services pps
  629.                 JOIN services s ON pps.service_id = s.id 
  630.                 WHERE pps.profile_id IN ($ids)
  631.                 ORDER BY s.group ASC, s.sort ASC, s.id ASC";
  632.         $result $connection->executeQuery($sql);
  633.         $providedServices $result->fetchAllAssociative();
  634.         $result array_map(function ($profile) use ($stations$providedServices): ProfileListingReadModel {
  635.             return $this->hydrateProfileRow2($profile$stations$providedServices);
  636.         }, $profiles);
  637.         return $result;
  638.     }
  639.     public function hydrateProfileRow2(array $row, array $stations, array $services): ProfileListingReadModel
  640.     {
  641.         $profile = new ProfileListingReadModel();
  642.         $profile->id $row['id'];
  643.         $profile->moderationStatus $row['moderation_status'];
  644.         $profile->city = new CityReadModel();
  645.         $profile->city->id $row['city_id'];
  646.         $profile->city->name $row['city_name'];
  647.         $profile->city->uriIdentity $row['city_uri_identity'];
  648.         $profile->city->countryCode $row['city_country_code'];
  649.         $profile->uriIdentity $row['uri_identity'];
  650.         $profile->name $row['name'];
  651.         $profile->description $row['description'];
  652.         $profile->phoneNumber $row['phone_number'];
  653.         $profile->approved = (bool)$row['is_approved'];
  654.         $profile->isUltraVip $row['adboard_placement_type'] == AdBoardPlacement::POSITION_GROUP_ULTRA_VIP;
  655.         $profile->isVip $row['adboard_placement_type'] == AdBoardPlacement::POSITION_GROUP_VIP;
  656.         $profile->isStandard false !== array_search(
  657.                 $row['adboard_placement_type'],
  658.                 [
  659.                     AdBoardPlacement::POSITION_GROUP_STANDARD_APPROVEDAdBoardPlacement::POSITION_GROUP_STANDARD,
  660.                     AdBoardPlacement::POSITION_GROUP_WITHOUT_OWNER_APPROVEDAdBoardPlacement::POSITION_GROUP_WITHOUT_OWNER
  661.                 ]
  662.             );
  663.         $profile->position $row['adboard_placement_position'];
  664.         $profile->active null !== $row['adboard_placement_type'] || $row['has_top_placement'];
  665.         $profile->hidden $row['has_placement_hiding'] == true;
  666.         $profile->personParameters = new ProfilePersonParametersReadModel();
  667.         $profile->personParameters->age $row['person_age'];
  668.         $profile->personParameters->height $row['person_height'];
  669.         $profile->personParameters->weight $row['person_weight'];
  670.         $profile->personParameters->breastSize $row['person_breast_size'];
  671.         $profile->personParameters->bodyType $row['person_body_type'];
  672.         $profile->personParameters->hairColor $row['person_hair_color'];
  673.         $profile->personParameters->privateHaircut $row['person_private_haircut'];
  674.         $profile->personParameters->nationality $row['person_nationality'];
  675.         $profile->personParameters->hasTattoo $row['person_has_tattoo'];
  676.         $profile->personParameters->hasPiercing $row['person_has_piercing'];
  677.         $profile->stations = [];
  678.         foreach ($stations as $station) {
  679.             if ($profile->id !== $station['profile_id'])
  680.                 continue;
  681.             $profileStation $profile->stations[$station['id']] ?? new StationReadModel($station['id'], $station['uriIdentity'], $station['name'], []);
  682.             if (null !== $station['line_name']) {
  683.                 $profileStation->lines[] = new StationLineReadModel($station['line_name'], $station['line_color']);
  684.             }
  685.             $profile->stations[$station['id']] = $profileStation;
  686.         }
  687.         $primaryId = (int)$row['primary_station_id'];
  688.         if (!empty($profile->stations)) {
  689.             uasort($profile->stations, function (StationReadModel $aStationReadModel $b) use ($primaryId) {
  690.                 $aPrimary $a->id === $primaryId;
  691.                 $bPrimary $b->id === $primaryId;
  692.                 if ($aPrimary !== $bPrimary) {
  693.                     return $aPrimary ? -1;
  694.                 }
  695.                 return strnatcasecmp($a->name$b->name);
  696.             });
  697.         }
  698.         $profile->providedServices = [];
  699.         foreach ($services as $service) {
  700.             if ($profile->id !== $service['profile_id'])
  701.                 continue;
  702.             $providedService $profile->providedServices[$service['id']] ?? new ProvidedServiceReadModel(
  703.                 $service['id'], $service['name'], $service['group'], $service['uriIdentity'],
  704.                 $service['condition'], $service['extra_charge'], $service['comment']
  705.             );
  706.             $profile->providedServices[$service['id']] = $providedService;
  707.         }
  708.         $profile->selfies $row['has_selfies'] ? [1] : [];
  709.         $profile->videos $row['has_videos'] ? [1] : [];
  710.         $avatar = [
  711.             'path' => $row['avatar_path'] ?? '',
  712.             'type' => $this->features->crop_avatar() ? Photo::TYPE_AVATAR Photo::TYPE_PHOTO
  713.         ];
  714.         if ($this->features->crop_avatar()) {
  715.             $profile->avatar $avatar;
  716.         } else {
  717.             $profile->mainPhoto $avatar;
  718.             $profile->photos = [];
  719.         }
  720.         $profile->comments $row['has_comments'] ? [1] : [];
  721.         $profile->apartmentsPricing = new ProfileApartmentPricingReadModel();
  722.         $profile->apartmentsPricing->oneHourPrice $row['apartments_one_hour_price'];
  723.         $profile->apartmentsPricing->twoHoursPrice $row['apartments_two_hours_price'];
  724.         $profile->apartmentsPricing->nightPrice $row['apartments_night_price'];
  725.         $profile->takeOutPricing = new ProfileTakeOutPricingReadModel();
  726.         $profile->takeOutPricing->oneHourPrice $row['take_out_one_hour_price'];
  727.         $profile->takeOutPricing->twoHoursPrice $row['take_out_two_hours_price'];
  728.         $profile->takeOutPricing->nightPrice $row['take_out_night_price'];
  729.         $profile->takeOutPricing->locations $row['take_out_locations'] ? array_map('intval'explode(','$row['take_out_locations'])) : [];
  730.         $profile->seo $row['seo'] ? json_decode($row['seo'], true) : null;
  731.         return $profile;
  732.     }
  733.     public function fetchMapProfilesByIds(ProfileIdINOrderedByINValues $specification): array
  734.     {
  735.         $ids implode(','$specification->getIds());
  736.         $mediaType $this->features->crop_avatar() ? Photo::TYPE_AVATAR Photo::TYPE_PHOTO;
  737.         $mediaIsMain $this->features->crop_avatar() ? 1;
  738.         $sql "
  739.             SELECT 
  740.                 p.id, p.uri_identity, p.map_latitude, p.map_longitude, p.phone_number, p.is_masseur, p.is_approved,
  741.                 p.person_age, p.person_breast_size, p.person_height, p.person_weight, pap.type as placement_type, p.primary_station_id,
  742.                 JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  743.                     as `name`,
  744.                 (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) 
  745.                     as `avatar_path`,
  746.                 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,
  747.                 GROUP_CONCAT(ps.station_id) as `stations`,
  748.                 GROUP_CONCAT(pps.service_id) as `services`,
  749.                 EXISTS(SELECT * FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  750.                     as `has_comments`,
  751.                 EXISTS(SELECT * FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  752.                     as `has_videos`,
  753.                 EXISTS(SELECT * FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  754.                     as `has_selfies`,
  755.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  756.                     as `has_top_placement`
  757.             FROM profiles `p`
  758.             LEFT JOIN profile_stations ps ON ps.profile_id = p.id
  759.             LEFT JOIN profile_provided_services pps ON pps.profile_id = p.id
  760.             LEFT JOIN profile_adboard_placements pap ON pap.profile_id = p.id
  761.             WHERE p.id IN ($ids)
  762.             GROUP BY p.id
  763.             "// AND p.map_latitude IS NOT NULL AND p.map_longitude IS NOT NULL; ORDER BY FIELD(p.id,$ids)
  764.         $result $this->getEntityManager()->getConnection()->executeQuery($sql);
  765.         $profiles $result->fetchAllAssociative();
  766.         $result array_map(function ($profile): ProfileMapReadModel {
  767.             return $this->hydrateMapProfileRow($profile);
  768.         }, $profiles);
  769.         return $result;
  770.     }
  771.     public function hydrateMapProfileRow(array $row): ProfileMapReadModel
  772.     {
  773.         $profile = new ProfileMapReadModel();
  774.         $profile->id $row['id'];
  775.         $profile->uriIdentity $row['uri_identity'];
  776.         $profile->name $row['name'];
  777.         $profile->phoneNumber $row['phone_number'];
  778.         $profile->avatar = ['path' => $row['avatar_path'] ?? '''type' => $this->features->crop_avatar() ? Photo::TYPE_AVATAR Photo::TYPE_PHOTO];
  779.         $profile->mapLatitude $row['map_latitude'];
  780.         $profile->mapLongitude $row['map_longitude'];
  781.         $profile->age $row['person_age'];
  782.         $profile->breastSize $row['person_breast_size'];
  783.         $profile->height $row['person_height'];
  784.         $profile->weight $row['person_weight'];
  785.         $profile->isMasseur $row['is_masseur'];
  786.         $profile->isApproved $row['is_approved'];
  787.         $profile->hasComments $row['has_comments'];
  788.         $profile->hasSelfies $row['has_selfies'];
  789.         $profile->hasVideos $row['has_videos'];
  790.         $profile->apartmentOneHourPrice $row['apartments_one_hour_price'];
  791.         $profile->apartmentTwoHoursPrice $row['apartments_two_hours_price'];
  792.         $profile->apartmentNightPrice $row['apartments_night_price'];
  793.         $profile->takeOutOneHourPrice $row['take_out_one_hour_price'];
  794.         $profile->takeOutTwoHoursPrice $row['take_out_two_hours_price'];
  795.         $profile->takeOutNightPrice $row['take_out_night_price'];
  796.         $profile->station $row['primary_station_id'] ?? ($row['stations'] ? explode(','$row['stations'])[0] : null);
  797.         $profile->services $row['services'] ? array_unique(explode(','$row['services'])) : [];
  798.         $profile->isPaid $row['placement_type'] >= AdBoardPlacement::POSITION_GROUP_STANDARD || $row['has_top_placement'] !== null;
  799. //        $prices = [ $row['apartments_one_hour_price'], $row['apartments_two_hours_price'], $row['apartments_night_price'],
  800. //            $row['take_out_one_hour_price'], $row['take_out_two_hours_price'], $row['take_out_night_price'] ];
  801. //        $prices = array_filter($prices, function($item) {
  802. //            return $item != null;
  803. //        });
  804. //        $profile->price = count($prices) ? min($prices) : null;
  805.         return $profile;
  806.     }
  807.     public function fetchAccountProfileListByIds(ProfileIdINOrderedByINValues $specification): array
  808.     {
  809.         $ids implode(','$specification->getIds());
  810.         $mediaType $this->features->crop_avatar() ? Photo::TYPE_AVATAR Photo::TYPE_PHOTO;
  811.         $mediaIsMain $this->features->crop_avatar() ? 1;
  812.         $sql "
  813.             SELECT 
  814.                 p.*, JSON_UNQUOTE(JSON_EXTRACT(p.name, '$.ru')) 
  815.                     as `name`, 
  816.                 JSON_UNQUOTE(JSON_EXTRACT(p.description, '$.ru')) 
  817.                     as `description`,
  818.                 (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) 
  819.                     as `avatar_path`,
  820.                 (SELECT type FROM profile_adboard_placements pap WHERE p.id = pap.profile_id LIMIT 1) 
  821.                     as `adboard_placement_type`,
  822.                 c.id 
  823.                     as `city_id`, 
  824.                 JSON_UNQUOTE(JSON_EXTRACT(c.name, '$.ru')) 
  825.                     as `city_name`, 
  826.                 c.uri_identity 
  827.                     as `city_uri_identity`,
  828.                 c.country_code 
  829.                     as `city_country_code`,
  830.                 EXISTS(SELECT * FROM profile_top_placements ptp WHERE p.id = ptp.profile_id AND (NOW() BETWEEN ptp.placed_at AND ptp.expires_at))
  831.                     as `has_top_placement`,
  832.                 EXISTS(SELECT * FROM placement_hidings ph WHERE p.id = ph.profile_id AND ph.entity_type = 'profile') 
  833.                     as `has_placement_hiding`,
  834.                 EXISTS(SELECT * FROM profile_comments pc WHERE p.id = pc.profile_id AND pc.deleted_at is NULL) 
  835.                     as `has_comments`,
  836.                 EXISTS(SELECT * FROM profile_media_files pmf_video WHERE p.id = pmf_video.profile_id AND pmf_video.type = 'video') 
  837.                     as `has_videos`,
  838.                 EXISTS(SELECT * FROM profile_media_files pmf_selfie WHERE p.id = pmf_selfie.profile_id AND pmf_selfie.type = 'selfie') 
  839.                     as `has_selfies`
  840.             FROM profiles `p`
  841.             JOIN cities `c` ON c.id = p.city_id 
  842.             WHERE p.id IN ($ids)
  843.             ORDER BY FIELD(p.id,$ids)";
  844.         $connection $this->getEntityManager()->getConnection();
  845.         $result $connection->executeQuery($sql);
  846.         $profiles $result->fetchAllAssociative();
  847.         $sql "SELECT 
  848.                     JSON_UNQUOTE(JSON_EXTRACT(cs.name, '$.ru')) 
  849.                         as `name`, 
  850.                     cs.uri_identity 
  851.                         as `uriIdentity`, 
  852.                     ps.profile_id
  853.                         as `profile_id` 
  854.                 FROM profile_stations ps
  855.                 JOIN city_stations cs ON ps.station_id = cs.id                 
  856.                 WHERE ps.profile_id IN ($ids)";
  857.         $result $connection->executeQuery($sql);
  858.         $stations $result->fetchAllAssociative();
  859.         $sql "SELECT 
  860.                     s.id 
  861.                         as `id`,
  862.                     JSON_UNQUOTE(JSON_EXTRACT(s.name, '$.ru')) 
  863.                         as `name`, 
  864.                     s.group 
  865.                         as `group`, 
  866.                     s.uri_identity 
  867.                         as `uriIdentity`,
  868.                     pps.profile_id
  869.                         as `profile_id`,
  870.                     pps.service_condition
  871.                         as `condition`,
  872.                     pps.extra_charge
  873.                         as `extra_charge`,
  874.                     pps.comment
  875.                         as `comment`
  876.                 FROM profile_provided_services pps
  877.                 JOIN services s ON pps.service_id = s.id 
  878.                 WHERE pps.profile_id IN ($ids)
  879.                 ORDER BY s.group ASC, s.sort ASC, s.id ASC";
  880.         $result $connection->executeQuery($sql);
  881.         $providedServices $result->fetchAllAssociative();
  882.         $result array_map(function ($profile) use ($stations$providedServices): ProfileListingReadModel {
  883.             return $this->hydrateProfileRow2($profile$stations$providedServices);
  884.         }, $profiles);
  885.         return $result;
  886.     }
  887.     public function getCommentedProfilesPaged(User $owner): ORMQueryResult
  888.     {
  889.         $qb $this->createQueryBuilder('profile')
  890.             ->join('profile.comments''comment')
  891.             ->andWhere('profile.owner = :owner')
  892.             ->setParameter('owner'$owner)
  893.             ->orderBy('comment.createdAt''DESC');
  894.         return new ORMQueryResult($qb);
  895.     }
  896.     /**
  897.      * @return ProfilePlacementPriceDetailReadModel[]
  898.      */
  899.     public function fetchOfOwnerPlacedPriceDetails(User $owner): array
  900.     {
  901.         $sql "
  902.             SELECT 
  903.                 p.id, p.is_approved, psp.price_amount
  904.             FROM profiles `p`
  905.             JOIN profile_adboard_placements pap ON pap.profile_id = p.id AND pap.placement_price_id IS NOT NULL
  906.             JOIN paid_service_prices psp ON pap.placement_price_id = psp.id
  907.             WHERE p.user_id = {$owner->getId()}
  908.         ";
  909.         $result $this->getEntityManager()->getConnection()->executeQuery($sql);
  910.         $profiles $result->fetchAllAssociative();
  911.         return array_map(function (array $row): ProfilePlacementPriceDetailReadModel {
  912.             return new ProfilePlacementPriceDetailReadModel(
  913.                 $row['id'], $row['is_approved'], $row['price_amount'] / 24
  914.             );
  915.         }, $profiles);
  916.     }
  917.     /**
  918.      * @return ProfilePlacementHidingDetailReadModel[]
  919.      */
  920.     public function fetchOfOwnerHiddenDetails(User $owner): array
  921.     {
  922.         $sql "
  923.             SELECT 
  924.                 p.id, p.is_approved
  925.             FROM profiles `p`
  926.             JOIN placement_hidings ph ON ph.profile_id = p.id
  927.             WHERE p.user_id = {$owner->getId()}
  928.         ";
  929.         $result $this->getEntityManager()->getConnection()->executeQuery($sql);
  930.         $profiles $result->fetchAllAssociative();
  931.         return array_map(function (array $row): ProfilePlacementHidingDetailReadModel {
  932.             return new ProfilePlacementHidingDetailReadModel(
  933.                 $row['id'], $row['is_approved'], true
  934.             );
  935.         }, $profiles);
  936.     }
  937.     protected function modifyListingQueryBuilder(QueryBuilder $qbstring $alias): void
  938.     {
  939.         $qb
  940.             ->addSelect('city')
  941.             ->addSelect('station')
  942.             ->addSelect('photo')
  943.             ->addSelect('video')
  944.             ->addSelect('comment')
  945.             ->addSelect('avatar')
  946.             ->join(sprintf('%s.city'$alias), 'city');
  947.         if (!in_array('station'$qb->getAllAliases()))
  948.             $qb->leftJoin(sprintf('%s.stations'$alias), 'station');
  949.         if (!in_array('photo'$qb->getAllAliases()))
  950.             $qb->leftJoin(sprintf('%s.photos'$alias), 'photo');
  951.         if (!in_array('video'$qb->getAllAliases()))
  952.             $qb->leftJoin(sprintf('%s.videos'$alias), 'video');
  953.         if (!in_array('avatar'$qb->getAllAliases()))
  954.             $qb->leftJoin(sprintf('%s.avatar'$alias), 'avatar');
  955.         if (!in_array('comment'$qb->getAllAliases()))
  956.             $qb->leftJoin(sprintf('%s.comments'$alias), 'comment');
  957.         $this->addFemaleGenderFilterToQb($qb$alias);
  958.         //TODO убрать, если все ок
  959.         //$this->excludeHavingPlacementHiding($qb, $alias);
  960.         if (!in_array('profile_adboard_placement'$qb->getAllAliases())) {
  961.             $qb
  962.                 ->leftJoin(sprintf('%s.adBoardPlacement'$alias), 'profile_adboard_placement');
  963.         }
  964.         $qb->addSelect('profile_adboard_placement');
  965.         if (!in_array('profile_top_placement'$qb->getAllAliases())) {
  966.             $qb
  967.                 ->leftJoin(sprintf('%s.topPlacements'$alias), 'profile_top_placement');
  968.         }
  969.         $qb->addSelect('profile_top_placement');
  970.         //if($this->features->free_profiles()) {
  971.         if (!in_array('placement_hiding'$qb->getAllAliases())) {
  972.             $qb
  973.                 ->leftJoin(sprintf('%s.placementHiding'$alias), 'placement_hiding');
  974.         }
  975.         $qb->addSelect('placement_hiding');
  976.         //}
  977.     }
  978.     protected function addActiveFilterToQb(QueryBuilder $qbstring $dqlAlias)
  979.     {
  980.         if (!in_array('profile_adboard_placement'$qb->getAllAliases())) {
  981.             $qb
  982.                 ->join(sprintf('%s.adBoardPlacement'$dqlAlias), 'profile_adboard_placement');
  983.         }
  984.     }
  985.     private function excludeHavingPlacementHiding(QueryBuilder $qb$alias): void
  986.     {
  987.         if ($this->features->free_profiles()) {
  988. //            if (!in_array('placement_hiding', $qb->getAllAliases())) {
  989. //                $qb
  990. //                    ->leftJoin(sprintf('%s.placementHiding', $alias), 'placement_hiding')
  991. //                    ->andWhere(sprintf('placement_hiding IS NULL'))
  992. //                ;
  993. //        }
  994.             $sub = new QueryBuilder($qb->getEntityManager());
  995.             $sub->select("exclude_hidden_placement_hiding");
  996.             $sub->from($qb->getEntityManager()->getClassMetadata(PlacementHiding::class)->name"exclude_hidden_placement_hiding");
  997.             $sub->andWhere(sprintf('exclude_hidden_placement_hiding.profile = %s'$alias));
  998.             $qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
  999.         }
  1000.     }
  1001. }