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