src/Entity/Profile/Profile.php line 75

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by simpson <simpsonwork@gmail.com>
  4.  * Date: 2019-03-19
  5.  * Time: 15:36
  6.  */
  7. namespace App\Entity\Profile;
  8. use AngelGamez\TranslatableBundle\Entity\TranslatableValue;
  9. //use ApiPlatform\Core\Annotation\ApiProperty;
  10. use App\Entity\Account\Advertiser;
  11. use App\Entity\ApartmentsPricing;
  12. use App\Entity\ContainsDomainEvents;
  13. use App\Entity\Account\Customer;
  14. use App\Entity\DomainEventsRecorderTrait;
  15. use App\Entity\ExpressPricing;
  16. use App\Entity\IProvidesServices;
  17. use App\Entity\Location\City;
  18. use App\Entity\Location\MapCoordinate;
  19. use App\Entity\Location\Station;
  20. use App\Entity\Messengers;
  21. use App\Entity\PhoneCallRestrictions;
  22. use App\Entity\Profile\Comment\CommentByCustomer;
  23. use App\Entity\Profile\Confirmation\ModerationRequest;
  24. use App\Entity\Sales\Profile\AdBoardPlacement;
  25. use App\Entity\Sales\Profile\PlacementHiding;
  26. use App\Entity\Sales\Profile\TopPlacement;
  27. use App\Entity\ProvidedServiceTrait;
  28. use App\Entity\TakeOutPricing;
  29. use App\Helper\TopCardTrait;
  30. use App\Repository\ProfileRepository;
  31. use Carbon\Carbon;
  32. use Carbon\CarbonImmutable;
  33. use Doctrine\Common\Collections\ArrayCollection;
  34. use Doctrine\Common\Collections\Collection;
  35. use Doctrine\ORM\Mapping as ORM;
  36. use Doctrine\ORM\Mapping\Index;
  37. //use ApiPlatform\Core\Annotation\ApiResource;
  38. //use ApiPlatform\Core\Annotation\ApiFilter;
  39. //use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
  40. //use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\RangeFilter;
  41. use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
  42. use Symfony\Component\Serializer\Annotation\Groups;
  43. use Gedmo\Mapping\Annotation as Gedmo;
  44. use App\Validator\Constraints\ValidPhoneForCountry as ValidPhoneForCountryAssert;
  45. use App\Validator\Constraints\PhoneNotBlack as PhoneNotBlackAssert;
  46. /**
  47.  * ApiResource(collectionOperations={"get"}, itemOperations={"get"}, normalizationContext={"groups"={"profile"}}, attributes={"pagination_client_enabled"=true, "pagination_client_items_per_page"=true})
  48.  * ApiFilter(SearchFilter::class, properties={"city": "exact", "providedServices": "exact"})
  49.  * ApiFilter(RangeFilter::class, properties={"personParameters.age", "personParameters.height", "personParameters.weight", "personParameters.breastSize", "apartmentsPricing.oneHourPrice"})
  50.  * @ValidPhoneForCountryAssert/ProtocolClass
  51.  * @PhoneNotBlackAssert/ProtocolClass
  52.  */
  53. #[Gedmo\SoftDeleteable(fieldName"deletedAt"timeAwaretrue)]
  54. #[ORM\Table(name'profiles')]
  55. #[Index(name'idx_deleted_at'columns: ['deleted_at'])]
  56. #[Index(name'idx_created_at'columns: ['created_at'])]
  57. #[Index(name'idx_gender'columns: ['person_gender'])]
  58. #[Index(name'idx_apartments_one_hour_price'columns: ['apartments_one_hour_price'])]
  59. #[Index(name'idx_is_dummy'columns: ['is_dummy'])]
  60. #[Index(name'idx_city_deleted'columns: ['city_id''deleted_at'])]
  61. #[Index(name'idx_city_deleted_moderation'columns: ['city_id''deleted_at''moderation_status'])]
  62. #[Index(name'idx_city_masseur_deleted'columns: ['city_id''is_masseur''deleted_at'])]
  63. #[Index(name'idx_city_masseur_deleted_moderation'columns: ['city_id''is_masseur''deleted_at''moderation_status'])]
  64. #[Index(name'idx_city_deleted_gender'columns: ['city_id''deleted_at''person_gender'])]
  65. #[Index(name'idx_city_deleted_moderation_gender'columns: ['city_id''deleted_at''moderation_status''person_gender'])]
  66. #[Index(name'idx_city_masseur_deleted_gender'columns: ['city_id''is_masseur''deleted_at''person_gender'])]
  67. #[Index(name'idx_city_masseur_deleted_moderation_gender'columns: ['city_id''is_masseur''deleted_at''moderation_status''person_gender'])]
  68. #[ORM\Entity(repositoryClassProfileRepository::class)]
  69. #[ORM\HasLifecycleCallbacks]
  70. class Profile implements ContainsDomainEventsIProvidesServices
  71. {
  72.     use SoftDeleteableEntity;
  73.     use DomainEventsRecorderTrait;
  74.     use ProvidedServiceTrait;
  75.     use TopCardTrait;
  76.     const MODERATION_STATUS_NOT_PASSED 0;
  77.     const MODERATION_STATUS_APPROVED 1;
  78.     const MODERATION_STATUS_WAITING 2;
  79.     const MODERATION_STATUS_REJECTED 3;
  80.     #[ORM\Id]
  81.     #[ORM\Column(name'id'type'integer')]
  82.     #[ORM\GeneratedValue(strategy'AUTO')]
  83.     #[Groups(['profile''listing'])]
  84.     protected int $id;
  85.     #[ORM\JoinColumn(name'user_id'referencedColumnName'id'nullabletrue)]
  86.     #[ORM\ManyToOne(targetEntityAdvertiser::class, inversedBy'profiles')]
  87.     protected ?Advertiser $owner;
  88.     #[ORM\Column(name'is_dummy'type'boolean'options: ['default' => 0])]
  89.     protected bool $dummy false;
  90.     /** @var TopPlacement[] */
  91.     #[ORM\OneToMany(targetEntityTopPlacement::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  92.     protected Collection $topPlacements;
  93.     #[ORM\OneToOne(targetEntityAdBoardPlacement::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  94.     protected ?AdBoardPlacement $adBoardPlacement null;
  95.     #[ORM\OneToOne(targetEntityPlacementHiding::class, mappedBy'profile'cascade: ['all'])]
  96.     protected ?PlacementHiding $placementHiding null;
  97.     #[ORM\Column(name'uri_identity'type'string'length64)]
  98.     #[Groups(['profile''listing'])]
  99.     protected string $uriIdentity;
  100.     #[ORM\Column(name'name'type'translatable')]
  101.     #[Groups(['profile''listing'])]
  102.     protected TranslatableValue $name;
  103.     #[ORM\Column(name'description'type'translatable')]
  104.     #[Groups('profile')]
  105.     protected ?TranslatableValue $description null;
  106.     #[ORM\Embedded(class: PersonParameters::class, columnPrefix'person_')]
  107.     #[Groups(['profile''listing'])]
  108.     protected PersonParameters $personParameters;
  109.     /** var ProfileService[] */
  110.     #[ORM\OneToMany(targetEntityProfileService::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  111.     #[ORM\Cache(usage'NONSTRICT_READ_WRITE'region'profiles')]
  112.     #[Groups(['profile''listing'])]
  113.     protected Collection $providedServices;
  114.     /** @var int[] */
  115.     #[ORM\Column(name'client_types'type'simple_array'nullabletrue)]
  116.     #[Groups('profile')]
  117.     protected ?array $clientTypes;
  118.     #[ORM\Column(name'phone_number'type'string'length24)]
  119.     #[Groups(['profile''listing'])]
  120.     protected string $phoneNumber;
  121.     #[ORM\Embedded(class: Messengers::class, columnPrefixfalse)]
  122.     #[Groups(['profile''listing'])]
  123.     protected ?Messengers $messengers null;
  124.     #[ORM\Embedded(class: PhoneCallRestrictions::class, columnPrefixfalse)]
  125.     #[Groups('profile')]
  126.     protected ?PhoneCallRestrictions $phoneCallRestrictions null;
  127.     #[ORM\Column(name'is_masseur'type'boolean')]
  128.     #[Groups(['profile''listing'])]
  129.     protected bool $masseur false;
  130.     #[ORM\Embedded(class: ClientRestrictions::class, columnPrefixfalse)]
  131.     #[Groups('profile')]
  132.     protected ?ClientRestrictions $clientRestrictions null;
  133.     #[ORM\Embedded(class: ApartmentsPricing::class, columnPrefixfalse)]
  134.     #[Groups('profile')]
  135.     protected ?ApartmentsPricing $apartmentsPricing null;
  136.     #[ORM\Embedded(class: TakeOutPricing::class, columnPrefixfalse)]
  137.     #[Groups('profile')]
  138.     protected ?TakeOutPricing $takeOutPricing null;
  139.     #[ORM\Embedded(class: ExpressPricing::class, columnPrefixfalse)]
  140.     #[Groups('profile')]
  141.     protected ?ExpressPricing $expressPricing null;
  142.     #[ORM\Embedded(class: CarPricing::class, columnPrefixfalse)]
  143.     #[Groups('profile')]
  144.     protected ?CarPricing $carPricing null;
  145.     #[ORM\Column(name'extra_charge'type'integer'nullabletrue)]
  146.     #[Groups('profile')]
  147.     protected ?int $extraCharge;
  148.     #[ORM\Column(name'prepayment'type'boolean'nullabletrue)]
  149.     #[Groups('profile')]
  150.     protected ?bool $prepayment null;
  151.     #[ORM\Column(name'prepayment_amount'type'integer'nullabletrue)]
  152.     #[Groups('profile')]
  153.     protected ?int $prepaymentAmount null;
  154.     #[ORM\Column(name'prepayment_comment'type'string'length512nullabletrue)]
  155.     #[Groups('profile')]
  156.     protected ?string $prepaymentComment null;
  157.     /** @var Photo[] */
  158.     #[ORM\OneToMany(targetEntityPhoto::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  159.     #[Groups('profile')]
  160.     protected Collection $photos;
  161.     /** @var Selfie[] */
  162.     #[ORM\OneToMany(targetEntitySelfie::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  163.     #[Groups('profile')]
  164.     protected Collection $selfies;
  165.     /** @var Video[] */
  166.     #[ORM\OneToMany(targetEntityVideo::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  167.     #[Groups('profile')]
  168.     protected Collection $videos;
  169.     #[ORM\OneToMany(targetEntityFileProcessingTask::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  170.     protected Collection $processingFiles;
  171.     #[ORM\OneToOne(targetEntityAdminApprovalPhoto::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  172.     protected ?AdminApprovalPhoto $adminApprovalPhoto null;
  173.     #[ORM\OneToOne(targetEntityAvatar::class, mappedBy'profile'cascade: ['all'], orphanRemovaltrue)]
  174.     #[Groups(['profile''listing'])]
  175.     protected ?Avatar $avatar null;
  176.     /** @var CommentByCustomer[] */
  177.     #[ORM\OneToMany(targetEntityCommentByCustomer::class, mappedBy'profile')]
  178.     #[Groups('profile')]
  179.     protected Collection $comments;
  180.     #[ORM\Column(name'is_approved'type'boolean')]
  181.     #[Groups(['profile''listing'])]
  182.     protected bool $approved false;
  183.     #[ORM\Column(name'moderation_status'type'integer')]
  184.     #[Groups('profile')]
  185.     protected int $moderationStatus 0;
  186.     #[ORM\JoinColumn(name'city_id'referencedColumnName'id')]
  187.     #[ORM\ManyToOne(targetEntityCity::class)]
  188.     #[ORM\Cache(usage'NONSTRICT_READ_WRITE'region'profiles')]
  189.     #[Groups(['profile''listing'])]
  190.     protected City $city;
  191.     /** @var Station[] */
  192.     //, indexBy="id"
  193.     #[ORM\JoinTable(name'profile_stations')]
  194.     #[ORM\JoinColumn(name'profile_id'referencedColumnName'id')]
  195.     #[ORM\InverseJoinColumn(name'station_id'referencedColumnName'id')]
  196.     #[ORM\ManyToMany(targetEntityStation::class)]
  197.     #[Groups(['profile''listing'])]
  198.     #[ORM\Cache(usage'NONSTRICT_READ_WRITE'region'profiles')]
  199.     protected Collection $stations;
  200.     #[ORM\Embedded(class: MapCoordinate::class, columnPrefixfalse)] // ApiProperty()
  201.     #[Groups(['profile''listing'])]
  202.     protected ?MapCoordinate $mapCoordinate;
  203.     #[ORM\Column(name'created_at'type'datetimetz_immutable'nullabletrue)]
  204.     #[Groups('profile')]
  205.     protected ?\DateTimeImmutable $createdAt;
  206.     #[Gedmo\Timestampable(on"change"field: ["name""description""personParameters""providedServices""clientTypes""phoneNumber""messengers""phoneCallrestrictions""masseur""clientRestrictions""apartmentsPricing""takeOutPricing""expressPricing""carPricing""extraCharge""prepayment""prepaymentAmount""prepaymentComment""photos""selfies""videos""avatar""stations""mapCoordinate"])]
  207.     #[ORM\Column(name'updated_at'type'datetimetz_immutable'nullabletrue)]
  208.     #[Groups('profile')]
  209.     protected ?\DateTimeImmutable $updatedAt;
  210.     #[ORM\Column(name'inactivated_at'type'datetimetz_immutable'nullabletrue)]
  211.     protected ?\DateTimeImmutable $inactivatedAt;
  212.     private bool $draft false;
  213.     #[ORM\Column(name'seo'type'json'nullabletrue)]
  214.     #[Groups(['profile''listing'])]
  215.     private ?array $seo null;
  216.     #[ORM\ManyToOne(targetEntityStation::class)]
  217.     #[ORM\JoinColumn(name'primary_station_id'referencedColumnName'id'nullabletrueonDelete'SET NULL')]
  218.     #[Groups(['profile''listing'])]
  219.     #[ORM\Cache(usage'READ_ONLY')]
  220.     private ?Station $primaryStation null;
  221.     #[ORM\Column(type'smallint'options: ['default' => 0])]
  222.     private int $deleteMode 0;
  223.     protected function __construct(?\DateTimeImmutable $createdAt)
  224.     {
  225.         $this->draft true;
  226.         $this->createdAt $createdAt;
  227.         $this->photos = new ArrayCollection();
  228.         $this->selfies = new ArrayCollection();
  229.         $this->videos = new ArrayCollection();
  230.         $this->processingFiles = new ArrayCollection();
  231.         $this->comments = new ArrayCollection();
  232.         $this->topPlacements = new ArrayCollection();
  233.         $this->providedServices = new ArrayCollection();
  234.         $this->stations = new ArrayCollection();
  235.         $this->inactivatedAt CarbonImmutable::now();
  236.     }
  237.     public static function draft(?\DateTimeImmutable $createdAt null, ?bool $dummy null): self
  238.     {
  239.         $profile = new static($createdAt);
  240.         if (null !== $dummy)
  241.             $profile->dummy $dummy;
  242.         return $profile;
  243.     }
  244.     public static function create(string $uriIdentity, ?\DateTimeImmutable $createdAt null): self
  245.     {
  246.         $profile = new static($createdAt);
  247.         $profile->defineUriIdentity($uriIdentity);
  248.         $profile->toggleMasseur(false);
  249.         return $profile;
  250.     }
  251.     public function defineUriIdentity(string $uriIdentity): void
  252.     {
  253.         if (!$this->isDraft()) {
  254.             throw new \DomainException('Profile is already created and can\'t change its URI.');
  255.         }
  256.         $this->uriIdentity $uriIdentity;
  257.         $this->draft false;
  258.     }
  259.     public function isDraft(): bool
  260.     {
  261.         return $this->draft;
  262.     }
  263.     public function toggleMasseur(bool $isMasseur): void
  264.     {
  265.         if ($this->masseur !== $isMasseur && (null !== $this->adBoardPlacement && false == $this->adBoardPlacement->getType()->isFree())) {
  266.             throw new \DomainException('Impossible to toggle profile type while it is displaying on adboard.');
  267.         }
  268.         $this->masseur $isMasseur;
  269.     }
  270.     public static function createMasseur(string $uriIdentity, ?\DateTimeImmutable $createdAt null): self
  271.     {
  272.         $profile = new static($createdAt);
  273.         $profile->defineUriIdentity($uriIdentity);
  274.         $profile->toggleMasseur(true);
  275.         return $profile;
  276.     }
  277.     public function isOwnedBy(Advertiser $account): bool
  278.     {
  279.         return $account->getId() === $this->owner->getId();
  280.     }
  281.     public function getId(): int
  282.     {
  283.         return $this->id;
  284.     }
  285.     public function setBio(TranslatableValue $nameTranslatableValue $description): void
  286.     {
  287.         $this->name $name;
  288.         $this->description $description;
  289.     }
  290.     public function setLocation(City $city$stations, ?MapCoordinate $mapCoordinate): void
  291.     {
  292.         if (!$this->isDraft() && !$this->city->equals($city)) {
  293.             throw new \DomainException('City change for a saved profile is forbidden.');
  294.         }
  295.         $this->city $city;
  296.         $this->changeStations($stations);
  297.         $this->normalizePrimaryStation();
  298.         $this->mapCoordinate $mapCoordinate;
  299.     }
  300.     protected function changeStations($stations)
  301.     {
  302.         if (null === $stations)
  303.             return;
  304.         if (false === is_array($stations) && false === is_iterable($stations))
  305.             throw new \InvalidArgumentException('Stations list should be either an array or an ArrayCollection');
  306.         $stationsArray is_iterable($stations) && !is_array($stations) ? iterator_to_array($stations) : $stations;
  307.         $stations = [];
  308.         foreach ($stationsArray as $station) {
  309.             $stations[$station->getId()] = $station;
  310.         }
  311.         $stationIds array_map(function (Station $station): int {
  312.             return $station->getId();
  313.         }, $stations);
  314.         $existingStationIds $this->stations->map(function (Station $station): int {
  315.             return $station->getId();
  316.         })->getValues();
  317.         $stationIdsToAdd array_diff($stationIds$existingStationIds);
  318.         $stationIdsToRemove array_diff($existingStationIds$stationIds);
  319.         foreach ($stationIdsToAdd as $stationId) {
  320.             $this->stations->add($stations[$stationId]);
  321.         }
  322.         foreach ($stationIdsToRemove as $stationId) {
  323.             $this->stations->remove($stationId);
  324.         }
  325.     }
  326.     public function normalizePrimaryStation(): void
  327.     {
  328.         if ($this->stations->isEmpty()) {
  329.             $this->primaryStation null;
  330.             return;
  331.         }
  332.         if ($this->primaryStation === null || !$this->stations->contains($this->primaryStation)) {
  333.             $this->primaryStation $this->stations->first();
  334.         }
  335.     }
  336.     public function setEnabledProvidedServices($services): void
  337.     {
  338.         if (null !== $services) {
  339.             if (is_array($services)) {
  340.                 $services = new ArrayCollection($services);
  341.             } elseif (!$services instanceof ArrayCollection) {
  342.                 if (is_iterable($services)) {
  343.                     $services = new ArrayCollection(iterator_to_array($services));
  344.                 } else {
  345.                     throw new \InvalidArgumentException('Services list should be either an array or an ArrayCollection');
  346.                 }
  347.             }
  348.             $this->providedServices $services;
  349.         }
  350.     }
  351.     public function setPhoneCallOptions(string $phoneNumber, ?PhoneCallRestrictions $restrictions, ?Messengers $messengers): void
  352.     {
  353.         $this->phoneNumber $phoneNumber;
  354.         $this->phoneCallRestrictions $restrictions;
  355.         $this->messengers $messengers;
  356.     }
  357.     public function setPricing(?ApartmentsPricing $apartmentsPricing, ?TakeOutPricing $takeOutPricing, ?int $extraCharge, ?ExpressPricing $expressPricing null, ?CarPricing $carPricing null): void
  358.     {
  359.         $this->apartmentsPricing $apartmentsPricing;
  360.         $this->takeOutPricing $takeOutPricing;
  361.         $this->extraCharge $extraCharge;
  362.         $this->expressPricing $expressPricing;
  363.         $this->carPricing $carPricing;
  364.     }
  365.     public function setPrepaymentOptions(?bool $prepayment, ?int $prepaymentAmount, ?string $prepaymentComment): void
  366.     {
  367.         $this->prepayment $prepayment;
  368.         if ($prepayment !== true) {
  369.             $this->prepaymentAmount null;
  370.             $this->prepaymentComment null;
  371.             return;
  372.         }
  373.         $this->prepaymentAmount $prepaymentAmount;
  374.         $this->prepaymentComment $prepaymentComment;
  375.     }
  376.     public function isApproved(): bool
  377.     {
  378.         return $this->approved;
  379.     }
  380.     public function approve(): void
  381.     {
  382.         $this->approved true;
  383.     }
  384.     public function unApprove(): void
  385.     {
  386.         $this->approved false;
  387.     }
  388.     public function getOwner(): ?Advertiser
  389.     {
  390.         return $this->owner;
  391.     }
  392.     public function setOwner(Advertiser $owner): void
  393.     {
  394.         $this->owner $owner;
  395.     }
  396.     public function hasOwner(): bool
  397.     {
  398.         return null !== $this->owner;
  399.     }
  400.     public function getTopPlacements(): Collection
  401.     {
  402.         return $this->topPlacements;
  403.     }
  404.     public function addTopPlacement(TopPlacement $topPlacement): void
  405.     {
  406.         $this->topPlacements->add($topPlacement);
  407.     }
  408.     public function getAdBoardPlacement(): ?AdBoardPlacement
  409.     {
  410.         return $this->adBoardPlacement;
  411.     }
  412.     public function setAdBoardPlacement(AdBoardPlacement $adBoardPlacement): void
  413.     {
  414.         $this->adBoardPlacement $adBoardPlacement;
  415.     }
  416.     /**
  417.      * Анкета оплачена и выводится в общих списках на сайте
  418.      * или в ТОПе, то есть "АКТИВНА"
  419.      */
  420.     public function isActive(): bool
  421.     {
  422.         return null !== $this->adBoardPlacement || $this->hasRunningTopPlacement();
  423.     }
  424.     public function hasRunningTopPlacement(): bool
  425.     {
  426.         $now = new \DateTimeImmutable('now');
  427.         foreach ($this->topPlacements as /** @var TopPlacement $topPlacement */ $topPlacement) {
  428.             if ($topPlacement->getPlacedAt() <= $now && $now <= $topPlacement->getExpiresAt())
  429.                 return true;
  430.         }
  431.         return false;
  432.     }
  433.     public function getUriIdentity(): string
  434.     {
  435.         return $this->uriIdentity;
  436.     }
  437.     public function getName(): TranslatableValue
  438.     {
  439.         return $this->name;
  440.     }
  441.     public function getDescription(): ?TranslatableValue
  442.     {
  443.         return $this->description;
  444.     }
  445.     public function getPersonParameters(): PersonParameters
  446.     {
  447.         return $this->personParameters;
  448.     }
  449.     public function setPersonParameters(PersonParameters $personParameters): void
  450.     {
  451.         $this->personParameters $personParameters;
  452.     }
  453.     public function getPhoneNumber(): string
  454.     {
  455.         return $this->phoneNumber;
  456.     }
  457.     //TODO return type
  458.     public function getPhoneCallRestrictions(): ?PhoneCallRestrictions
  459.     {
  460.         return $this->phoneCallRestrictions;
  461.     }
  462.     public function isMasseur(): bool
  463.     {
  464.         return $this->masseur;
  465.     }
  466.     //TODO return type
  467.     public function getClientRestrictions(): ?ClientRestrictions
  468.     {
  469.         return $this->clientRestrictions;
  470.     }
  471.     //TODO return type
  472.     public function setClientRestrictions(?ClientRestrictions $restrictions): void
  473.     {
  474.         $this->clientRestrictions $restrictions;
  475.     }
  476.     //TODO return type
  477.     public function getApartmentsPricing(): ?ApartmentsPricing
  478.     {
  479.         return $this->apartmentsPricing;
  480.     }
  481.     public function getTakeOutPricing(): ?TakeOutPricing
  482.     {
  483.         return $this->takeOutPricing;
  484.     }
  485.     public function getExtraCharge(): ?int
  486.     {
  487.         return $this->extraCharge;
  488.     }
  489.     public function isPrepayment(): ?bool
  490.     {
  491.         return $this->prepayment;
  492.     }
  493.     public function isWithoutPrepayment(): bool
  494.     {
  495.         return $this->prepayment === false;
  496.     }
  497.     public function getPrepaymentAmount(): ?int
  498.     {
  499.         return $this->prepaymentAmount;
  500.     }
  501.     public function getPrepaymentComment(): ?string
  502.     {
  503.         return $this->prepaymentComment;
  504.     }
  505.     public function addPhoto(string $pathbool $isMain): Photo
  506.     {
  507.         $photos $this->getPhotos();
  508.         $found $photos->filter(function (Photo $photo) use ($path): bool {
  509.             return $path === $photo->getPath();
  510.         });
  511.         if (!$found->isEmpty())
  512.             return $found->first();
  513.         if (true === $isMain) {
  514.             $photos->forAll(function ($indexPhoto $photo): true {
  515.                 $photo->unsetMain();
  516.                 return true;
  517.             });
  518.         }
  519.         $photo = new Photo($this$path$isMain);
  520.         $this->photos->add($photo);
  521.         return $photo;
  522.     }
  523.     /**
  524.      * @return Photo[]
  525.      */
  526.     public function getPhotos(): Collection
  527.     {
  528.         return $this->photos->filter(function ($mediaFile): bool {
  529.             return get_class($mediaFile) == Photo::class;
  530.         });
  531.     }
  532.     public function removePhoto(string $path): bool
  533.     {
  534.         foreach ($this->getPhotos() as $photo) {
  535.             if ($path === $photo->getPath()) {
  536.                 $this->photos->removeElement($photo);
  537.                 return true;
  538.             }
  539.         }
  540.         return false;
  541.     }
  542.     public function getMainPhotoOrFirstPhoto(): ?Photo
  543.     {
  544.         $photos $this->getPhotos();
  545.         if ($photos->isEmpty()) {
  546.             return null;
  547.         }
  548.         $mainPhoto $this->getMainPhoto();
  549.         if (null === $mainPhoto) {
  550.             $mainPhoto $photos->first();
  551.         }
  552.         return $mainPhoto;
  553.     }
  554.     public function getMainPhoto(): ?Photo
  555.     {
  556.         $photos $this->getPhotos();
  557.         if ($photos->isEmpty()) {
  558.             return null;
  559.         }
  560.         $mainPhoto null;
  561.         $photos->forAll(function ($indexPhoto $photo) use (&$mainPhoto): bool {
  562.             if ($photo->isMain()) {
  563.                 $mainPhoto $photo;
  564.                 return false// Stop the cycle
  565.             }
  566.             return true;
  567.         });
  568.         return $mainPhoto;
  569.     }
  570.     public function changeMainPhoto(string $path): void
  571.     {
  572.         $photos $this->getPhotos();
  573.         $found $photos->filter(function (Photo $photo) use ($path): bool {
  574.             return $path === $photo->getPath();
  575.         });
  576.         if ($found->isEmpty()) {
  577.             return;
  578.         }
  579.         $mainPhoto $found->first();
  580.         $photos->forAll(function ($indexPhoto $photo): true {
  581.             $photo->unsetMain();
  582.             return true;
  583.         });
  584.         $mainPhoto->setMain();
  585.     }
  586.     public function addSelfie(string $path): Selfie
  587.     {
  588.         $found $this->getSelfies()->filter(function (Selfie $selfie) use ($path): bool {
  589.             return $path === $selfie->getPath();
  590.         });
  591.         if (!$found->isEmpty())
  592.             return $found->first();
  593.         $selfie = new Selfie($this$path);
  594.         $this->selfies->add($selfie);
  595.         return $selfie;
  596.     }
  597.     /**
  598.      * @return Selfie[]
  599.      */
  600.     public function getSelfies(): Collection
  601.     {
  602.         return $this->selfies;
  603.     }
  604.     public function removeSelfie(string $path): bool
  605.     {
  606.         foreach ($this->getSelfies() as $selfie) {
  607.             if ($path === $selfie->getPath()) {
  608.                 $this->selfies->removeElement($selfie);
  609.                 return true;
  610.             }
  611.         }
  612.         return false;
  613.     }
  614.     public function getConfirmedVideos(): Collection
  615.     {
  616.         return $this->videos->filter(function ($mediaFile): bool {
  617.             if (!$mediaFile instanceof Video) {
  618.                 return false;
  619.             }
  620.             return $mediaFile->isConfirmed();
  621.         });
  622.     }
  623.     /**
  624.      * Храним только 1 видео для анкеты
  625.      */
  626.     public function addVideo(string $videoPath, ?string $posterPath null): Video
  627.     {
  628.         $found $this->getVideos()->filter(function (Video $video) use ($videoPath): bool {
  629.             return $videoPath === $video->getPath();
  630.         });
  631.         if (!$found->isEmpty())
  632.             return $found->first();
  633.         $video = new Video($this$videoPath);
  634.         if (null !== $posterPath) {
  635.             $video->setPreviewPath($posterPath);
  636.         }
  637.         //теперь разрешаем много видео
  638.         //$this->videos->clear();
  639.         $this->videos->add($video);
  640.         return $video;
  641.     }
  642.     /**
  643.      * @return Video[]
  644.      */
  645.     public function getVideos(): Collection
  646.     {
  647.         return $this->videos->filter(function ($mediaFile): bool {
  648.             return ($mediaFile instanceof Video);
  649.         });
  650.     }
  651.     public function removeVideo(string $path): bool
  652.     {
  653.         foreach ($this->getVideos() as $video) {
  654.             if ($path === $video->getPath()) {
  655.                 $this->videos->removeElement($video);
  656.                 $this->photos->removeElement($video);
  657.                 return true;
  658.             }
  659.         }
  660.         return false;
  661.     }
  662.     /**
  663.      * Добавляет таск на обработку оригинала видео в подходящий формат
  664.      *
  665.      * @param string $path Путь к файлу оригинала относительно фс очередей
  666.      */
  667.     public function addRawVideo(string $path): FileProcessingTask
  668.     {
  669.         $file = new FileProcessingTask($this$path);
  670.         $this->processingFiles->add($file);
  671.         return $file;
  672.     }
  673.     public function hasFilesInProcess(): bool
  674.     {
  675.         return $this->videosInProcess() > 0;
  676.     }
  677.     public function videosInProcess(): int
  678.     {
  679.         $inProcess $this->processingFiles->filter(function (FileProcessingTask $task): bool {
  680.             return !$task->isCompleted();
  681.         });
  682.         return $inProcess->count();
  683.     }
  684.     public function isMediaProcessed(): bool
  685.     {
  686.         foreach ($this->videos as $video)
  687.             if (null === $video->getPreviewPath())
  688.                 return false;
  689.         return true;
  690.     }
  691.     public function getAvatar(): ?Avatar
  692.     {
  693.         return $this->avatar;
  694.     }
  695.     public function setAvatar(string $path): void
  696.     {
  697.         $this->avatar = new Avatar($this$path);
  698.     }
  699.     public function removeAvatar(): bool
  700.     {
  701.         if (null == $this->avatar)
  702.             return false;
  703.         foreach ($this->photos as $photo) {
  704.             if ($this->avatar->getPath() === $photo->getPath()) {
  705.                 $this->photos->removeElement($photo);
  706.                 break;
  707.             }
  708.         }
  709.         $this->avatar null;
  710.         return true;
  711.     }
  712.     /**
  713.      * @return CommentByCustomer[]
  714.      */
  715.     public function getComments(): Collection
  716.     {
  717.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  718.             return null == $comment->getParent();
  719.         });
  720.     }
  721.     /**
  722.      * @return CommentByCustomer[]
  723.      */
  724.     public function getCommentsOrderedByNotReplied(): array
  725.     {
  726.         $comments $this->comments->filter(function (CommentByCustomer $comment): bool {
  727.             return null == $comment->getParent();
  728.         })->toArray();
  729.         usort($comments, function (CommentByCustomer $commentACommentByCustomer $commentB): int {
  730.             if ((null == $commentA->getLastCommentByAdvertiser() && null == $commentB->getLastCommentByAdvertiser())
  731.                 || (null != $commentA->getLastCommentByAdvertiser() && null != $commentB->getLastCommentByAdvertiser())) {
  732.                 if ($commentA->getCreatedAt() == $commentB->getCreatedAt())
  733.                     return $commentA->getId() > $commentB->getId() ? -1;
  734.                 else
  735.                     return $commentA->getCreatedAt() > $commentB->getCreatedAt() ? -1;
  736.             }
  737.             if (null == $commentA->getLastCommentByAdvertiser() && null != $commentB->getLastCommentByAdvertiser())
  738.                 return -1;
  739.             else
  740.                 return 1;
  741.         });
  742.         return $comments;
  743.     }
  744.     public function getCreatedAt(): ?\DateTimeImmutable
  745.     {
  746.         return $this->createdAt;
  747.     }
  748.     /**
  749.      * @return CommentByCustomer[]
  750.      */
  751.     public function getCommentsWithoutReply(): Collection
  752.     {
  753.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  754.             return null == $comment->getParent() && false == $comment->isCommentedByAdvertiser();
  755.         });
  756.     }
  757.     /**
  758.      * @return CommentByCustomer[]
  759.      */
  760.     public function getCommentsWithReply(): Collection
  761.     {
  762.         return $this->comments->filter(function (CommentByCustomer $comment): bool {
  763.             return null == $comment->getParent() && true == $comment->isCommentedByAdvertiser();
  764.         });
  765.     }
  766.     /**
  767.      * @return CommentByCustomer[]
  768.      */
  769.     public function getNewComments(): Collection
  770.     {
  771.         $weekAgo CarbonImmutable::now()->sub('7 days');
  772.         return $this->comments->filter(function (CommentByCustomer $comment) use ($weekAgo): bool {
  773.             return null == $comment->getParent()
  774.                 && (
  775.                     $comment->getCreatedAt() >= $weekAgo
  776.                     || null == $this->getCommentReply($comment)
  777.                 );
  778.         });
  779.     }
  780.     private function getCommentReply(CommentByCustomer $parent): ?CommentByCustomer
  781.     {
  782.         foreach ($this->comments as $comment)
  783.             if ($comment->getParent() == $parent)
  784.                 return $comment;
  785.         return null;
  786.     }
  787.     public function getOldComments(): Collection
  788.     {
  789.         $weekAgo CarbonImmutable::now()->sub('7 days');
  790.         return $this->comments->filter(function (CommentByCustomer $comment) use ($weekAgo): bool {
  791.             return null == $comment->getParent()
  792.                 && false == (
  793.                     $comment->getCreatedAt() >= $weekAgo
  794.                     || null == $this->getCommentReply($comment)
  795.                 );
  796.         });
  797.     }
  798.     public function getCommentFromUser(Customer $user): ?CommentByCustomer
  799.     {
  800.         foreach ($this->comments as $comment)
  801.             if (null == $comment->getParent() && null != $comment->getUser() && $user->getId() == $comment->getUser()->getId())
  802.                 return $comment;
  803.         return null;
  804.     }
  805.     //TODO return type
  806.     public function getCity(): City
  807.     {
  808.         return $this->city;
  809.     }
  810.     /**
  811.      * @return Station[]
  812.      */
  813.     public function getStations(): Collection
  814.     {
  815.         return $this->stations;
  816.     }
  817.     public function getMapCoordinate(): ?MapCoordinate
  818.     {
  819.         return $this->mapCoordinate;
  820.     }
  821.     public function getUpdatedAt(): ?\DateTimeImmutable
  822.     {
  823.         return $this->updatedAt;
  824.     }
  825.     public function setUpdatedAt(\DateTimeImmutable $updatedAt): void
  826.     {
  827.         $this->updatedAt $updatedAt;
  828.     }
  829.     public function getModerationStatus(): int
  830.     {
  831.         return $this->moderationStatus;
  832.     }
  833.     public function setModerationStatus(int $status): void
  834.     {
  835.         if (self::MODERATION_STATUS_APPROVED === $status) {
  836.             throw new \RuntimeException(sprintf('Use %s::passModeration() method instead', static::class));
  837.         }
  838.         $validStatuses = [self::MODERATION_STATUS_NOT_PASSEDself::MODERATION_STATUS_APPROVEDself::MODERATION_STATUS_WAITINGself::MODERATION_STATUS_REJECTED];
  839.         if (false === array_search($status$validStatuses))
  840.             throw new \LogicException('Trying to set an invalid moderation status');
  841.         $this->moderationStatus $status;
  842.     }
  843.     public function isModerationPassed(): bool
  844.     {
  845.         return $this->moderationStatus == self::MODERATION_STATUS_APPROVED;
  846.     }
  847.     public function isModerationWaiting(): bool
  848.     {
  849.         return $this->moderationStatus == self::MODERATION_STATUS_WAITING;
  850.     }
  851.     public function isModerationRejected(): bool
  852.     {
  853.         return $this->moderationStatus == self::MODERATION_STATUS_REJECTED;
  854.     }
  855.     public function passModeration(?ModerationRequest $moderationRequest null): void
  856.     {
  857.         $this->moderationStatus self::MODERATION_STATUS_APPROVED;
  858.         $func = static function ($kPhoto|Video $file) use ($moderationRequest): bool {
  859.             if (!$file->isConfirmed()) {
  860.                 $file->passModeration($moderationRequest);
  861.             }
  862.             return true;
  863.         };
  864.         $this->videos->forAll($func);
  865.     }
  866.     public function delete(): void
  867.     {
  868.         $this->deletePlacementHiding();
  869.         $this->deleteFromAdBoard();
  870.         $now = new \DateTimeImmutable('now');
  871.         $toDelete = [];
  872.         foreach ($this->topPlacements as $topPlacement) {
  873.             if ($topPlacement->getExpiresAt() > $now)
  874.                 $toDelete[] = $topPlacement;
  875.         }
  876.         foreach ($toDelete as $topPlacement)
  877.             $this->topPlacements->removeElement($topPlacement);
  878.         $this->setDeletedAt(Carbon::now());
  879.     }
  880.     public function deletePlacementHiding(): void
  881.     {
  882.         $this->placementHiding null;
  883.     }
  884.     public function deleteFromAdBoard(): void
  885.     {
  886.         $this->adBoardPlacement null;
  887.     }
  888.     //TODO return type
  889.     public function undoDelete(): void
  890.     {
  891.         $this->setDeletedAt(); // will pass null by default
  892.     }
  893.     //TODO return type
  894.     public function deleteFromTopPlacement(): void
  895.     {
  896.         //здесь нужна логика отмены конретного размещения
  897. //        $this->topPlacement = null;
  898.     }
  899.     public function getExpressPricing(): ?ExpressPricing
  900.     {
  901.         return $this->expressPricing;
  902.     }
  903.     public function getCarPricing(): ?CarPricing
  904.     {
  905.         return $this->carPricing;
  906.     }
  907.     //TODO return type
  908.     /**
  909.      * @return int[]
  910.      */
  911.     public function getClientTypes(): array
  912.     {
  913.         return $this->clientTypes ?? [];
  914.     }
  915.     /**
  916.      * @param int[] $clientTypes
  917.      */
  918.     public function setClientTypes(array $clientTypes): void
  919.     {
  920.         $this->clientTypes $clientTypes;
  921.     }
  922.     public function getMessengers(): ?Messengers
  923.     {
  924.         return $this->messengers;
  925.     }
  926.     public function getInactivatedAt(): ?\DateTimeImmutable
  927.     {
  928.         return $this->inactivatedAt;
  929.     }
  930.     public function setInactive(): void
  931.     {
  932.         $this->inactivatedAt CarbonImmutable::now();
  933.     }
  934.     public function undoInactive(): void
  935.     {
  936.         $this->inactivatedAt null;
  937.     }
  938.     public function isHidden(): bool
  939.     {
  940.         return null !== $this->getPlacementHiding();
  941.     }
  942.     public function getPlacementHiding(): ?PlacementHiding
  943.     {
  944.         return $this->placementHiding;
  945.     }
  946.     public function setPlacementHiding(PlacementHiding $placementHiding): void
  947.     {
  948.         $this->placementHiding $placementHiding;
  949.     }
  950.     public function hasSelfie(): bool
  951.     {
  952.         return $this->selfies->count() > 0;
  953.     }
  954.     public function hasVideo(): bool
  955.     {
  956.         return $this->videos->count() > 0;
  957.     }
  958.     public function isCommented(): bool
  959.     {
  960.         return $this->comments->count() > 0;
  961.     }
  962.     public function adminApprovalPhoto(): ?AdminApprovalPhoto
  963.     {
  964.         return $this->adminApprovalPhoto;
  965.     }
  966.     public function setAdminApprovalPhoto(?string $path): void
  967.     {
  968.         $this->adminApprovalPhoto $path ? new AdminApprovalPhoto($this$path) : null;
  969.     }
  970.     public function seo(): ?array
  971.     {
  972.         return $this->seo;
  973.     }
  974.     public function seoPhoneNumber(): ?string
  975.     {
  976.         return $this->seo['phone'] ?? null;
  977.     }
  978.     public function setSeoPhoneNumber(string $phoneNumber): void
  979.     {
  980.         if (null === $this->seo) {
  981.             $this->seo = [];
  982.         }
  983.         $this->seo['phone'] = $phoneNumber;
  984.     }
  985.     public function getPrimaryStation(): ?Station
  986.     {
  987.         $station $this->primaryStation ?? $this->getStations()->first();
  988.         if (false === $station) {
  989.             return null;
  990.         }
  991.         return $station;
  992.     }
  993.     public function setPrimaryStation(?Station $station): void
  994.     {
  995.         $this->primaryStation $station;
  996.         $this->normalizePrimaryStation();
  997.     }
  998.     public function getStationsSortedByPrimary(): array
  999.     {
  1000.         $stations $this->stations->toArray();
  1001.         if (!$this->primaryStation) {
  1002.             return $stations;
  1003.         }
  1004.         usort($stations, function (Station $aStation $b) {
  1005.             if ($a->getId() === $this->primaryStation->getId()) return -1;
  1006.             if ($b->getId() === $this->primaryStation->getId()) return 1;
  1007.             return 0;
  1008.         });
  1009.         return $stations;
  1010.     }
  1011.     public function getDeleteMode(): int
  1012.     {
  1013.         return $this->deleteMode;
  1014.     }
  1015.     public function setDeleteMode(int $deleteMode): self
  1016.     {
  1017.         $this->deleteMode $deleteMode;
  1018.         return $this;
  1019.     }
  1020.     public function isHardDeleted(): bool
  1021.     {
  1022.         return $this->deleteMode === 2;
  1023.     }
  1024. }