src/Entity/User.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\Entity;
  3. use App\Entity\Account\Avatar;
  4. use App\Entity\Location\City;
  5. use App\Entity\Sales\AccountCharge;
  6. use App\Entity\Sales\AccountEnrollment;
  7. use App\Entity\Sales\AccountTransaction;
  8. use App\PaymentProcessing\Exception\CurrencyMismatchException;
  9. use App\PaymentProcessing\Exception\NotEnoughMoneyException;
  10. use App\Repository\UserRepository;
  11. use App\Service\CountryCurrencyResolver;
  12. use Doctrine\Common\Collections\ArrayCollection;
  13. use Doctrine\Common\Collections\Collection;
  14. use Doctrine\ORM\Mapping as ORM;
  15. use Money\Currency;
  16. use Money\Money;
  17. use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
  18. use Symfony\Component\Serializer\Annotation\Groups;
  19. use Symfony\Component\Validator\Constraints as Assert;
  20. //use Vich\UploaderBundle\Mapping\Annotation as Vich;
  21. use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
  22. use Symfony\Component\Security\Core\User\UserInterface;
  23. #[ORM\Entity(repositoryClass: UserRepository::class)]
  24. #[UniqueEntity(fields: ['email'], groups: ['Registration'])]
  25. #[UniqueEntity(fields: ['nickName'], groups: ['Registration'])] // //Vich\Uploadable
  26. #[ORM\HasLifecycleCallbacks]
  27. #[ORM\InheritanceType('SINGLE_TABLE')]
  28. #[ORM\DiscriminatorColumn(name: 'type', type: 'string', length: 12)]
  29. #[ORM\DiscriminatorMap(['advertiser' => Account\Advertiser::class, 'customer' => Account\Customer::class])]
  30. abstract class User implements UserInterface, PasswordAuthenticatedUserInterface, \Serializable
  31. {
  32.     public const ROLE_USER = 'ROLE_USER';
  33.     #[ORM\Id]
  34.     #[ORM\GeneratedValue]
  35.     #[ORM\Column(type: 'integer')]
  36.     #[Groups(['comments'])]
  37.     private int $id;
  38.     
  39.     #[ORM\Column(type: 'string', length: 180, unique: true)]
  40.     #[Assert\NotBlank(groups: ['Registration'])]
  41.     #[Assert\Email(groups: ['Registration'])]
  42.     private ?string $email = null;
  43.     #[ORM\Column(type: 'string', length: 100)]
  44.     #[Assert\NotBlank(groups: ['Registration'])]
  45.     #[Assert\Length(max: 64, groups: ['Registration'])]
  46.     #[Groups(['comments'])]
  47.     private ?string $nickName = null;
  48.     #[ORM\Column(type: 'text', nullable: true)]
  49.     private ?string $notes = null;
  50.     #[ORM\Column(name: 'country_code', type: 'string', length: 2)]
  51.     private string $country;
  52.     #[ORM\JoinColumn(name: 'city_id', referencedColumnName: 'id')]
  53.     #[ORM\ManyToOne(targetEntity: City::class)]
  54.     private ?City $city = null;
  55.     #[ORM\OneToOne(targetEntity: Avatar::class, mappedBy: 'user', cascade: ['all'], orphanRemoval: true)]
  56.     #[Groups(['comments'])]
  57.     protected ?Avatar $avatar;
  58.     #[ORM\Column(type: 'json')]
  59.     private array $roles = [];
  60.     /** The hashed password*/
  61.     #[ORM\Column(type: 'string')]
  62.     private string $password;
  63.     #[Assert\NotBlank(groups: ['Registration'])]
  64.     private ?string $plainPassword = null;
  65.     #[ORM\Column(type: 'string', length: 255, nullable: true)]
  66.     private ?string $confirmationCode;
  67.     #[ORM\Column(type: 'string', length: 255, nullable: true)]
  68.     private ?string $smscCode;
  69.     #[ORM\Column(type: 'boolean')]
  70.     private bool $enabled;
  71.     #[ORM\Column(type: 'boolean')]
  72.     private bool $trusted = false;
  73.     #[ORM\Column(name: 'credits', type: 'integer')]
  74.     private int $credits = 0;
  75.     /**
  76.      * Валюта для финансовых операций аккаунта.
  77.      * Устанавливается при регистрации в зависимости от выбранной страны, и не может быть изменена через кабинет.
  78.      */
  79.     #[ORM\Column(name: 'currency_code', type: 'string', length: 3)]
  80.     private string $currencyCode;
  81.     #[ORM\Column(type: 'boolean', options: ['default' => 1])]
  82.     private bool $fullRegistered = true;
  83.     #[ORM\Column(type: 'integer', options: ['default' => 0])]
  84.     private int $postRegistrationStep = 0;
  85.     /** @var AccountEnrollment[] */
  86.     #[ORM\OneToMany(targetEntity: AccountEnrollment::class, mappedBy: 'account')]
  87.     private Collection $enrollments;
  88.     /** @var AccountCharge[] */
  89.     #[ORM\OneToMany(targetEntity: AccountCharge::class, mappedBy: 'account')]
  90.     private Collection $charges;
  91.     /** @var AccountTransaction[] */
  92.     #[ORM\OneToMany(targetEntity: AccountTransaction::class, mappedBy: 'account')]
  93.     private Collection $transactions;
  94.     #[ORM\Column(name: 'created', type: 'datetime')]
  95.     private \DateTimeInterface $created;
  96.     #[ORM\Column(name: 'updated', type: 'datetime', nullable: true)]
  97.     private ?\DateTimeInterface $updated;
  98.     #[ORM\Column(name: 'balance_low_notified_at', type: 'datetime', nullable: true)]
  99.     private ?\DateTimeInterface $lowBalanceNotifiedAt;
  100.     #[ORM\Column(name: 'mautic_rebill_insufficient_funds_sent_at', type: 'datetimetz_immutable', nullable: true)]
  101.     private ?\DateTimeImmutable $mauticRebillInsufficientFundsSentAt = null;
  102.     #[ORM\Column(name: 'mautic_not_used_paid_placement_30d_sent_at', type: 'datetimetz_immutable', nullable: true)]
  103.     private ?\DateTimeImmutable $mauticNotUsedPaidPlacement30dSentAt = null;
  104.     #[ORM\Column(name: 'mautic_not_used_paid_placement_30d_bonus_enrolled_at', type: 'datetimetz_immutable', nullable: true)]
  105.     private ?\DateTimeImmutable $mauticNotUsedPaidPlacement30dBonusEnrolledAt = null;
  106.     #[ORM\Column(name: 'last_login_at', type: 'datetimetz_immutable', nullable: true)]
  107.     private ?\DateTimeImmutable $lastLoginAt = null;
  108.     #[ORM\Column(name: 'last_paid_placement_at', type: 'datetimetz_immutable', nullable: true)]
  109.     private ?\DateTimeImmutable $lastPaidPlacementAt = null;
  110.     #[ORM\Column(name: 'ban', type: 'string', length: 5, nullable: true)]
  111.     private ?string $ban = null;
  112.     #[ORM\OneToOne(targetEntity: OfferBarHidden::class, cascade: ['all'], mappedBy: 'account')]
  113.     private ?OfferBarHidden $offerBarHidden;
  114.     public function __construct()
  115.     {
  116.         $this->roles = [self::ROLE_USER];
  117.         $this->enabled = false;
  118.         $this->enrollments = new ArrayCollection();
  119.         $this->charges = new ArrayCollection();
  120.         $this->transactions = new ArrayCollection();
  121.         //TODO temp
  122.         $this->created = new \DateTime();
  123.         $this->updated = new \DateTime();
  124.     }
  125.     public function getId(): ?int
  126.     {
  127.         return $this->id;
  128.     }
  129.     public function getEmail(): ?string
  130.     {
  131.         return $this->email;
  132.     }
  133.     public function setEmail(string $email): void
  134.     {
  135.         $this->email = $email;
  136.     }
  137.     public function getNickName(): ?string
  138.     {
  139.         return $this->nickName;
  140.     }
  141.     public function setNickName(string $nickName): void
  142.     {
  143.         $this->nickName = $nickName;
  144.     }
  145.     public function getCountry(): ?string
  146.     {
  147.         return $this->country;
  148.     }
  149.     public function setCountry($country): void
  150.     {
  151.         $this->country = $country;
  152.     }
  153.     public function getCity(): ?City
  154.     {
  155.         return $this->city;
  156.     }
  157.     public function setCity(City $city): void
  158.     {
  159.         $this->city = $city;
  160.         $this->country = $city->getCountryCode();
  161.     }
  162.     /**
  163.      * A visual identifier that represents this user.
  164.      *
  165.      * @see UserInterface
  166.      */
  167.     public function getUsername(): string
  168.     {
  169.         return (string)$this->email;
  170.     }
  171.     public function getUserIdentifier(): string
  172.     {
  173.         return $this->getUsername();
  174.     }
  175.     /**
  176.      * @see UserInterface
  177.      */
  178.     public function getRoles(): array
  179.     {
  180.         $roles = $this->roles;
  181.         // guarantee every user at least has ROLE_USER
  182.         $roles[] = 'ROLE_USER';
  183.         return array_unique($roles);
  184.     }
  185.     public function setRoles(array $roles): self
  186.     {
  187.         $this->roles = $roles;
  188.         return $this;
  189.     }
  190.     /**
  191.      * @see UserInterface
  192.      */
  193.     public function getPassword(): string
  194.     {
  195.         return (string)$this->password;
  196.     }
  197.     public function setPassword(string $password): void
  198.     {
  199.         $this->password = $password;
  200.     }
  201.     public function getPlainPassword(): ?string
  202.     {
  203.         return $this->plainPassword;
  204.     }
  205.     public function setPlainPassword(string $plainPassword): void
  206.     {
  207.         $this->plainPassword = $plainPassword;
  208.     }
  209.     public function getConfirmationCode(): string
  210.     {
  211.         return $this->confirmationCode;
  212.     }
  213.     public function setConfirmationCode(string $confirmationCode): void
  214.     {
  215.         $this->confirmationCode = $confirmationCode;
  216.     }
  217.     public function getSmscCode(): string
  218.     {
  219.         return $this->smscCode;
  220.     }
  221.     public function setSmscCode(string $smscCode): void
  222.     {
  223.         $this->smscCode = $smscCode;
  224.     }
  225.     public function isEnabled(): bool
  226.     {
  227.         return $this->enabled;
  228.     }
  229.     public function setEnabled(bool $enabled): void
  230.     {
  231.         $this->enabled = $enabled;
  232.     }
  233.     public function isTrusted(): bool
  234.     {
  235.         return $this->trusted;
  236.     }
  237.     public function setTrusted(bool $trusted): void
  238.     {
  239.         $this->trusted = $trusted;
  240.     }
  241.     public function isFullRegistered(): bool
  242.     {
  243.         return $this->fullRegistered;
  244.     }
  245.     public function setFullRegistered(bool $fullRegistered): void
  246.     {
  247.         $this->fullRegistered = $fullRegistered;
  248.     }
  249.     /**
  250.      * Зачисляет деньги на счет аккаунта
  251.      *
  252.      * @param Money $toEnroll
  253.      *
  254.      * @throws \DomainException Если указана отрицательная или нулевая сумма
  255.      * @throws CurrencyMismatchException Если валюты баланса и суммы зачисления не совпадают
  256.      */
  257.     public function enroll(Money $toEnroll): void
  258.     {
  259.         if ($toEnroll->isNegative() || $toEnroll->isZero()) {
  260.             throw new \DomainException('Can not enroll negative or zero amount.');
  261.         }
  262.         $currentBalance = $this->getCurrentBalance();
  263.         if (!$currentBalance->isSameCurrency($toEnroll)) {
  264.             throw new CurrencyMismatchException();
  265.         }
  266.         $newBalance = $currentBalance->add($toEnroll);
  267.         $this->credits = $newBalance->getAmount();
  268.     }
  269.     /**
  270.      * Списывает деньги со счета аккаунта
  271.      *
  272.      * @param Money $toCharge
  273.      * @param bool  $withOverdraft Возможность делать отрицательный баланс для ручных списаний
  274.      *
  275.      * @throws \DomainException Если указана отрицательная или нулевая сумма
  276.      * @throws CurrencyMismatchException Если валюты баланса и суммы списания не совпадают
  277.      * @throws NotEnoughMoneyException Если на счету недостаточно средств
  278.      */
  279.     public function charge(Money $toCharge, bool $withOverdraft = false): void
  280.     {
  281.         if ($toCharge->isNegative() || $toCharge->isZero()) {
  282.             throw new \DomainException('Can not charge negative or zero amount.');
  283.         }
  284.         $currentBalance = $this->getCurrentBalance();
  285.         if (!$currentBalance->isSameCurrency($toCharge)) {
  286.             throw new CurrencyMismatchException();
  287.         }
  288.         if ($currentBalance->lessThan($toCharge) && !$withOverdraft) {
  289.             throw new NotEnoughMoneyException();
  290.         }
  291.         $newBalance = $currentBalance->subtract($toCharge);
  292.         $this->credits = $newBalance->getAmount();
  293.     }
  294.     public function getCurrentBalance(): Money
  295.     {
  296.         return new Money($this->credits, new Currency($this->currencyCode));
  297.     }
  298.     public function getCurrencyCode(): string
  299.     {
  300.         return $this->currencyCode;
  301.     }
  302.     public function resolveCurrency(CountryCurrencyResolver $currencyResolver): void
  303.     {
  304.         $this->currencyCode = $currencyResolver->getCurrencyFor($this->country);
  305.     }
  306.     /**
  307.      * @return AccountEnrollment[]
  308.      */
  309.     public function getEnrollments(): Collection
  310.     {
  311.         return $this->enrollments;
  312.     }
  313.     /**
  314.      * @return AccountCharge[]
  315.      */
  316.     public function getCharges(): Collection
  317.     {
  318.         return $this->charges;
  319.     }
  320.     /**
  321.      * @return AccountTransaction[]
  322.      */
  323.     public function getTransactions(): Collection
  324.     {
  325.         return $this->transactions;
  326.     }
  327.     /**
  328.      * @see UserInterface
  329.      */
  330.     public function getSalt(): void
  331.     {
  332.         // not needed when using the "bcrypt" algorithm in security.yaml
  333.     }
  334.     /**
  335.      * @see UserInterface
  336.      */
  337.     public function eraseCredentials(): void
  338.     {
  339.         // If you store any temporary, sensitive data on the user, clear it here
  340.         $this->plainPassword = null;
  341.     }
  342.     public function getCreated(): \DateTimeInterface
  343.     {
  344.         return $this->created;
  345.     }
  346.     /**
  347.      * @inheritDoc
  348.      */
  349.     public function serialize()
  350.     {
  351.         return \serialize([
  352.             $this->id,
  353.             $this->email,
  354.             $this->password,
  355.             $this->roles,
  356.             $this->enabled,
  357.         ]);
  358.     }
  359.     /**
  360.      * @inheritDoc
  361.      */
  362.     public function unserialize($serialized): void
  363.     {
  364.         list(
  365.             $this->id,
  366.             $this->email,
  367.             $this->password,
  368.             $this->roles,
  369.             $this->enabled
  370.             ) = \unserialize($serialized, ['allowed_classes' => false]);
  371.     }
  372.     public function getNotes(): ?string
  373.     {
  374.         return $this->notes;
  375.     }
  376.     public function setNotes(?string $notes): void
  377.     {
  378.         $this->notes = $notes;
  379.     }
  380.     public function isBanned(): bool
  381.     {
  382.         return null != $this->ban;
  383.     }
  384.     public function getBan(): ?string
  385.     {
  386.         return $this->ban;
  387.     }
  388.     public function setBan(?string $ban): void
  389.     {
  390.         $this->ban = $ban;
  391.     }
  392.     public function isLowBalanceNotified(): bool
  393.     {
  394.         return $this->lowBalanceNotifiedAt != null;
  395.     }
  396.     public function setLowBalanceNotified(?\DateTimeInterface $dateTime): void
  397.     {
  398.         $this->lowBalanceNotifiedAt = $dateTime;
  399.     }
  400.     public function getMauticRebillInsufficientFundsSentAt(): ?\DateTimeImmutable
  401.     {
  402.         return $this->mauticRebillInsufficientFundsSentAt;
  403.     }
  404.     public function setMauticRebillInsufficientFundsSentAt(?\DateTimeImmutable $sentAt): void
  405.     {
  406.         $this->mauticRebillInsufficientFundsSentAt = $sentAt;
  407.     }
  408.     public function getMauticNotUsedPaidPlacement30dSentAt(): ?\DateTimeImmutable
  409.     {
  410.         return $this->mauticNotUsedPaidPlacement30dSentAt;
  411.     }
  412.     public function setMauticNotUsedPaidPlacement30dSentAt(?\DateTimeImmutable $sentAt): void
  413.     {
  414.         $this->mauticNotUsedPaidPlacement30dSentAt = $sentAt;
  415.     }
  416.     public function getMauticNotUsedPaidPlacement30dBonusEnrolledAt(): ?\DateTimeImmutable
  417.     {
  418.         return $this->mauticNotUsedPaidPlacement30dBonusEnrolledAt;
  419.     }
  420.     public function setMauticNotUsedPaidPlacement30dBonusEnrolledAt(?\DateTimeImmutable $enrolledAt): void
  421.     {
  422.         $this->mauticNotUsedPaidPlacement30dBonusEnrolledAt = $enrolledAt;
  423.     }
  424.     public function getLastLoginAt(): ?\DateTimeImmutable
  425.     {
  426.         return $this->lastLoginAt;
  427.     }
  428.     public function setLastLoginAt(\DateTimeImmutable $lastLoginAt): void
  429.     {
  430.         $this->lastLoginAt = $lastLoginAt;
  431.     }
  432.     public function getLastPaidPlacementAt(): ?\DateTimeImmutable
  433.     {
  434.         return $this->lastPaidPlacementAt;
  435.     }
  436.     public function setLastPaidPlacementAt(\DateTimeImmutable $lastPaidPlacementAt): void
  437.     {
  438.         $this->lastPaidPlacementAt = $lastPaidPlacementAt;
  439.     }
  440.     public function getAvatar(): ?Avatar
  441.     {
  442.         return $this->avatar;
  443.     }
  444.     public function setAvatar(string $path): void
  445.     {
  446.         $this->avatar = new Avatar($this, $path);
  447.     }
  448.     public function getPostRegistrationStep(): int
  449.     {
  450.         return $this->postRegistrationStep;
  451.     }
  452.     public function setPostRegistrationStep(int $postRegistrationStep): void
  453.     {
  454.         $this->postRegistrationStep = $postRegistrationStep;
  455.     }
  456.     public function offerBarHidden(): ?OfferBarHidden
  457.     {
  458.         return $this->offerBarHidden;
  459.     }
  460.     public function setOfferBarHidden(): void
  461.     {
  462.         if (null !== $this->offerBarHidden) {
  463.             return;
  464.         }
  465.         $this->offerBarHidden = new OfferBarHidden($this);
  466.     }
  467. }