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(repositoryClassUserRepository::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'length12)]
  29. #[ORM\DiscriminatorMap(['advertiser' => Account\Advertiser::class, 'customer' => Account\Customer::class])]
  30. abstract class User implements UserInterfacePasswordAuthenticatedUserInterface\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'length180uniquetrue)]
  40.     #[Assert\NotBlank(groups: ['Registration'])]
  41.     #[Assert\Email(groups: ['Registration'])]
  42.     private ?string $email null;
  43.     #[ORM\Column(type'string'length100)]
  44.     #[Assert\NotBlank(groups: ['Registration'])]
  45.     #[Assert\Length(max64groups: ['Registration'])]
  46.     #[Groups(['comments'])]
  47.     private ?string $nickName null;
  48.     #[ORM\Column(type'text'nullabletrue)]
  49.     private ?string $notes null;
  50.     #[ORM\Column(name'country_code'type'string'length2)]
  51.     private string $country;
  52.     #[ORM\JoinColumn(name'city_id'referencedColumnName'id')]
  53.     #[ORM\ManyToOne(targetEntityCity::class)]
  54.     private ?City $city null;
  55.     #[ORM\OneToOne(targetEntityAvatar::class, mappedBy'user'cascade: ['all'], orphanRemovaltrue)]
  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'length255nullabletrue)]
  66.     private ?string $confirmationCode;
  67.     #[ORM\Column(type'string'length255nullabletrue)]
  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'length3)]
  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(targetEntityAccountEnrollment::class, mappedBy'account')]
  87.     private Collection $enrollments;
  88.     /** @var AccountCharge[] */
  89.     #[ORM\OneToMany(targetEntityAccountCharge::class, mappedBy'account')]
  90.     private Collection $charges;
  91.     /** @var AccountTransaction[] */
  92.     #[ORM\OneToMany(targetEntityAccountTransaction::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'nullabletrue)]
  97.     private ?\DateTimeInterface $updated;
  98.     #[ORM\Column(name'balance_low_notified_at'type'datetime'nullabletrue)]
  99.     private ?\DateTimeInterface $lowBalanceNotifiedAt;
  100.     #[ORM\Column(name'ban'type'string'length5nullabletrue)]
  101.     private ?string $ban null;
  102.     #[ORM\OneToOne(targetEntityOfferBarHidden::class, cascade: ['all'], mappedBy'account')]
  103.     private ?OfferBarHidden $offerBarHidden;
  104.     public function __construct()
  105.     {
  106.         $this->roles = [self::ROLE_USER];
  107.         $this->enabled false;
  108.         $this->enrollments = new ArrayCollection();
  109.         $this->charges = new ArrayCollection();
  110.         $this->transactions = new ArrayCollection();
  111.         //TODO temp
  112.         $this->created = new \DateTime();
  113.         $this->updated = new \DateTime();
  114.     }
  115.     public function getId(): ?int
  116.     {
  117.         return $this->id;
  118.     }
  119.     public function getEmail(): ?string
  120.     {
  121.         return $this->email;
  122.     }
  123.     public function setEmail(string $email): void
  124.     {
  125.         $this->email $email;
  126.     }
  127.     public function getNickName(): ?string
  128.     {
  129.         return $this->nickName;
  130.     }
  131.     public function setNickName(string $nickName): void
  132.     {
  133.         $this->nickName $nickName;
  134.     }
  135.     public function getCountry(): ?string
  136.     {
  137.         return $this->country;
  138.     }
  139.     public function setCountry($country): void
  140.     {
  141.         $this->country $country;
  142.     }
  143.     public function getCity(): ?City
  144.     {
  145.         return $this->city;
  146.     }
  147.     public function setCity(City $city): void
  148.     {
  149.         $this->city $city;
  150.         $this->country $city->getCountryCode();
  151.     }
  152.     /**
  153.      * A visual identifier that represents this user.
  154.      *
  155.      * @see UserInterface
  156.      */
  157.     public function getUsername(): string
  158.     {
  159.         return (string)$this->email;
  160.     }
  161.     public function getUserIdentifier(): string
  162.     {
  163.         return $this->getUsername();
  164.     }
  165.     /**
  166.      * @see UserInterface
  167.      */
  168.     public function getRoles(): array
  169.     {
  170.         $roles $this->roles;
  171.         // guarantee every user at least has ROLE_USER
  172.         $roles[] = 'ROLE_USER';
  173.         return array_unique($roles);
  174.     }
  175.     public function setRoles(array $roles): self
  176.     {
  177.         $this->roles $roles;
  178.         return $this;
  179.     }
  180.     /**
  181.      * @see UserInterface
  182.      */
  183.     public function getPassword(): string
  184.     {
  185.         return (string)$this->password;
  186.     }
  187.     public function setPassword(string $password): void
  188.     {
  189.         $this->password $password;
  190.     }
  191.     public function getPlainPassword(): ?string
  192.     {
  193.         return $this->plainPassword;
  194.     }
  195.     public function setPlainPassword(string $plainPassword): void
  196.     {
  197.         $this->plainPassword $plainPassword;
  198.     }
  199.     public function getConfirmationCode(): string
  200.     {
  201.         return $this->confirmationCode;
  202.     }
  203.     public function setConfirmationCode(string $confirmationCode): void
  204.     {
  205.         $this->confirmationCode $confirmationCode;
  206.     }
  207.     public function getSmscCode(): string
  208.     {
  209.         return $this->smscCode;
  210.     }
  211.     public function setSmscCode(string $smscCode): void
  212.     {
  213.         $this->smscCode $smscCode;
  214.     }
  215.     public function isEnabled(): bool
  216.     {
  217.         return $this->enabled;
  218.     }
  219.     public function setEnabled(bool $enabled): void
  220.     {
  221.         $this->enabled $enabled;
  222.     }
  223.     public function isTrusted(): bool
  224.     {
  225.         return $this->trusted;
  226.     }
  227.     public function setTrusted(bool $trusted): void
  228.     {
  229.         $this->trusted $trusted;
  230.     }
  231.     public function isFullRegistered(): bool
  232.     {
  233.         return $this->fullRegistered;
  234.     }
  235.     public function setFullRegistered(bool $fullRegistered): void
  236.     {
  237.         $this->fullRegistered $fullRegistered;
  238.     }
  239.     /**
  240.      * Зачисляет деньги на счет аккаунта
  241.      *
  242.      * @param Money $toEnroll
  243.      *
  244.      * @throws \DomainException Если указана отрицательная или нулевая сумма
  245.      * @throws CurrencyMismatchException Если валюты баланса и суммы зачисления не совпадают
  246.      */
  247.     public function enroll(Money $toEnroll): void
  248.     {
  249.         if ($toEnroll->isNegative() || $toEnroll->isZero()) {
  250.             throw new \DomainException('Can not enroll negative or zero amount.');
  251.         }
  252.         $currentBalance $this->getCurrentBalance();
  253.         if (!$currentBalance->isSameCurrency($toEnroll)) {
  254.             throw new CurrencyMismatchException();
  255.         }
  256.         $newBalance $currentBalance->add($toEnroll);
  257.         $this->credits $newBalance->getAmount();
  258.     }
  259.     /**
  260.      * Списывает деньги со счета аккаунта
  261.      *
  262.      * @param Money $toCharge
  263.      * @param bool  $withOverdraft Возможность делать отрицательный баланс для ручных списаний
  264.      *
  265.      * @throws \DomainException Если указана отрицательная или нулевая сумма
  266.      * @throws CurrencyMismatchException Если валюты баланса и суммы списания не совпадают
  267.      * @throws NotEnoughMoneyException Если на счету недостаточно средств
  268.      */
  269.     public function charge(Money $toChargebool $withOverdraft false): void
  270.     {
  271.         if ($toCharge->isNegative() || $toCharge->isZero()) {
  272.             throw new \DomainException('Can not charge negative or zero amount.');
  273.         }
  274.         $currentBalance $this->getCurrentBalance();
  275.         if (!$currentBalance->isSameCurrency($toCharge)) {
  276.             throw new CurrencyMismatchException();
  277.         }
  278.         if ($currentBalance->lessThan($toCharge) && !$withOverdraft) {
  279.             throw new NotEnoughMoneyException();
  280.         }
  281.         $newBalance $currentBalance->subtract($toCharge);
  282.         $this->credits $newBalance->getAmount();
  283.     }
  284.     public function getCurrentBalance(): Money
  285.     {
  286.         return new Money($this->credits, new Currency($this->currencyCode));
  287.     }
  288.     public function getCurrencyCode(): string
  289.     {
  290.         return $this->currencyCode;
  291.     }
  292.     public function resolveCurrency(CountryCurrencyResolver $currencyResolver): void
  293.     {
  294.         $this->currencyCode $currencyResolver->getCurrencyFor($this->country);
  295.     }
  296.     /**
  297.      * @return AccountEnrollment[]
  298.      */
  299.     public function getEnrollments(): Collection
  300.     {
  301.         return $this->enrollments;
  302.     }
  303.     /**
  304.      * @return AccountCharge[]
  305.      */
  306.     public function getCharges(): Collection
  307.     {
  308.         return $this->charges;
  309.     }
  310.     /**
  311.      * @return AccountTransaction[]
  312.      */
  313.     public function getTransactions(): Collection
  314.     {
  315.         return $this->transactions;
  316.     }
  317.     /**
  318.      * @see UserInterface
  319.      */
  320.     public function getSalt(): void
  321.     {
  322.         // not needed when using the "bcrypt" algorithm in security.yaml
  323.     }
  324.     /**
  325.      * @see UserInterface
  326.      */
  327.     public function eraseCredentials(): void
  328.     {
  329.         // If you store any temporary, sensitive data on the user, clear it here
  330.         $this->plainPassword null;
  331.     }
  332.     public function getCreated(): \DateTimeInterface
  333.     {
  334.         return $this->created;
  335.     }
  336.     /**
  337.      * @inheritDoc
  338.      */
  339.     public function serialize()
  340.     {
  341.         return \serialize([
  342.             $this->id,
  343.             $this->email,
  344.             $this->password,
  345.             $this->roles,
  346.             $this->enabled,
  347.         ]);
  348.     }
  349.     /**
  350.      * @inheritDoc
  351.      */
  352.     public function unserialize($serialized): void
  353.     {
  354.         list(
  355.             $this->id,
  356.             $this->email,
  357.             $this->password,
  358.             $this->roles,
  359.             $this->enabled
  360.             ) = \unserialize($serialized, ['allowed_classes' => false]);
  361.     }
  362.     public function getNotes(): ?string
  363.     {
  364.         return $this->notes;
  365.     }
  366.     public function setNotes(?string $notes): void
  367.     {
  368.         $this->notes $notes;
  369.     }
  370.     public function isBanned(): bool
  371.     {
  372.         return null != $this->ban;
  373.     }
  374.     public function getBan(): ?string
  375.     {
  376.         return $this->ban;
  377.     }
  378.     public function setBan(?string $ban): void
  379.     {
  380.         $this->ban $ban;
  381.     }
  382.     public function isLowBalanceNotified(): bool
  383.     {
  384.         return $this->lowBalanceNotifiedAt != null;
  385.     }
  386.     public function setLowBalanceNotified(?\DateTimeInterface $dateTime): void
  387.     {
  388.         $this->lowBalanceNotifiedAt $dateTime;
  389.     }
  390.     public function getAvatar(): ?Avatar
  391.     {
  392.         return $this->avatar;
  393.     }
  394.     public function setAvatar(string $path): void
  395.     {
  396.         $this->avatar = new Avatar($this$path);
  397.     }
  398.     public function getPostRegistrationStep(): int
  399.     {
  400.         return $this->postRegistrationStep;
  401.     }
  402.     public function setPostRegistrationStep(int $postRegistrationStep): void
  403.     {
  404.         $this->postRegistrationStep $postRegistrationStep;
  405.     }
  406.     public function offerBarHidden(): ?OfferBarHidden
  407.     {
  408.         return $this->offerBarHidden;
  409.     }
  410.     public function setOfferBarHidden(): void
  411.     {
  412.         if (null !== $this->offerBarHidden) {
  413.             return;
  414.         }
  415.         $this->offerBarHidden = new OfferBarHidden($this);
  416.     }
  417. }