src/Service/NearestProfiles.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Profile\Profile;
  4. use App\Repository\ProfileRepository;
  5. use App\Specification\ElasticSearch\ISpecification;
  6. use App\Specification\Profile\ProfileIdINOrderedByINValues;
  7. use App\Specification\Profile\ProfileIdNotIn;
  8. use App\Specification\Profile\ProfileIsLocated;
  9. use App\Specification\QueryModifier\ProfileOrderedByDistanceFromCoordinate;
  10. use Happyr\DoctrineSpecification\Logic\AndX;
  11. use Happyr\DoctrineSpecification\Query\QueryModifier;
  12. class NearestProfiles
  13. {
  14.     private array $result = [];
  15.     private int $limit 0;
  16.     private Profile $profile;
  17.     public function __construct(
  18.         private ProfileRepository $profileRepository,
  19.         private ProfileList $profileList,
  20.     ) {}
  21.     public function getNearestProfiles(Profile $profileint $limit): array
  22.     {
  23.         $this->profile $profile;
  24.         $this->limit $limit;
  25.         if(null !== $profile->getMapCoordinate()->getLatitude() && null !== $profile->getMapCoordinate()->getLongitude()) {
  26.             $spec = new ProfileOrderedByDistanceFromCoordinate($profile->getMapCoordinate());
  27.             $this->fetch($spec);
  28.         }
  29. //        $spec = new ProfileIsLocated(null, null, null, [$profile->getStations()->first()]);
  30. //        $this->fetch($spec);
  31.         $spec = new ProfileIsLocated(nullnullnull, [$profile->getStations()->toArray()]);
  32.         $this->fetch($spec);
  33.         $spec = new ProfileIsLocated($profile->getCity(), nullnullnull);
  34.         $this->fetch($spec);
  35.         return count($this->result) ? $this->profileRepository->fetchListingByIds(new ProfileIdINOrderedByINValues($this->result)) : [];
  36.     }
  37.     private function fetch(ISpecification|QueryModifier $spec)
  38.     {
  39.         if(count($this->result) >= $this->limit) {
  40.             return;
  41.         }
  42.         $spec = new AndX(
  43.             $spec,
  44.             new ProfileIdNotIn(array_merge([$this->profile->getId()], $this->result)),
  45.             $this->profileList->getModerationSpecByFlag(),
  46.             $this->profileList->getActiveSpecByFlag(true),
  47.         );
  48.         $profileIds $this->profileRepository->listIdMatchingSpec($spec0$this->limit count($this->result));
  49.         $this->result array_merge($this->result$profileIds);
  50.     }
  51. }